-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathITimg.js
1850 lines (1618 loc) · 68.2 KB
/
ITimg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
importClass(android.os.Build);
importClass(android.graphics.Color);
importClass(org.opencv.android.Utils);
importClass(android.graphics.Bitmap);
importClass(java.util.List);
importClass(org.opencv.imgproc.Imgproc);
importClass(org.opencv.core.Mat);
importClass(org.opencv.core.Size);
importClass(org.opencv.core.MatOfKeyPoint);
importClass(org.opencv.core.MatOfPoint2f);
importClass(org.opencv.features2d.SIFT);
if (package_path == undefined) {
var package_path = context.getExternalFilesDir(null).getAbsolutePath();
}
let ITimg = {};
//识别的小图,ocr文字
ITimg.elements = {
"content": "",
"number": 0
};
ITimg.results = false;
//整数原子变量,确保计时准确
ITimg.timer_lock = threads.atomic(0);
ITimg.setting = {
"图片监测": false,
"full_resolution": false,
"defaultOcr": "XiaoYueOCR",
"截图方式": "辅助",
"异常超时": 5,
"调试": false,
"图片代理": true,
"自动授权截图": true,
}
/**
* 初始化ITimg识别函数的一些参数默认值,申请截图权限,设置异常超时
* @param {object} picture_default - 设置picture函数的参数默认值
* @param {object} ocr_default - 设置OCR文字识别函数的参数默认值
*/
function Prepare(picture_default, ocr_default, outline_default, matchFeatures_default, setting) {
let context;
(function() {
context = this;
}());
if (this === context) {
return new Prepare(picture_default, ocr_default, outline_default, matchFeatures_default);
}
if (setting) {
console.verbose("更新ITimg设置值");
for (let setup in ITimg.setting) {
if (setting.hasOwnProperty(setup)) {
ITimg.setting[setup] = setting[setup];
}
}
}
if (!picture_default) {
picture_default = {};
}
if (!ocr_default) {
ocr_default = {};
}
if (!outline_default) {
outline_default = {};
}
if (!matchFeatures_default) {
matchFeatures_default = {}
}
//属性为undefined时不会在日志中显示
this.picture = {
timing: picture_default.timing || 0,
area: picture_default.area || "全屏",
nods: picture_default.nods || 0,
threshold: picture_default.threshold || 0.8,
grayscale: picture_default.grayscale || undefined,
resolution: picture_default.resolution || ITimg.setting.full_resolution || undefined,
small_image_catalog: picture_default.small_image_catalog || "./library/gallery/",
matchTemplate_max: picture_default.matchTemplate_max || 5,
};
this.ocr = {
timing: ocr_default.timing || 0,
area: ocr_default.area || "全屏",
nods: ocr_default.nods || 0,
part: ocr_default.part || false,
similar: ocr_default.similar || 0.75,
saveSmallImg: ocr_default.saveSmallImg,
picture_failed_further: ocr_default.picture_failed_further,
resolution: ocr_default.resolution || undefined,
ocr_type: ocr_default.ocr_type || ITimg.setting.defaultOcr,
visualization: ocr_default.visualization,
correction_path: ocr_default.correction_path || undefined,
};
this.outline = {
type: outline_default.type || "BINARY",
size: outline_default.size || 10,
isdilate: outline_default.isdilate,
timing: outline_default.timing || 0,
area: outline_default.area || "全屏",
nods: outline_default.nods || 0,
}
this.matchFeatures = {
timing: matchFeatures_default.timing || 0,
nods: matchFeatures_default.nods || 0,
area: matchFeatures_default.area || "全屏",
threshold: matchFeatures_default.threshold || 0.8,
filter_w: matchFeatures_default.filter_w || 10,
filter_h: matchFeatures_default.filter_h || 10,
scale: matchFeatures_default.scale || 1,
matcher: matchFeatures_default.matcher || "BRUTEFORCE_L1",
visualization: matchFeatures_default.visualization || true,
saveSmallImg: matchFeatures_default.saveSmallImg,
picture_failed_further: matchFeatures_default.picture_failed_further,
small_image_catalog: matchFeatures_default.small_image_catalog || "./library/gallery/template/"
}
files.ensureDir(package_path + "/logs/binarized_contour/");
files.create(package_path + "/logs/binarized_contour/.nomedia")
files.ensureDir(package_path + "/logs/captureScreen/");
files.ensureDir(package_path + "/logs/matchFeatures/");
files.create(package_path + "/logs/matchFeatures/.nomedia")
try {
ITimg.gallery_info = JSON.parse(files.read(package_path + this.matchFeatures.small_image_catalog + "gallery_info.json"), (encoding = "utf-8"));
} catch (e) {
ITimg.gallery_info = {
"分辨率": {
"w": width,
"h": height
},
"服务器": "简中服"
}
}
ITimg.language = ITimg.gallery_info.服务器;
ITimg.default_list = this;
$debug.setMemoryLeakDetectionEnabled(true);
if (ITimg.setting.图片监测 && (app.autojs.versionCode > 8082200)) {
ITimg.permission_detection = false;
setTimeout(function() {
ITimg.permission_detection = true;
}, 60000 * 15);
}
log("图库全分辨率兼容:" + this.picture.resolution)
if (this.picture.resolution) {
log("缩放参数:" + scaleSet(2, undefined, true))
}
if (!$images.getScreenCaptureOptions()) {
switch (ITimg.setting.截图方式) {
case "辅助":
申请截图();
break;
case "Shizuku":
$shell.setDefaultOptions({
adb: true,
});
break;
}
if (ITimg.setting.异常超时) {
threads.start(function() {
let is = (ITimg.setting.异常超时 === true) ? 5 : ITimg.setting.异常超时;
console.info("异常界面超时暂停处理,分钟:" + is);
fn = function() {
if (ITimg.timer_lock == is) {
toast("程序在" + (is / 2) + "分钟内未能判断当前界面,状态异常,将暂停并返回桌面")
console.error("程序在" + (is / 2) + "分钟内未能判断当前界面,状态异常,将暂停并返回桌面")
tool.Floating_emit("暂停", "状态异常");
} else if (ITimg.elements.number > 150) {
toast("程序在当前界面连续识别到同一内容" + ITimg.elements.number + "次,状态异常,将暂停并返回桌面")
console.error("程序在当前界面连续识别到同一内容" + ITimg.elements.number + "次,状态异常,将暂停并返回桌面")
tool.Floating_emit("暂停", "状态异常");
}
if (ITimg.timer_lock == "暂停") {
return
}
if (ITimg.results == null || ITimg.results == false) {
ITimg.timer_lock.getAndIncrement();
} else {
ITimg.timer_lock = threads.atomic(0)
}
}
//每分钟检测一次
setInterval(fn, 1000 * 60)
})
} else {
log("异常界面超时暂停:" + ITimg.setting.异常超时)
}
}
}
function 申请截图() {
console.verbose("申请截图")
if (typeof ITimg.results != "number") {
ITimg.results = 5;
}
while (ITimg.results) {
$settings.setEnabled('foreground_service', true);
sleep((typeof ITimg.results != "number" ? 5 : ITimg.results) * 150);
if (ITimg.setting.自动授权截图) {
if (storages.create("Doolu_download").get("Capture") != "true") {
sleep(20)
console.verbose("确认线程启动中");
sleep(30)
threads.start(function() {
if (device.brand != "HUAWEI") {
if (device.release != 11) {
// if (files.read("./lib/prototype/Capture.txt") != "true") {
var checked;
if (checked = idMatches(/(.*checkbox.*|.*remember.*)/).packageNameContains("com.android.systemui").findOne(500)) {
checked.click();
storages.create("Doolu_download").put("Capture", "true");
console.info("已勾选请求辅助截图权限不再显示");
};
// };
};
} else {
console.verbose("HUAWEI")
}
if (beginBtn = classNameContains("Button").textMatches(/(.*立即开始.*|.*允许.*|.*Start now.*|.*立即開始.*|.*允許.*)/).findOne(10000)) {
//log(beginBtn)
beginBtn.click();
} else if (beginBtn = classNameContains("Button").textMatches(/(.*立即开始.*|.*允许.*|.*Start now.*|.*立即開始.*|.*允許.*)/).findOne(10000)) {
console.info("允许请求截图权限控件信息:")
console.info(beginBtn)
beginBtn.click();
};
})
} else {
console.info("已勾选请求辅助截图权限不再显示");
}
} else {
console.verbose("未开启自动允许辅助截图权限");
}
sleep(200);
try {
function direction() {
let WidthHeight = getWidthHeight();
console.warn("屏幕宽:" + WidthHeight[0] + "屏幕高:" + WidthHeight[1] + "\n----------------开始请求辅助截图权限\n--------------如一直卡住请打开后台弹出界面权限");
if (getRotation() == 0) {
return WidthHeight[0] < WidthHeight[1];
} else {
return WidthHeight[0] > WidthHeight[1];
}
}
if (!requestScreenCapture(direction())) {
//if (!requestScreenCapture({
// orientation: setting.模拟器 ? 1 : 2,
//})) {
// 请求截图权限
toast("申请录屏(横屏辅助截图)权限被拒绝!");
console.error("申请录屏(横屏辅助截图)权限被拒绝!");
tool.dialog_tips("温馨提示", "PRTS辅助是图像识别脚本程序,在工作前必须先获取录屏(横屏辅助截图)权限!!!\n如需程序自动允许录屏(横屏辅助截图)权限,请前往侧边栏-设置,打开自动允许辅助截图。如果在悬浮窗面板运行时无法申请辅助截图权限,请授权应用后台弹出界面权限", "@drawable/ic_report_problem_black_48dp");
tool.Floating_emit("展示文本", "状态", "状态:申请录屏权限被拒绝");
tool.Floating_emit("暂停", "结束程序");
ITimg.exit = true;
break
} else {
toast("请求辅助截图权限成功");
//请求截图权限成功后启动方舟
if (ITimg.results == 2) {
tool.launchPackage(ITimg.packageName);
}
console.info("自动请求截图权限成功!!");
sleep(10)
break;
};
} catch (cap) {
if (cap.message.toString().indexOf("Couldn't allocate virtual display, because too much virtual display was created for the uid") != -1) {
let tips = "申请录屏(横屏辅助截图)权限被拒绝!,请重启应用:\n" + cap.message
toast(tips)
console.error(tips)
tool.Floating_emit("展示文本", "状态", "状态:申请录屏权限被拒绝");
tool.Floating_emit("暂停", "结束程序");
sleep(500);
break
}
$images.stopScreenCapture();
toast("异常,重新尝试" + cap);
console.error("申请辅助截图异常,重新尝试\n" + cap);
// $settings.setEnabled('foreground_service', false);
sleep(300);
};
let tips = "应用多次尝试申请辅助截图权限失败! 请查看运行日志-确认报错信息,打开相关权限:'通知','后台弹出界面(小米,vivo才有)',或保持后台省电策略无限制。"
switch (ITimg.results) {
case 1:
toast(tips)
console.error(tips);
tool.Floating_emit("展示文本", "状态", "状态:请求截图权限出错");
tool.Floating_emit("暂停", "结束程序");
exit();
break
case 3:
ITimg.packageName = tool.currentPackage();
toastLog(tips + "\n\n现在尝试启动应用到前台重新尝试")
app.launchPackage(context.getPackageName());
sleep(2500);
break
}
ITimg.results--;
}
};
/*
function rootgetScreen() {
console.time('rootScreenCapture');
let img = rootScreenCapture();
console.timeEnd('rootScreenCapture');
console.log(img);
img.saveTo(files.cwd() + '/test.png');
img.recycle();
*/
/**
* 使用root截图
* @return png格式图片的字节数组
*/
function rootgetScreen() {
let tempBuffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024);
let byteArrayOutputStream = new java.io.ByteArrayOutputStream();
try {
let exec = java.lang.Runtime.getRuntime().exec(['su', '-c', '/system/bin/screencap -p']);
exec.getOutputStream().close();
let inputStream = exec.getInputStream();
let bufferedInputStream = new java.io.BufferedInputStream(inputStream);
let count;
while ((count = bufferedInputStream.read(tempBuffer)) !== -1) {
byteArrayOutputStream.write(tempBuffer, 0, count);
}
bufferedInputStream.close();
let retCode = exec.waitFor();
// console.log(retCode);
exec.destroy();
} catch (e) {
console.error($debug.getStackTrace(e));
}
return images.fromBytes(byteArrayOutputStream.toByteArray());
}
function adbSgetScreen() {
//$shell.setDefaultOptions({adb : true});
try {
if (!files.exists(package_path + "/mrfz/screencap.sh")) {
files.create(package_path + "/mrfz/screencap.png")
files.create(package_path + "/mrfz/screencap.sh");
shell("chmod 777 " + package_path + "/mrfz/screencap.png");
files.write(package_path + "/mrfz/screencap.sh", "screencap -p " + package_path + "/mrfz/screencap.png")
}
shell("sh " + package_path + "/mrfz/screencap.sh")
} catch (err) {
console.error("adb异常,请确认已在Shizuku应用中授权" + err);
toast("adb异常,请确认已在Shizuku应用中授权" + err);
// tool.Floating_emit("暂停", "结束程序");
sleep(500);
exit();
}
sleep(10);
return images.read(package_path + "/mrfz/screencap.png");
}
function scaleSet(splitScreen, tuku_de, value) {
splitScreen = 2;
//判断缩放比例
if (tuku_de == undefined) {
tuku_de = [];
tuku_de[0] = ITimg.gallery_info.分辨率.h;
tuku_de[1] = ITimg.gallery_info.分辨率.w;
// console.error(tuku_de)
}
if (tuku_de[0] == height && tuku_de[1] == width) {
return 1;
}
let DefaultDelta = tuku_de[0] / tuku_de[1],
DeviceDelta = height / width;
if (value) {
log(tuku_de[0])
log(tuku_de[1])
log(DefaultDelta)
console.verbose(DeviceDelta)
log(DefaultDelta < DeviceDelta)
console.info(DefaultDelta < DeviceDelta ? width / tuku_de[1] : height / tuku_de[0]);
}
if (splitScreen == 2) {
if (DefaultDelta > DeviceDelta) {
return width / tuku_de[1];
} else {
return height / tuku_de[0];
}
} else {
return width / tuku_de[0];
}
}
/**
* 在大图中匹配小图
* @param {string} picture - 图片名称,不包括后缀
* @param {object} list
* @param {number} [list.action = undefined] - 找图识别到后立即进行的操作
* @param {number} [list.timing = 0] - 找图识别到→action操作后等待时间
* @param {string | number | ObjectArray} [list.area = "全屏"] - 找图识别区域, 全屏从中划分四角, 1:左上角,2:右上角,3左下角,4:右下角, 可组合
* @param {number} [list.nods = 0] - 找不到后等待时间
* @param {object} [list.picture = ITimg.captureScreen_()] - 在指定大图中识别
* @param {number|boolean} [list.grayscale = undefined] - 灰度化图片,1为大图,2为小图
* @param {boolean|string} [list.log_policy = undefined] - 识别结果日志打印策略 - true:不显示
* @param {Number} [list.threshold = 0.8] - 图片相似度 - 0.8
* @param {boolean} [list.resolution = false] - 使用多分辨率兼容找图 - false
* @param {string} [list.small_image_catalog = "./mrfz/tuku/"] - picture小图片所在的文件目录
* @param {Number} [list.matchTemplate_max = 5] - 在大图片中搜索小图片最大的结果数量
* @returns {boolean|object} - 返回值取决于list.action
*/
function 图像匹配(picture, list) {
if (!list) {
list = {};
};
list = {
action: list.action,
timing: list.timing || ITimg.default_list.picture.timing,
area: list.area || ITimg.default_list.picture.area,
nods: list.nods || ITimg.default_list.picture.nods,
picture: list.picture,
threshold: list.threshold || ITimg.default_list.picture.threshold,
grayscale: list.grayscale || ITimg.default_list.picture.grayscale,
log_policy: list.log_policy,
resolution: list.resolution || ITimg.default_list.picture.resolution,
small_image_catalog: list.small_image_catalog,
matchTemplate_max: list.matchTemplate_max,
}
let img;
let imgList = list.picture || captureScreen_();
let img_small;
let small_image_catalog = (list.small_image_catalog || ITimg.default_list.picture.small_image_catalog) + picture + ".png";
//多分辨率兼容
if (list.resolution) {
try {
let scale = scaleSet();
img = images.read(small_image_catalog);
img_small = images.scale(img, scale, scale);
} catch (e) {
console.error("缩放失败" + e);
img_small = images.read(small_image_catalog);
}
try {
img.recycle()
} catch (e) {};
} else {
img_small = images.read(small_image_catalog);
}
if (list.grayscale) {
// 灰度化
let gray = images.grayscale((list.grayscale == 1 ? imgList : img_small));
(list.grayscale == 1 ? imgList : img_small).recycle();
// 重要!灰度化后,图片从argb四通道变成了单通道
//因此,需要转换为四通道才能用于找图
if (list.grayscale == 1) {
imgList = images.cvtColor(gray, "GRAY2BGRA");
} else {
img_small = images.cvtColor(gray, "GRAY2BGRA");
};
if (ITimg.setting.调试) {
let pngPtah = package_path + "/logs/captureScreen/灰度化-" + list.grayscale + "-" + picture + ".png";
images.save((list.grayscale == 1 ? imgList : img_small), pngPtah);
}
gray.recycle();
}
list.area = regional_division(list.area);
try {
if (list.action != 6) {
ITimg.results = $images.findImage(imgList, img_small, {
region: list.area,
threshold: list.threshold,
});
} else {
ITimg.results = $images.matchTemplate(imgList, img_small, {
region: list.area,
max: list.matchTemplate_max || ITimg.default_list.picture.matchTemplate_max,
threshold: list.threshold
});
}
} catch (err) {
if (err.message != "java.lang.NullPointerException: template = null") {
toast("识图程序发生异常,返回false\n" + picture + err)
console.error("识图程序发生异常,返回false\n" + picture + err);
} else {
console.error("-要匹配的 '" + picture + ".png' 图片为空,返回false。错误信息:" + err.message + small_image_catalog)
}
try {
imgList.recycle()
img_small.recycle()
} catch (e) {}
return false
}
try {
!imgList.isRecycled() && imgList.recycle();
} catch (e) {}
if (ITimg.results) {
if (list.action == 6) {
return ITimg.results;
}
let img_small_xy = {
w: img_small.getWidth(),
h: img_small.getHeight()
}
//回收图片
img_small.recycle();
ITimg.timer_lock = threads.atomic(0);
if (ITimg.elements.content == picture) {
ITimg.elements.number = ITimg.elements.number + 1;
} else {
ITimg.elements = {
"content": picture,
"number": 0
};
}
ITimg.results.x = ITimg.results.x + random((ITimg.results.x > 10) ? -5 : 0, 10);
ITimg.results.y = ITimg.results.y + random((ITimg.results.y > 10) ? -5 : 0, 10);
switch (list.action) {
case 0:
sleep(50);
//click_s(cx,cy)
click(ITimg.results.x + img_small_xy.w / 2, ITimg.results.y + img_small_xy.h / 2);
break;
case 1:
click(ITimg.results.x + 10, ITimg.results.y + 10);
break
case 2:
click(ITimg.results.x + img_small_xy.w, ITimg.results.y)
break
case 3:
click(ITimg.results.x, ITimg.results.y + img_small_xy.h);
break
case 4:
click(ITimg.results.x + img_small_xy.w, ITimg.results.y + img_small_xy.h);
break
case 5:
return {
"x": ITimg.results.x,
"y": ITimg.results.y,
"w": img_small_xy.w,
"h": img_small_xy.h,
"left": ITimg.results.x,
"top": ITimg.results.y,
"right": ITimg.results.x + img_small_xy.w,
"bottom": ITimg.results.y + img_small_xy.h,
};
};
(list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.info(picture + " 匹配成功 " + ITimg.results);
sleep(list.timing);
return true;
} else {
if (list.picture) {
!list.picture.isRecycled() && list.picture.recycle()
list.picture = "隐藏"
}
img_small.recycle();
sleep(list.nods);
(list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.error("" + picture + " 匹配失败\n--找图配置:" + JSON.stringify(list));
return false;
};
}
/**
* 基于autojs Pro9 优化的特征匹配
* @param {boolean} grayscale - 是否灰度化后再计算特征,默认为true
*/
function matchFeatures(picture, list) {
if (!list) {
list = {};
}
list = {
action: list.action,
timing: list.timing || ITimg.default_list.matchFeatures.timing,
area: list.area || ITimg.default_list.matchFeatures.area,
nods: list.nods || ITimg.default_list.matchFeatures.nods,
picture: list.picture,
matcher: list.matcher || ITimg.default_list.matchFeatures.matcher,
threshold: list.threshold || ITimg.default_list.matchFeatures.threshold,
filter_w: list.filter_w || ITimg.default_list.matchFeatures.filter_w,
filter_h: list.filter_h || ITimg.default_list.matchFeatures.filter_h,
grayscale: list.grayscale,
visualization: list.visualization,
saveSmallImg: list.saveSmallImg,
imageFeatures: list.imageFeatures,
picture_failed_further: list.picture_failed_further,
scale: list.scale || ITimg.default_list.matchFeatures.scale,
log_policy: list.log_policy,
small_image_catalog: list.small_image_catalog || ITimg.default_list.matchFeatures.small_image_catalog,
}
if (list.saveSmallImg === undefined) {
list.saveSmallImg = ITimg.default_list.matchFeatures.saveSmallImg;
}
if (list.picture_failed_further === undefined) {
list.picture_failed_further = ITimg.default_list.matchFeatures.picture_failed_further;
}
if (list.visualization === undefined) {
list.visualization = ITimg.default_list.matchFeatures.visualization;
}
let small_image_catalog = files.path(list.small_image_catalog + picture + ".png");
if (list.saveSmallImg) {
let parts = small_image_catalog.split(/[\/\\]/);
// 去掉数组的最后第二个元素,即最后的目录名
parts.splice(parts.length - 2, 1);
parts.pop();
let picture_name = (list.saveSmallImg === true ? picture : list.saveSmallImg);
// 重新组合剩余的部分成为路径
//获得上一级目录
small_image_save_catalog = files.path(parts.join('/') + "/"); // 使用 '/' 作为路径分隔符
if (files.exists(small_image_save_catalog + picture_name + ".png")) {
console.verbose(picture_name + " 小图已缓存,转到更快的图像匹配");
let grayscale = list.grayscale;
parts = list.small_image_catalog;
//可能导致部分设备闪退,不保证是灰度化图片后的原因
list.picture = undefined;
list.small_image_catalog = small_image_save_catalog;
list.grayscale = undefined;
// return 图像匹配(picture_name, list);
let results = 图像匹配(picture_name, list);
if (results) {
return results;
} else if (list.picture_failed_further) {
console.verbose("常规图像匹配失败,继续特征匹配");
small_image_save_catalog += picture_name + ".png";
list.small_image_save_catalog = parts;
list.grayscale = grayscale;
parts = null;
results = null;
picture_name = null;
grayscale = null;
} else {
return false;
}
// */
} else {
small_image_save_catalog += picture_name + ".png";
}
}
if (!files.exists(small_image_catalog)) {
console.error("小图不存在,无法匹配:", small_image_catalog);
return false;
}
console.time("特征找图总时长");
list.area = regional_division(list.area);
let sceneImg;
if (!list.imageFeatures) {
let img_ = list.picture || captureScreen_();
//长时间持有图片
sceneImg = images.copy(img_, true);
!img_.isRecycled() && img_.recycle();
}
if (list.visualization && !list.imageFeatures) {
// 指定特征点算法SIFT
let sift = SIFT.create();
//大图指定区域部分没有特征点(全黑)时会崩溃,ajp遗留bug
// 获取检验大图特征点,曲线救国
console.time("detect_test");
let big_keyPoints = new MatOfKeyPoint();
let bigTrainImage = new Mat();
//还原色彩空间
Imgproc.cvtColor(sceneImg.mat.submat(list.area[1], list.area[3] + list.area[1], list.area[0], list.area[2] + list.area[0]), bigTrainImage, Imgproc.COLOR_BGRA2RGBA);
if (list.scale != 1) {
//按缩放比例缩放
let newSize = new Size(bigTrainImage.cols() * list.scale, bigTrainImage.rows() * list.scale);
Imgproc.resize(bigTrainImage, bigTrainImage, newSize, 0, 0, Imgproc.INTER_AREA);
}
sift.detect(bigTrainImage, big_keyPoints);
bigTrainImage.release();
console.timeEnd("detect_test");
// console.info(big_keyPoints.toArray().length)
if (!big_keyPoints.toArray().length) {
sceneImg.recycle();
big_keyPoints.release();
if (list.picture) {
!list.picture.isRecycled() && list.picture.recycle()
list.picture = "隐藏"
}
if (list.imageFeatures) {
list.imageFeatures = "隐藏";
}
sleep(list.nods);
(list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.warn("" + picture + " 匹配失败,大图无特征点\n--特征找图配置:" + JSON.stringify(list));
!sceneImg.isRecycled() && sceneImg.recycle();
return false
}
big_keyPoints.release();
}
// 若要提高效率,可以在计算大图特征时调整scale参数,默认为0.5,
// 越小越快,但可以放缩过度导致匹配错误。若在特征匹配时无法搜索到正确结果,可以调整这里的参数,比如\{scale: 1\}
// 也可以在这里指定\{region: [...]\}参数只计算这个区域的特征提高效率
if (!list.imageFeatures) {
var sceneFeatures = $images.detectAndComputeFeatures(sceneImg, {
region: list.area,
grayscale: list.grayscale,
scale: list.scale,
});
}
if (list.picture) {
!list.picture.isRecycled() && list.picture.recycle()
list.picture = "隐藏"
}
let img_small = images.read(small_image_catalog);
// 计算小图特征
let objectFeatures = $images.detectAndComputeFeatures(img_small, {
grayscale: list.grayscale,
});
img_small.recycle();
// 将特征和匹配绘制出来,在调试时更容易看出匹配效果,但会增加耗时
let drawMatches;
//大图指定区域部分没有特征点(全黑)时会崩溃,ajp遗留bug
if (list.visualization) {
drawMatches = package_path + "/logs/matchFeatures/" + picture + "_特征"+list.matcher+"_匹配结果.jpg";
// log(drawMatches)
// images.save(img, drawMatches);
}
//其他匹配算法可能导致闪退
if (list.matcher == 1) {
list.matcher = "BRUTEFORCE_L1";
} else if (list.matcher == 2) {
list.matcher = "BRUTEFORCE_SL2";
} else if (list.matcher == 3) {
list.matcher = "BRUTEFORCE";
} else if (list.matcher == 4) {
list.matcher = "FLANNBASED";
}
ITimg.results = $images.matchFeatures((list.imageFeatures ? list.imageFeatures : sceneFeatures), objectFeatures, {
drawMatches: drawMatches,
threshold: list.threshold,
matcher: list.matcher
});
// 回收特征对象
objectFeatures.recycle();
if (!list.imageFeatures) {
sceneFeatures.recycle();
} else {
list.imageFeatures = "隐藏";
}
if (!ITimg.results) {
sleep(list.nods);
(list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.warn("" + picture + " 匹配失败\n--特征找图配置:" + JSON.stringify(list));
if (sceneImg) {
!sceneImg.isRecycled() && sceneImg.recycle();
}
return false;
}
function isRectangle(A, B, C, D) {
//计算所有边的长度
let AB = Math.sqrt((B.x - A.x) ** 2 + (B.y - A.y) ** 2);
let BC = Math.sqrt((C.x - B.x) ** 2 + (C.y - B.y) ** 2);
let CD = Math.sqrt((D.x - C.x) ** 2 + (D.y - C.y) ** 2);
let DA = Math.sqrt((A.x - D.x) ** 2 + (A.y - D.y) ** 2);
// Calculate diagonals
let AC = Math.sqrt((C.x - A.x) ** 2 + (C.y - A.y) ** 2);
let BD = Math.sqrt((D.x - B.x) ** 2 + (D.y - B.y) ** 2);
//可容忍误差百分比,最高建议35
let errorPercentage = 25; // 允许±5%的误差
//检查是否有两对相等的边和闭合的对角线
if (approximatelyEqual(AB, CD, errorPercentage) && approximatelyEqual(BC, DA, errorPercentage) &&
approximatelyEqual(AC, BD, errorPercentage)) {
return true;
} else {
return false;
}
}
function approximatelyEqual(a, b, errorPercentage) {
let maxError = (errorPercentage / 100) * a;
// console.warn(a, b, (Math.abs(a - b) <= maxError))
return Math.abs(a - b) <= maxError;
}
if (!isRectangle(ITimg.results.topLeft, ITimg.results.topRight, ITimg.results.bottomLeft, ITimg.results.bottomRight)) {
sleep(list.nods);
// (list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.error("" + picture + " 匹配失败\n--特征找图配置:" + JSON.stringify(list));
if (sceneImg) {
!sceneImg.isRecycled() && sceneImg.recycle();
}
console.error(picture + " 识别结果是非矩形形状,可能是非正确的小图。详情可" + (list.visualization ? "" : "设置匹配参数visualization为true,") + "前往 " + package_path + "/logs/matchFeatures/,查看相关可视化识别结果\n--特征找图配置:", JSON.stringify(list));
return false
}
//console.info(ITimg.results)
ITimg.results = {
top: parseInt(ITimg.results.topRight.y),
left: parseInt(ITimg.results.topLeft.x),
bottom: parseInt(ITimg.results.bottomLeft.y),
right: parseInt(ITimg.results.bottomRight.x)
}
ITimg.results.x = ITimg.results.left;
ITimg.results.y = ITimg.results.top;
ITimg.results.h = ITimg.results.bottom - ITimg.results.top;
ITimg.results.w = ITimg.results.right - ITimg.results.left;
if (ITimg.results.w <= list.filter_w || ITimg.results.h <= list.filter_h) {
sleep(list.nods);
// (list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.error("" + picture + " 匹配失败\n--特征找图配置:" + JSON.stringify(list));
if (sceneImg) {
!sceneImg.isRecycled() && sceneImg.recycle();
}
console.error(picture + " wh小于滤值 " + list.filter_w + "," + list.filter_h + " 无效结果,可能是非正确的小图。详情可" + (list.visualization ? "" : "设置匹配参数visualization为true,") + "前往 " + package_path + "/logs/matchFeatures/,查看相关可视化识别结果\n--特征找图配置:", JSON.stringify(list));
return false;
}
if (list.saveSmallImg && !list.imageFeatures) {
console.verbose("缓存小图到:" + small_image_save_catalog);
if (ITimg.results.x >= 0 && ITimg.results.y >= 0 && ITimg.results.x + ITimg.results.w <= sceneImg.width && ITimg.results.y + ITimg.results.h <= sceneImg.height) {
let submat = images.clip(sceneImg, ITimg.results.x, ITimg.results.y, ITimg.results.w, ITimg.results.h)
images.save(submat, small_image_save_catalog);
submat.recycle();
} else {
console.error("特征匹配坐标越界,无法裁剪小图")
}
}
if (sceneImg) {
!sceneImg.isRecycled() && sceneImg.recycle();
}
console.timeEnd("特征找图总时长");
if (ITimg.results) {
ITimg.timer_lock = threads.atomic(0);
if (ITimg.elements.content == picture) {
ITimg.elements.number = ITimg.elements.number + 1;
} else {
ITimg.elements = {
"content": picture,
"number": 0
};
}
switch (list.action) {
case 0:
sleep(50);
click(ITimg.results.x + ITimg.results.w / 2 + random((ITimg.results.x > 10) ? -5 : 0, 10), ITimg.results.y + ITimg.results.h / 2 + random((ITimg.results.x > 10) ? -5 : 0, 10));
break;
case 1:
click(ITimg.results.x + 5, ITimg.results.y + 5);
break
case 2:
click(ITimg.results.right, ITimg.results.top);
break
case 3:
click(ITimg.results.left, ITimg.results.bottom);
break
case 4:
click(ITimg.results.right, ITimg.results.bottom);
break
case 5:
return ITimg.results;
}
(list.log_policy || ITimg.default_list.picture.log_policy) ? "" : console.info(picture + " 特征匹配成功 " + ITimg.results.x + ", " + ITimg.results.y);
sleep(list.timing);
return true;
}
}
/**
* 对图片 进行文字识别,并匹配words文字
* @param {string} words - 需要识别的文字
* @param {object} list
* @param {number} [list.action = undefined] - ocr识别到后立即进行的操作
* @param {number} [list.timing = 0] - ocr识别到后等待时间
* @param {string | number | ObjectArray} [list.area = "全屏"] - 找图识别区域, 全屏从中划分四角, 1:左上角,2:右上角,3左下角,4:右下角, 可组合
* @param {object} [list.picture = ITimg.captureScreen_()] - 在指定大图中识别
* @param {number} [list.nods = 0] - 没有匹配到相关的文字后等待时间
* @param {boolean} [list.part = fasle] - text需要包含字符串words的筛选条件
* @param {number} [list.similar = 0.7] - 中文模糊匹配相似度,基于字形计算因子
* @param {boolean} [list.refresh = true] - 是否重新截图界面,在新图片中识别, false:不刷新
* @param {boolean|object} [list.resolution = false] - 使用多分辨率兼容(缩放大图)识别文字
* @param {object} [list.gather] - 仅在该数据集{text,left,top,right,bottom}中匹配words文字
* @param {boolean|string} [list.log_policy = false] - 识别结果日志打印策略. brief:'简短' / true:不显示
* @param {boolean|string} [list.saveSmallImg = false] - 是否缓存小图,saveSmallImg可传入名称
* @param {boolean} [list.picture_failed_further = false] - 缓存图像匹配时失败,继续OCR识别
* @param {string} [list.ocr_type = "MlkitOCR"] - ocr扩展类型
* @param {boolean} 识别结果可视化,暂未支持
* @param {boolean | object} [list.resolution = false] - 使用多分辨率兼容(调整大图片大小)识别文字,可使用{w:w,h:h}指定大小
* @param {string} [list.correction_path = false] - ocr识别字符纠正规则json文件路径
* @returns {boolean|object} - 返回值取决于list.action
*/
function ocr文字识别(words, list) {
if (!list) {
list = {};
}
list = {
action: list.action,
timing: list.timing || ITimg.default_list.ocr.timing,
picture: list.picture,
area: list.area || ITimg.default_list.ocr.area,
nods: list.nods || ITimg.default_list.ocr.nods,
part: list.part || ITimg.default_list.ocr.part,
similar: list.similar || ITimg.default_list.ocr.similar,
refresh: list.refresh,
resolution: list.resolution || ITimg.default_list.ocr.resolution,
gather: list.gather,
threshold: list.threshold,
saveSmallImg: list.saveSmallImg,
visualization: list.visualization,
picture_failed_further: list.picture_failed_further,
log_policy: list.log_policy,
ocr_type: list.ocr_type || ITimg.default_list.ocr.ocr_type,
correction_path: list.correction_path || ITimg.default_list.ocr.correction_path
}