-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
2012 lines (1777 loc) · 74.6 KB
/
__init__.py
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
import os
import re
import subprocess
import sys
import time
from collections import defaultdict
import cv2
import numexpr
from a_cv_imwrite_imread_plus import save_cv_image
from adbeventparser import EventRecord
from adbnativeblitz import AdbFastScreenshots
from flatten_everything import flatten_everything
from geteventplayback import GeteventPlayBack
from istruthy import is_truthy
from touchtouch import touch
from usefuladb import AdbControl
import pandas as pd
import numpy as np
from a_pandas_ex_apply_ignore_exceptions import pd_add_apply_ignore_exceptions
pd_add_apply_ignore_exceptions()
adbconfig = sys.modules[__name__]
adbconfig.all_devices = {}
class RecordedEvent:
"""
Represents a recorded event with an associated command for execution.
Attributes:
- fu: The function for executing the recorded event.
- command: The command used for recording the event.
- execution: The full execution command for replaying the recorded event.
"""
def __init__(self, fu, command):
self.command = command
self.execution = f"su -c 'cat {command} | sh'"
self.fu = fu
def __call__(self, **kwargs):
self.fu(self.execution, **kwargs)
def __str__(self):
return self.execution
def __repr__(self):
return self.__str__()
class AdbDescriptor:
"""
Solution for inheriting attributes from a Pandas DataFrame
Descriptor for accessing the AdbControl instance associated with a class instance.
"""
def __get__(self, instance, owner):
try:
if not instance.__dict__[self.name]:
instance.__dict__[self.name] = instance.__dict__["_attrs"][
"adb_instance"
]
except Exception:
instance.__dict__[self.name] = None
return instance.__dict__[self.name]
def __set__(self, instance, value):
try:
instance.__dict__[self.name] = instance.__dict__["_attrs"]["adb_instance"]
except Exception:
instance.__dict__[self.name] = value
def __delete__(self, instance):
return
def __set_name__(self, owner, name):
self.name = name
class DataFrameWithMeta(pd.DataFrame):
"""
Subclass of pandas DataFrame with additional metadata, specifically designed for ADB interactions.
Attributes:
- adb_instance: A descriptor attribute providing access to the associated AdbControl instance.
Example:
```
adb_plus = AdbControlPlus(adb_path="/path/to/adb", device_serial="123456")
df = DataFrameWithMeta(data=my_data, adb_instance=adb_plus)
df.adb_instance # Access the associated AdbControlPlus instance
```
"""
adb_instance = AdbDescriptor()
@property
def _constructor(self):
return self.__class__
def __init__(self, *args, adb_instance=None, **kwargs):
self.adb_instance = adb_instance
super().__init__(*args, **kwargs)
self.attrs["adb_instance"] = adb_instance
def plus_save_screenshots(self, folder, column="aa_screenshot"):
r"""
Save screenshots from the specified column to the given folder.
Args:
- folder (str): The folder path where the screenshots will be saved.
- column (str, optional): The column containing screenshots. Defaults to "aa_screenshot".
Returns:
pandas.Series: A Series with file paths of the saved screenshots.
Example:
saved_files = df.plus_save_screenshots(folder="/path/to/screenshots")
"""
return self.ds_apply_ignore(
pd.NA,
lambda x: save_cv_image(
f'{os.path.join(folder, str(x.name) + ".png")}', x[column]
)
if x.aa_area > 0
else pd.NA,
axis=1,
)
class DataFrameWithMetaShaply(DataFrameWithMeta):
r"""
Subclass of DataFrameWithMeta with additional functionality for drawing and saving Shapely polygons on images.
Attributes:
- color (tuple, optional): RGB color tuple for drawing polygons. Defaults to (255, 0, 255).
- thickness (int, optional): Thickness of polygon edges. Defaults to 2.
"""
def plus_save_screenshots(
self, folder, column="aa_screenshot", color=(255, 0, 255), thickness=2
):
"""
Save screenshots with Shapely polygons drawn on them to the specified folder.
Args:
- folder (str): The folder path where the screenshots will be saved.
- column (str, optional): The column containing screenshots. Defaults to "aa_screenshot".
- color (tuple, optional): RGB color tuple for drawing polygons. Defaults to (255, 0, 255).
- thickness (int, optional): Thickness of polygon edges. Defaults to 2.
Returns:
pandas.Series: A Series with file paths of the saved screenshots.
Example:
saved_files = df_shaply.plus_save_screenshots(folder="/path/to/screenshots")
"""
allfi = []
for i, va in self.iterrows():
try:
im = va[column].copy()
ff = va.boundary
cv2.fillPoly(im, [ff], color)
cv2.polylines(im, [ff], isClosed=True, color=color, thickness=thickness)
filep = os.path.join(folder, str(i) + ".png")
save_cv_image(f"{filep}", im)
allfi.append(filep)
except Exception:
allfi.append(pd.NA)
return pd.Series(allfi, index=self.index.copy())
class DrawExecutor:
r"""
Executor class for drawing and saving shapes on images based on provided function and DataFrame.
Attributes:
- fu: The drawing function.
- frame: The DataFrame containing information about shapes.
- screenshot: The screenshot image.
"""
def __init__(self, fu, frame, screenshot):
self.fu = fu
self.screenshot = screenshot
self.frame = frame
def __call__(
self,
save_folder=None,
min_area=100,
shapes=("rectangle", "triangle", "circle", "pentagon", "hexagon", "oval"),
):
try:
if min_area > self.frame.aa_area.iloc[0]:
return pd.NA
sho = self.fu(
self.frame,
self.screenshot,
min_area=min_area,
shapes=shapes,
cv2show=False,
)
if save_folder:
save_cv_image(
os.path.join(save_folder, str(self.frame.index[0]) + ".png"), sho
)
return sho
except Exception as fe:
sys.stderr.write(f"{fe}\n")
sys.stderr.flush()
return pd.NA
def __str__(self):
return "()"
def __repr__(self):
return "()"
def _pandas_ex_fuzzy_match(df, stringlist, column=None, scorer=None, min_value=0):
r"""
Perform fuzzy matching between a DataFrame column and a list of strings.
Parameters:
- df (DataFrameWithMeta): The input DataFrame containing the data.
- stringlist (list): The list of strings to match against the DataFrame column.
- column (str, optional): The column in the DataFrame to perform the fuzzy matching on.
Defaults to 'aa_text' if not specified.
- scorer (callable, optional): The scoring function for fuzzy matching.
Defaults to fuzz.WRatio from the rapidfuzz library if not specified.
- min_value (int, optional): The minimum matching score for a match to be considered.
Matches with scores below this threshold will be excluded from the result.
Defaults to 0 if not specified.
Returns:
- DataFrameWithMeta: A new DataFrame containing rows that match the specified criteria.
Example:
```
stringlist = ['Pôxxquer', 'Quxxs', 'Quênixxa - Premier League', ... ]
df3 = df.plus_fuzzy_match(stringlist=stringlist, column='aa_text', scorer=fuzz.WRatio, min_value=0)
print(df3)
```
Note:
- This function uses the rapidfuzz library (https://pypi.org/project/rapidfuzz/ - written in C++) for fuzzy matching.
"""
if not scorer:
scorer = fuzz.WRatio
if not column:
column = "aa_text"
df1 = pd.DataFrame(stringlist, columns=[column])
df3 = df.d_fuzzy_merge(
df1,
right_on=column,
left_on=column,
usedtype=np.uint8,
scorer=scorer,
concat_value=True,
)
return DataFrameWithMeta(
df3.loc[df3.concat_value > min_value],
adb_instance=df.adb_instance,
)
def _pandas_ex_count_colors(
df,
column="aa_screenshot",
):
r"""
Count the occurrence of colors in images stored in a DataFrame column.
Parameters:
- df (DataFrameWithMeta): The input DataFrame containing the data.
- column (str, optional): The column in the DataFrame containing images.
Defaults to 'aa_screenshot' if not specified.
Returns:
- DataFrameWithMeta: A new DataFrame containing color count information.
Example:
```
dft = df.plus_count_colors(column='aa_screenshot')
print(dft)
```
Note:
- This function uses the `colorcount` (https://github.com/hansalemaos/colorcountcython - written in Cython) function to count the occurrence of colors in each image.
- The resulting DataFrame includes columns 'aa_img_index', 'aa_r', 'aa_g', 'aa_b', and 'aa_count'.
- 'aa_img_index' represents the index of the image in the DataFrame.
- 'aa_r', 'aa_g', and 'aa_b' represent the red, green, and blue components of the color.
- 'aa_count' represents the count of the corresponding color in the image.
"""
dft = (
df[column]
.ds_apply_ignore(
((), ()),
lambda b: colorcount(pic=b, coords=False, count=True)[
"color_count"
].items(),
)
.to_frame()
.explode(column)
.dropna()
.ds_apply_ignore(
[pd.NA, pd.NA, pd.NA, pd.NA, pd.NA],
lambda q: [
q.name,
q[column][0][0],
q[column][0][1],
q[column][0][2],
q[column][1],
],
result_type="expand",
axis=1,
)
.dropna()
.astype({0: np.uint32, 1: np.uint8, 2: np.uint8, 3: np.uint8, 4: np.uint32})
.rename(
columns={0: "aa_img_index", 1: "aa_r", 2: "aa_g", 3: "aa_b", 4: "aa_count"}
)
)
return DataFrameWithMeta(
dft,
adb_instance=df.adb_instance,
)
def _pandas_ex_color_coords(
df,
column="aa_screenshot",
):
r"""
Extract color coordinates from images stored in a DataFrame column.
Parameters:
- df (DataFrameWithMeta): The input DataFrame containing the data.
- column (str, optional): The column in the DataFrame containing images.
Defaults to 'aa_screenshot' if not specified.
Returns:
- DataFrameWithMeta: A new DataFrame containing color coordinate information.
Example:
```
df_color_coords = df.plus_color_coords(column='aa_screenshot')
print(df_color_coords)
```
Note:
- This function uses the `colorcount` (https://github.com/hansalemaos/colorcountcython - written in Cython) function to extract color coordinates from each image.
- The resulting DataFrame includes columns 'aa_img_index', 'aa_r', 'aa_g', 'aa_b', 'aa_x', and 'aa_y'.
- 'aa_img_index' represents the index of the image in the DataFrame.
- 'aa_r', 'aa_g', and 'aa_b' represent the red, green, and blue components of the color.
- 'aa_x' and 'aa_y' represent the x and y coordinates of the color in the image.
"""
dfcolorcoords = df[column].ds_apply_ignore(
pd.NA,
lambda b: colorcount(pic=b, coords=True, count=False)["color_coords"].items(),
)
dfcolorcoords.to_frame().dropna().explode(column).apply(
lambda q: q[column][0], result_type="expand", axis=1
)
dfcolorcoords = (
dfcolorcoords.to_frame()
.dropna()
.explode(column)
.apply(
lambda q: [
q.name,
q[column][0][0],
q[column][0][1],
q[column][0][2],
q[column][1],
],
result_type="expand",
axis=1,
)
.explode(4)
.dropna()
.astype({0: np.uint32, 1: np.uint8, 2: np.uint8, 3: np.uint8})
)
dfcolorcoords["aa_x"] = dfcolorcoords[4].str[0].astype(np.uint32)
dfcolorcoords["aa_y"] = dfcolorcoords[4].str[1].astype(np.uint32)
dfcolorcoords.drop(columns=4, inplace=True)
dfcolorcoords.reset_index(drop=True, inplace=True)
dfcolorcoords.rename(
columns={0: "aa_img_index", 1: "aa_r", 2: "aa_g", 3: "aa_b"}, inplace=True
)
return DataFrameWithMeta(
dfcolorcoords,
adb_instance=df.adb_instance,
)
def _pandas_ex_color_search_with_c(
df,
colors2find,
column="aa_screenshot",
cpus=5,
chunks=1,
print_stderr=True,
print_stdout=False,
usecache=True,
with_sendevent=False,
):
r"""
Search for specified colors in images stored in a DataFrame column using C-extension.
Parameters:
- df (DataFrameWithMeta): The input DataFrame containing the data.
- colors2find (list): A list of RGB tuples representing colors to search for in the images.
- column (str, optional): The column in the DataFrame containing images.
Defaults to 'aa_screenshot' if not specified.
- cpus (int, optional): The number of CPU cores to use for parallel processing. Defaults to 5.
- chunks (int, optional): The number of chunks to divide the data into for parallel processing. Defaults to 1.
- print_stderr (bool, optional): Whether to print stderr messages during color search. Defaults to True.
- print_stdout (bool, optional): Whether to print stdout messages during color search. Defaults to False.
- usecache (bool, optional): Whether to use caching for color search results. Defaults to True.
- with_sendevent (bool, optional): Whether to include sendevent information in the result. Defaults to False.
Returns:
- DataFrameWithMeta: The input DataFrame with additional columns related to color search.
Example:
```
df = df.plus_color_search_with_c(
colors2find=[(255, 0, 0), (0, 255, 0), (0, 0, 255)],
column='aa_screenshot',
cpus=4,
chunks=2,
print_stderr=True,
print_stdout=False,
usecache=True,
with_sendevent=False,
)
print(df)
```
Note:
- This function uses the C-extension https://github.com/hansalemaos/chopchopcolorc for efficient parallel color search.
- The resulting DataFrame includes an 'aa_colorsearch_c' column containing search results.
- If a color is found in an image, the corresponding entry is a non-negative integer; otherwise, it is NA.
- Additional columns include 'aa_csearch_mean_x' and 'aa_csearch_mean_y', representing the mean x and y coordinates of the found colors.
- If 'with_sendevent' is True, the DataFrame includes columns for input tap and sendevent information.
"""
with_input_tap = True
df2 = df.copy()
df2.loc[:, "aa_colorsearch_c"] = pd.Series(
color_search_c(
pics=df2[column].to_list(),
rgb_tuples=colors2find,
cpus=cpus,
chunks=chunks,
print_stderr=print_stderr,
print_stdout=print_stdout,
usecache=usecache,
)
).ds_apply_ignore(
pd.NA, lambda x: pd.NA if len(x) == 1 and np.sum(x[0]) <= 0 else x
)
df2["aa_csearch_mean_x"] = df2.aa_colorsearch_c.ds_apply_ignore(
pd.NA,
lambda q: numexpr.evaluate(
"h/j",
global_dict={},
local_dict={
"j": len(q),
"h": numexpr.evaluate(
"sum(q)", local_dict={"q": q[..., 1]}, global_dict={}
),
},
),
).fillna(-1)
df2["aa_csearch_mean_y"] = df2.aa_colorsearch_c.ds_apply_ignore(
pd.NA,
lambda q: numexpr.evaluate(
"h/j",
global_dict={},
local_dict={
"j": len(q),
"h": numexpr.evaluate(
"sum(q)", local_dict={"q": q[..., 0]}, global_dict={}
),
},
),
).fillna(-1)
#
df2["aa_csearch_mean_y"] = df2.ds_apply_ignore(
pd.NA, lambda j: int(j.aa_csearch_mean_y + j.aa_start_y), axis=1
)
df2["aa_csearch_mean_x"] = df2.ds_apply_ignore(
pd.NA, lambda j: int(j.aa_csearch_mean_x + j.aa_start_x), axis=1
)
dfr = DataFrameWithMeta(
df2,
adb_instance=df.adb_instance,
)
dfrclick = _add_click_methods(
dfr,
with_input_tap=with_input_tap,
with_sendevent=with_sendevent,
column_input_tap="ff_colormean_input_tap",
column_x="aa_csearch_mean_x",
column_y="aa_csearch_mean_y",
sendevent_prefix="ff_colormean_sendevent_",
)
dfrclick.loc[
((dfrclick["aa_colorsearch_c"].isna())),
[
"aa_csearch_mean_x",
"aa_csearch_mean_y",
"ff_colormean_input_tap",
*[
k
for k in dfrclick.columns
if str(k).startswith("ff_colormean_sendevent_")
],
],
] = pd.NA
return dfrclick
def _pandas_ex_find_shapes(
dframe,
with_draw_function=True,
threshold1=10,
threshold2=90,
approxPolyDPvar=0.01,
cpus=5,
chunks=1,
print_stderr=True,
print_stdout=False,
usecache=True,
column="aa_screenshot",
with_sendevent=False,
):
r"""
Find and analyze shapes in images stored in a DataFrame column.
Parameters:
- dframe (DataFrameWithMeta): The input DataFrame containing the data.
- with_draw_function (bool, optional): Whether to include a drawing function in the results. Defaults to True.
- threshold1 (int, optional): The first threshold value for shape detection. Defaults to 10.
- threshold2 (int, optional): The second threshold value for shape detection. Defaults to 90.
- approxPolyDPvar (float, optional): The approximation accuracy for polygonal shapes. Defaults to 0.01.
- cpus (int, optional): The number of CPU cores to use for parallel processing. Defaults to 5.
- chunks (int, optional): The number of chunks to divide the data into for parallel processing. Defaults to 1.
- print_stderr (bool, optional): Whether to print stderr messages during shape analysis. Defaults to True.
- print_stdout (bool, optional): Whether to print stdout messages during shape analysis. Defaults to False.
- usecache (bool, optional): Whether to use caching for shape analysis results. Defaults to True.
- column (str, optional): The column in the DataFrame containing images.
Defaults to 'aa_screenshot' if not specified.
- with_sendevent (bool, optional): Whether to include sendevent information in the result. Defaults to False.
Returns:
- DataFrameWithMeta: The input DataFrame with additional columns related to shape analysis.
Example:
df = df.plus_find_shapes(
with_draw_function=True,
threshold1=20,
threshold2=80,
approxPolyDPvar=0.005,
cpus=4,
chunks=2,
print_stderr=True,
print_stdout=False,
usecache=True,
column='aa_screenshot',
with_sendevent=False,
)
print(df)
Note:
- This function uses https://github.com/hansalemaos/multiprocshapefinder
to detect and analyze shapes in images.
- The resulting DataFrame includes columns related to shape coordinates and characteristics.
- If 'with_draw_function' is True, a 'ff_drawn_shape' column includes drawn shapes using the
DrawExecutor class.
- Additional columns include 'aa_offset_x' and 'aa_offset_y', representing the offset of the detected shapes.
- 'aa_real_center_x' and 'aa_real_center_y' represent the real center coordinates of the detected shapes.
- If 'with_sendevent' is True, the DataFrame includes columns for input tap and sendevent information.
"""
with_input_tap = True
lookupdict = dframe.index.to_frame().reset_index(drop=True).to_dict()[0]
df = dframe.reset_index(drop=True)
imagefilter = df[column].to_dict() #
df4 = find_all_shapes(
list(imagefilter.values()),
threshold1=threshold1,
threshold2=threshold2,
approxPolyDPvar=approxPolyDPvar,
cpus=cpus,
chunks=chunks,
print_stderr=print_stderr,
print_stdout=print_stdout,
usecache=usecache,
)
df4 = df4.astype(
{
k: "Int64"
for k in df4.columns
if str(k).startswith("aa_bound") or str(k).startswith("aa_center")
}
)
if with_draw_function:
allclasses = []
for i1, i2 in zip(range(len(df4)), range(1, len(df4) + 1)):
df4t = df4.iloc[i1:i2]
allclasses.append(
DrawExecutor(
draw_results, df4t, df.iloc[df4t.aa_img_index.iloc[0]][column]
)
)
df4["ff_drawn_shape"] = allclasses
df4.loc[:, "aa_img_index"] = df4["aa_img_index"].map(lookupdict)
df4["aa_offset_x"] = (
df4.groupby("aa_img_index")
.apply(lambda x: dframe.loc[x.aa_img_index])
.aa_start_x.reset_index()["aa_start_x"]
)
df4["aa_offset_y"] = (
df4.groupby("aa_img_index")
.apply(lambda x: dframe.loc[x.aa_img_index])
.aa_start_y.reset_index()["aa_start_y"]
)
df4["aa_real_center_x"] = df4["aa_center_x"] + df4["aa_offset_x"]
df4["aa_real_center_y"] = df4["aa_center_y"] + df4["aa_offset_y"]
dfr = DataFrameWithMeta(
df4,
adb_instance=dframe.adb_instance,
)
return _add_click_methods(
dfr,
with_input_tap=with_input_tap,
with_sendevent=with_sendevent,
column_input_tap="ff_shape_input_tap",
column_x="aa_real_center_x",
column_y="aa_real_center_y",
sendevent_prefix="ff_shape_sendevent_",
)
def _pandas_ex_template_matching(
df,
needles,
with_sendevent=True,
with_image_data=True,
thresh=0.9,
pad_input=False,
mode="constant",
constant_values=0,
usecache=True,
processes=5,
chunks=1,
print_stdout=False,
print_stderr=True,
column="aa_screenshot",
):
r"""
Perform template matching on images in a DataFrame column.
Parameters:
- df (DataFrameWithMeta): The input DataFrame containing the data.
- needles (list): A dict (name : image) of template images to match.
- with_sendevent (bool, optional): Whether to include sendevent commands in the results. Defaults to True.
- with_image_data (bool, optional): Whether to include image data in the results. Defaults to True.
- thresh (float, optional): The threshold for matching similarity. Defaults to 0.9.
- pad_input (bool, optional): Whether to pad the input images. Defaults to False.
- mode (str, optional): The padding mode if 'pad_input' is True. Defaults to 'constant'.
- constant_values (int, optional): The constant value for padding. Defaults to 0.
- usecache (bool, optional): Whether to use caching for template matching results. Defaults to True.
- processes (int, optional): The number of CPU cores to use for parallel processing. Defaults to 5.
- chunks (int, optional): The number of chunks to divide the data into for parallel processing. Defaults to 1.
- print_stdout (bool, optional): Whether to print stdout messages during template matching. Defaults to False.
- print_stderr (bool, optional): Whether to print stderr messages during template matching. Defaults to True.
- column (str, optional): The column in the DataFrame containing images.
Defaults to 'aa_screenshot' if not specified.
Returns:
- DataFrameWithMeta: A DataFrame with matched template information, including input taps and sendevent commands.
Example:
```
df = df.plus_template_matching(
needles={'b1': 'c:\pic1.png', 'b2': 'c:\pic2.png'},
with_sendevent=True,
with_image_data=True,
thresh=0.8,
pad_input=True,
mode='constant',
constant_values=255,
usecache=True,
processes=4,
chunks=2,
print_stdout=True,
print_stderr=False,
column='aa_screenshot',
)
print(df)
```
Note:
- This function uses the https://github.com/hansalemaos/needlefinder algorithm for template matching.
- The resulting DataFrame includes columns related to template matching results, including input taps and sendevent commands.
- The 'needles' parameter should be a list of template images.
- Input taps and sendevent commands are included if 'with_input_tap' and 'with_sendevent' are True.
"""
with_input_tap = True
self = df.adb_instance
df2 = df.dropna(subset=column).copy()
df2["aa_realindex"] = df2.index.__array__().copy()
haystacks = df2[column].to_list()
dfneedles = find_needles_in_multi_haystacks(
haystacks=haystacks,
needles=needles,
with_image_data=with_image_data,
thresh=thresh,
pad_input=pad_input,
mode=mode,
constant_values=constant_values,
usecache=usecache,
processes=processes,
chunks=chunks,
print_stdout=print_stdout,
print_stderr=print_stderr,
)
lookupdict = df2.aa_realindex.to_frame().reset_index(drop=True).to_dict()
dfneedlesabs = dfneedles.groupby("aa_img_index", group_keys=False).apply(
lambda q: DataFrameWithMeta(
[
q.aa_start_x + df2.iloc[q.aa_img_index].aa_start_x.iloc[0],
q.aa_start_y + df2.iloc[q.aa_img_index].aa_start_y.iloc[0],
q.aa_end_x + df2.iloc[q.aa_img_index].aa_start_x.iloc[0],
q.aa_end_y + df2.iloc[q.aa_img_index].aa_start_y.iloc[0],
q.aa_center_x + df2.iloc[q.aa_img_index].aa_start_x.iloc[0],
q.aa_center_y + df2.iloc[q.aa_img_index].aa_start_y.iloc[0],
q.aa_img_index,
],
adb_instance=self,
).T
)
dfneedlesabs.attrs["adb_instance"] = self
for col in dfneedlesabs.columns:
try:
dfneedlesabs[col] = dfneedlesabs[col].astype("Int64")
except Exception:
pass
dfneedlesabs["aa_img_index"] = dfneedlesabs["aa_img_index"].map(
lookupdict["aa_realindex"]
)
dfneedlesabs.columns = [f"aa_needle_abs_{x[3:]}" for x in dfneedlesabs.columns]
dfneedles.columns = [f"aa_needle_{x[3:]}" for x in dfneedles.columns]
dfneedlesabs2 = pd.concat([dfneedlesabs, dfneedles], axis=1)
df2["aa_merge_index"] = df2.index.__array__().copy()
dfr = (
df2.merge(
dfneedlesabs2,
right_on="aa_needle_abs_img_index",
left_on="aa_merge_index",
how="inner",
)
.drop(columns="aa_merge_index")
.rename(columns={"aa_needle_abs_img_index": "aa_img_index"})
.reset_index(drop=True)
)
dfr = DataFrameWithMeta(
dfr,
adb_instance=self,
)
return _add_click_methods(
dfr,
with_input_tap=with_input_tap,
with_sendevent=with_sendevent,
column_input_tap="ff_needle_input_tap",
column_x="aa_needle_center_x",
column_y="aa_needle_center_y",
sendevent_prefix="ff_needle_sendevent_",
)
def _get_pandas_ex_color_cluster(
img,
colors,
reverse_colors=True,
backend="C",
memorylimit_mb=10000,
eps=3,
min_samples=10,
algorithm="auto",
leaf_size=30,
n_jobs=5,
max_width=100,
max_height=100,
interpolation=cv2.INTER_NEAREST,
):
r"""
Perform color clustering on an image and return the cluster information.
Parameters:
- img (numpy.ndarray): The input image for color clustering.
- colors (list): List of colors to identify clusters.
- reverse_colors (bool, optional): Whether to reverse the colors (RGB - BGR). Defaults to True.
- backend (str, optional): The backend for Euclidean distance calculation. Defaults to "C".
- memorylimit_mb (int, optional): Memory limit in megabytes for the Euclidean distance matrix.
Defaults to 10000.
- eps (float, optional): The maximum distance between two samples for one to be considered
as in the neighborhood of the other.
Defaults to 3.
- min_samples (int, optional): The number of samples in a neighborhood
for a point to be considered as a core point. Defaults to 10.
- algorithm (str, optional): The algorithm to compute nearest neighbors. Defaults to "auto".
- leaf_size (int, optional): Leaf size passed to BallTree or KDTree. Defaults to 30.
- n_jobs (int, optional): The number of parallel jobs to run for DBSCAN. Defaults to 5.
- max_width (int, optional): Maximum width for resizing the image. Defaults to 100.
- max_height (int, optional): Maximum height for resizing the image. Defaults to 100.
- interpolation (int, optional): Interpolation method for resizing the image.
Defaults to cv2.INTER_NEAREST.
Returns:
- ShapelyGeometryCollection: A Shapely Geometry Collection representing the color clusters.
Note:
- This function utilizes the ColorCluster class for color clustering and DBSCAN for clustering.
- The resulting Shapely Geometry Collection represents the identified color clusters in the image.
```
"""
return (
ColorCluster(
img=img,
max_width=max_width,
max_height=max_height,
interpolation=interpolation,
)
.find_colors(colors=colors, reverse_colors=reverse_colors)
.calculate_euclidean_matrix(backend=backend, memorylimit_mb=memorylimit_mb)
.get_dbscan_labels(
eps=eps,
min_samples=min_samples,
algorithm=algorithm,
leaf_size=leaf_size,
n_jobs=n_jobs,
)
.get_clusters()
.get_shapely()
)
def _pandas_ex_color_cluster(
df,
colors,
reverse_colors=True,
backend="C",
memorylimit_mb=10000,
eps=10,
min_samples=3,
algorithm="auto",
leaf_size=30,
n_jobs=5,
max_width=100,
max_height=100,
interpolation=cv2.INTER_NEAREST,
column="aa_screenshot",
with_sendevent=False,
):
r"""
Perform color clustering on images in a DataFrame column and add the cluster information to the DataFrame.
Parameters:
- df (DataFrameWithMeta): Input DataFrame with image data and metadata.
- colors (list): List of colors to identify clusters.
- reverse_colors (bool, optional): Whether to reverse the order of colors. Defaults to True.
- backend (str, optional): The backend for Euclidean distance calculation. Defaults to "C".
- memorylimit_mb (int, optional): Memory limit in megabytes for the Euclidean distance matrix.
Defaults to 10000.
- eps (float, optional): The maximum distance between two samples for one to be considered as in
the neighborhood of the other. Defaults to 10.
- min_samples (int, optional): The number of samples in a neighborhood for a point to be
considered as a core point. Defaults to 3.
- algorithm (str, optional): The algorithm to compute nearest neighbors. Defaults to "auto".
- leaf_size (int, optional): Leaf size passed to BallTree or KDTree. Defaults to 30.
- n_jobs (int, optional): The number of parallel jobs to run for DBSCAN. Defaults to 5.
- max_width (int, optional): Maximum width for resizing the image. Defaults to 100.
- max_height (int, optional): Maximum height for resizing the image. Defaults to 100.
- interpolation (int, optional): Interpolation method for resizing the image.
Defaults to cv2.INTER_NEAREST.
- column (str, optional): The column containing image data. Defaults to "aa_screenshot".
- with_sendevent (bool, optional): Whether to include sendevent methods in the output DataFrame.
Defaults to False.
Returns:
- DataFrameWithMetaShaply: DataFrame with added color cluster information and methods for interaction
with the clusters.
Example:
```
df = DataFrameWithMeta()
df["aa_screenshot"] = [...] # Add image data to the DataFrame
df["aa_start_x"] = [...] # Add metadata to the DataFrame
clustered_df = _pandas_ex_color_cluster(
df=df,
colors=[(255, 0, 0), (0, 255, 0), (0, 0, 255)],
reverse_colors=True,
backend="C",
memorylimit_mb=10000,
eps=10,
min_samples=3,
algorithm="auto",
leaf_size=30,
n_jobs=5,
max_width=100,
max_height=100,
interpolation=cv2.INTER_NEAREST,
column="aa_screenshot",
with_sendevent=True,
)
print(clustered_df)
```
Note:
- This function applies color clustering to images in the specified DataFrame column.
- The resulting DataFrame includes additional columns with color cluster information and methods for interaction.
```
"""
with_input_tap = True
aa_color_cluster = df[column].ds_apply_ignore(
pd.NA,
lambda img: _get_pandas_ex_color_cluster(
img,
colors,
reverse_colors=reverse_colors,
backend=backend,
memorylimit_mb=memorylimit_mb,
eps=eps,
min_samples=min_samples,
algorithm=algorithm,
leaf_size=leaf_size,
n_jobs=n_jobs,
max_width=max_width,
max_height=max_height,
interpolation=interpolation,
),
)
importantdata = []
for i, item in zip(df.index, aa_color_cluster):
if not pd.isna(item):
importantdata.append(
pd.DataFrame(item.shapelydata).T.assign(
aa_img_index=i, aa_colorcluster=item
)
)
dfshapely = pd.concat(importantdata, ignore_index=True)
dfshapely["aa_center_cluster_x"] = dfshapely.ds_apply_ignore(
pd.NA,
lambda x: x["representative_point"][0] + df.loc[x.aa_img_index].aa_start_x,
axis=1,
)
dfshapely["aa_center_cluster_y"] = dfshapely.ds_apply_ignore(
pd.NA,
lambda x: x["representative_point"][1] + df.loc[x.aa_img_index].aa_start_y,
axis=1,
)
dfshapely = DataFrameWithMeta(
dfshapely,
adb_instance=df.adb_instance,
)