Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

Sorter.py 31 KB

You have to be logged in to leave a comment. Sign In
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
  1. import math
  2. import multiprocessing
  3. import operator
  4. import os
  5. import sys
  6. import tempfile
  7. from functools import cmp_to_key
  8. from pathlib import Path
  9. import cv2
  10. import numpy as np
  11. from numpy import linalg as npla
  12. from core import imagelib, mathlib, pathex
  13. from core.cv2ex import *
  14. from core.imagelib import estimate_sharpness
  15. from core.interact import interact as io
  16. from core.joblib import Subprocessor
  17. from core.leras import nn
  18. from DFLIMG import *
  19. from facelib import LandmarksProcessor
  20. class BlurEstimatorSubprocessor(Subprocessor):
  21. class Cli(Subprocessor.Cli):
  22. def on_initialize(self, client_dict):
  23. self.estimate_motion_blur = client_dict['estimate_motion_blur']
  24. #override
  25. def process_data(self, data):
  26. filepath = Path( data[0] )
  27. dflimg = DFLIMG.load (filepath)
  28. if dflimg is None or not dflimg.has_data():
  29. self.log_err (f"{filepath.name} is not a dfl image file")
  30. return [ str(filepath), 0 ]
  31. else:
  32. image = cv2_imread( str(filepath) )
  33. face_mask = LandmarksProcessor.get_image_hull_mask (image.shape, dflimg.get_landmarks())
  34. image = (image*face_mask).astype(np.uint8)
  35. if self.estimate_motion_blur:
  36. value = cv2.Laplacian(image, cv2.CV_64F, ksize=11).var()
  37. else:
  38. value = estimate_sharpness(image)
  39. return [ str(filepath), value ]
  40. #override
  41. def get_data_name (self, data):
  42. #return string identificator of your data
  43. return data[0]
  44. #override
  45. def __init__(self, input_data, estimate_motion_blur=False ):
  46. self.input_data = input_data
  47. self.estimate_motion_blur = estimate_motion_blur
  48. self.img_list = []
  49. self.trash_img_list = []
  50. super().__init__('BlurEstimator', BlurEstimatorSubprocessor.Cli, 60)
  51. #override
  52. def on_clients_initialized(self):
  53. io.progress_bar ("", len (self.input_data))
  54. #override
  55. def on_clients_finalized(self):
  56. io.progress_bar_close ()
  57. #override
  58. def process_info_generator(self):
  59. cpu_count = multiprocessing.cpu_count()
  60. io.log_info(f'Running on {cpu_count} CPUs')
  61. for i in range(cpu_count):
  62. yield 'CPU%d' % (i), {}, {'estimate_motion_blur':self.estimate_motion_blur}
  63. #override
  64. def get_data(self, host_dict):
  65. if len (self.input_data) > 0:
  66. return self.input_data.pop(0)
  67. return None
  68. #override
  69. def on_data_return (self, host_dict, data):
  70. self.input_data.insert(0, data)
  71. #override
  72. def on_result (self, host_dict, data, result):
  73. if result[1] == 0:
  74. self.trash_img_list.append ( result )
  75. else:
  76. self.img_list.append ( result )
  77. io.progress_bar_inc(1)
  78. #override
  79. def get_result(self):
  80. return self.img_list, self.trash_img_list
  81. def sort_by_blur(input_path):
  82. io.log_info ("Sorting by blur...")
  83. img_list = [ (filename,[]) for filename in pathex.get_image_paths(input_path) ]
  84. img_list, trash_img_list = BlurEstimatorSubprocessor (img_list).run()
  85. io.log_info ("Sorting...")
  86. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  87. return img_list, trash_img_list
  88. def sort_by_motion_blur(input_path):
  89. io.log_info ("Sorting by motion blur...")
  90. img_list = [ (filename,[]) for filename in pathex.get_image_paths(input_path) ]
  91. img_list, trash_img_list = BlurEstimatorSubprocessor (img_list, estimate_motion_blur=True).run()
  92. io.log_info ("Sorting...")
  93. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  94. return img_list, trash_img_list
  95. def sort_by_face_yaw(input_path):
  96. io.log_info ("Sorting by face yaw...")
  97. img_list = []
  98. trash_img_list = []
  99. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
  100. filepath = Path(filepath)
  101. dflimg = DFLIMG.load (filepath)
  102. if dflimg is None or not dflimg.has_data():
  103. io.log_err (f"{filepath.name} is not a dfl image file")
  104. trash_img_list.append ( [str(filepath)] )
  105. continue
  106. pitch, yaw, roll = LandmarksProcessor.estimate_pitch_yaw_roll ( dflimg.get_landmarks(), size=dflimg.get_shape()[1] )
  107. img_list.append( [str(filepath), yaw ] )
  108. io.log_info ("Sorting...")
  109. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  110. return img_list, trash_img_list
  111. def sort_by_face_pitch(input_path):
  112. io.log_info ("Sorting by face pitch...")
  113. img_list = []
  114. trash_img_list = []
  115. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
  116. filepath = Path(filepath)
  117. dflimg = DFLIMG.load (filepath)
  118. if dflimg is None or not dflimg.has_data():
  119. io.log_err (f"{filepath.name} is not a dfl image file")
  120. trash_img_list.append ( [str(filepath)] )
  121. continue
  122. pitch, yaw, roll = LandmarksProcessor.estimate_pitch_yaw_roll ( dflimg.get_landmarks(), size=dflimg.get_shape()[1] )
  123. img_list.append( [str(filepath), pitch ] )
  124. io.log_info ("Sorting...")
  125. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  126. return img_list, trash_img_list
  127. def sort_by_face_source_rect_size(input_path):
  128. io.log_info ("Sorting by face rect size...")
  129. img_list = []
  130. trash_img_list = []
  131. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
  132. filepath = Path(filepath)
  133. dflimg = DFLIMG.load (filepath)
  134. if dflimg is None or not dflimg.has_data():
  135. io.log_err (f"{filepath.name} is not a dfl image file")
  136. trash_img_list.append ( [str(filepath)] )
  137. continue
  138. source_rect = dflimg.get_source_rect()
  139. rect_area = mathlib.polygon_area(np.array(source_rect[[0,2,2,0]]).astype(np.float32), np.array(source_rect[[1,1,3,3]]).astype(np.float32))
  140. img_list.append( [str(filepath), rect_area ] )
  141. io.log_info ("Sorting...")
  142. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  143. return img_list, trash_img_list
  144. class HistSsimSubprocessor(Subprocessor):
  145. class Cli(Subprocessor.Cli):
  146. #override
  147. def process_data(self, data):
  148. img_list = []
  149. for x in data:
  150. img = cv2_imread(x)
  151. img_list.append ([x, cv2.calcHist([img], [0], None, [256], [0, 256]),
  152. cv2.calcHist([img], [1], None, [256], [0, 256]),
  153. cv2.calcHist([img], [2], None, [256], [0, 256])
  154. ])
  155. img_list_len = len(img_list)
  156. for i in range(img_list_len-1):
  157. min_score = float("inf")
  158. j_min_score = i+1
  159. for j in range(i+1,len(img_list)):
  160. score = cv2.compareHist(img_list[i][1], img_list[j][1], cv2.HISTCMP_BHATTACHARYYA) + \
  161. cv2.compareHist(img_list[i][2], img_list[j][2], cv2.HISTCMP_BHATTACHARYYA) + \
  162. cv2.compareHist(img_list[i][3], img_list[j][3], cv2.HISTCMP_BHATTACHARYYA)
  163. if score < min_score:
  164. min_score = score
  165. j_min_score = j
  166. img_list[i+1], img_list[j_min_score] = img_list[j_min_score], img_list[i+1]
  167. self.progress_bar_inc(1)
  168. return img_list
  169. #override
  170. def get_data_name (self, data):
  171. return "Bunch of images"
  172. #override
  173. def __init__(self, img_list ):
  174. self.img_list = img_list
  175. self.img_list_len = len(img_list)
  176. slice_count = 20000
  177. sliced_count = self.img_list_len // slice_count
  178. if sliced_count > 12:
  179. sliced_count = 11.9
  180. slice_count = int(self.img_list_len / sliced_count)
  181. sliced_count = self.img_list_len // slice_count
  182. self.img_chunks_list = [ self.img_list[i*slice_count : (i+1)*slice_count] for i in range(sliced_count) ] + \
  183. [ self.img_list[sliced_count*slice_count:] ]
  184. self.result = []
  185. super().__init__('HistSsim', HistSsimSubprocessor.Cli, 0)
  186. #override
  187. def process_info_generator(self):
  188. cpu_count = len(self.img_chunks_list)
  189. io.log_info(f'Running on {cpu_count} threads')
  190. for i in range(cpu_count):
  191. yield 'CPU%d' % (i), {'i':i}, {}
  192. #override
  193. def on_clients_initialized(self):
  194. io.progress_bar ("Sorting", len(self.img_list))
  195. io.progress_bar_inc(len(self.img_chunks_list))
  196. #override
  197. def on_clients_finalized(self):
  198. io.progress_bar_close()
  199. #override
  200. def get_data(self, host_dict):
  201. if len (self.img_chunks_list) > 0:
  202. return self.img_chunks_list.pop(0)
  203. return None
  204. #override
  205. def on_data_return (self, host_dict, data):
  206. raise Exception("Fail to process data. Decrease number of images and try again.")
  207. #override
  208. def on_result (self, host_dict, data, result):
  209. self.result += result
  210. return 0
  211. #override
  212. def get_result(self):
  213. return self.result
  214. def sort_by_hist(input_path):
  215. io.log_info ("Sorting by histogram similarity...")
  216. img_list = HistSsimSubprocessor(pathex.get_image_paths(input_path)).run()
  217. return img_list, []
  218. class HistDissimSubprocessor(Subprocessor):
  219. class Cli(Subprocessor.Cli):
  220. #override
  221. def on_initialize(self, client_dict):
  222. self.img_list = client_dict['img_list']
  223. self.img_list_len = len(self.img_list)
  224. #override
  225. def process_data(self, data):
  226. i = data[0]
  227. score_total = 0
  228. for j in range( 0, self.img_list_len):
  229. if i == j:
  230. continue
  231. score_total += cv2.compareHist(self.img_list[i][1], self.img_list[j][1], cv2.HISTCMP_BHATTACHARYYA)
  232. return score_total
  233. #override
  234. def get_data_name (self, data):
  235. #return string identificator of your data
  236. return self.img_list[data[0]][0]
  237. #override
  238. def __init__(self, img_list ):
  239. self.img_list = img_list
  240. self.img_list_range = [i for i in range(0, len(img_list) )]
  241. self.result = []
  242. super().__init__('HistDissim', HistDissimSubprocessor.Cli, 60)
  243. #override
  244. def on_clients_initialized(self):
  245. io.progress_bar ("Sorting", len (self.img_list) )
  246. #override
  247. def on_clients_finalized(self):
  248. io.progress_bar_close()
  249. #override
  250. def process_info_generator(self):
  251. cpu_count = min(multiprocessing.cpu_count(), 8)
  252. io.log_info(f'Running on {cpu_count} CPUs')
  253. for i in range(cpu_count):
  254. yield 'CPU%d' % (i), {}, {'img_list' : self.img_list}
  255. #override
  256. def get_data(self, host_dict):
  257. if len (self.img_list_range) > 0:
  258. return [self.img_list_range.pop(0)]
  259. return None
  260. #override
  261. def on_data_return (self, host_dict, data):
  262. self.img_list_range.insert(0, data[0])
  263. #override
  264. def on_result (self, host_dict, data, result):
  265. self.img_list[data[0]][2] = result
  266. io.progress_bar_inc(1)
  267. #override
  268. def get_result(self):
  269. return self.img_list
  270. def sort_by_hist_dissim(input_path):
  271. io.log_info ("Sorting by histogram dissimilarity...")
  272. img_list = []
  273. trash_img_list = []
  274. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
  275. filepath = Path(filepath)
  276. dflimg = DFLIMG.load (filepath)
  277. image = cv2_imread(str(filepath))
  278. if dflimg is not None and dflimg.has_data():
  279. face_mask = LandmarksProcessor.get_image_hull_mask (image.shape, dflimg.get_landmarks())
  280. image = (image*face_mask).astype(np.uint8)
  281. img_list.append ([str(filepath), cv2.calcHist([cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)], [0], None, [256], [0, 256]), 0 ])
  282. img_list = HistDissimSubprocessor(img_list).run()
  283. io.log_info ("Sorting...")
  284. img_list = sorted(img_list, key=operator.itemgetter(2), reverse=True)
  285. return img_list, trash_img_list
  286. def sort_by_brightness(input_path):
  287. io.log_info ("Sorting by brightness...")
  288. img_list = [ [x, np.mean ( cv2.cvtColor(cv2_imread(x), cv2.COLOR_BGR2HSV)[...,2].flatten() )] for x in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading") ]
  289. io.log_info ("Sorting...")
  290. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  291. return img_list, []
  292. def sort_by_hue(input_path):
  293. io.log_info ("Sorting by hue...")
  294. img_list = [ [x, np.mean ( cv2.cvtColor(cv2_imread(x), cv2.COLOR_BGR2HSV)[...,0].flatten() )] for x in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading") ]
  295. io.log_info ("Sorting...")
  296. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  297. return img_list, []
  298. def sort_by_black(input_path):
  299. io.log_info ("Sorting by amount of black pixels...")
  300. img_list = []
  301. for x in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
  302. img = cv2_imread(x)
  303. img_list.append ([x, img[(img == 0)].size ])
  304. io.log_info ("Sorting...")
  305. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=False)
  306. return img_list, []
  307. def sort_by_origname(input_path):
  308. io.log_info ("Sort by original filename...")
  309. img_list = []
  310. trash_img_list = []
  311. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
  312. filepath = Path(filepath)
  313. dflimg = DFLIMG.load (filepath)
  314. if dflimg is None or not dflimg.has_data():
  315. io.log_err (f"{filepath.name} is not a dfl image file")
  316. trash_img_list.append( [str(filepath)] )
  317. continue
  318. img_list.append( [str(filepath), dflimg.get_source_filename()] )
  319. io.log_info ("Sorting...")
  320. img_list = sorted(img_list, key=operator.itemgetter(1))
  321. return img_list, trash_img_list
  322. def sort_by_oneface_in_image(input_path):
  323. io.log_info ("Sort by one face in images...")
  324. image_paths = pathex.get_image_paths(input_path)
  325. a = np.array ([ ( int(x[0]), int(x[1]) ) \
  326. for x in [ Path(filepath).stem.split('_') for filepath in image_paths ] if len(x) == 2
  327. ])
  328. if len(a) > 0:
  329. idxs = np.ndarray.flatten ( np.argwhere ( a[:,1] != 0 ) )
  330. idxs = np.unique ( a[idxs][:,0] )
  331. idxs = np.ndarray.flatten ( np.argwhere ( np.array([ x[0] in idxs for x in a ]) == True ) )
  332. if len(idxs) > 0:
  333. io.log_info ("Found %d images." % (len(idxs)) )
  334. img_list = [ (path,) for i,path in enumerate(image_paths) if i not in idxs ]
  335. trash_img_list = [ (image_paths[x],) for x in idxs ]
  336. return img_list, trash_img_list
  337. io.log_info ("Nothing found. Possible recover original filenames first.")
  338. return [], []
  339. class FinalLoaderSubprocessor(Subprocessor):
  340. class Cli(Subprocessor.Cli):
  341. #override
  342. def on_initialize(self, client_dict):
  343. self.faster = client_dict['faster']
  344. #override
  345. def process_data(self, data):
  346. filepath = Path(data[0])
  347. try:
  348. dflimg = DFLIMG.load (filepath)
  349. if dflimg is None or not dflimg.has_data():
  350. self.log_err (f"{filepath.name} is not a dfl image file")
  351. return [ 1, [str(filepath)] ]
  352. bgr = cv2_imread(str(filepath))
  353. if bgr is None:
  354. raise Exception ("Unable to load %s" % (filepath.name) )
  355. gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
  356. if self.faster:
  357. source_rect = dflimg.get_source_rect()
  358. sharpness = mathlib.polygon_area(np.array(source_rect[[0,2,2,0]]).astype(np.float32), np.array(source_rect[[1,1,3,3]]).astype(np.float32))
  359. else:
  360. face_mask = LandmarksProcessor.get_image_hull_mask (gray.shape, dflimg.get_landmarks())
  361. sharpness = estimate_sharpness( (gray[...,None]*face_mask).astype(np.uint8) )
  362. pitch, yaw, roll = LandmarksProcessor.estimate_pitch_yaw_roll ( dflimg.get_landmarks(), size=dflimg.get_shape()[1] )
  363. hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
  364. except Exception as e:
  365. self.log_err (e)
  366. return [ 1, [str(filepath)] ]
  367. return [ 0, [str(filepath), sharpness, hist, yaw, pitch ] ]
  368. #override
  369. def get_data_name (self, data):
  370. #return string identificator of your data
  371. return data[0]
  372. #override
  373. def __init__(self, img_list, faster ):
  374. self.img_list = img_list
  375. self.faster = faster
  376. self.result = []
  377. self.result_trash = []
  378. super().__init__('FinalLoader', FinalLoaderSubprocessor.Cli, 60)
  379. #override
  380. def on_clients_initialized(self):
  381. io.progress_bar ("Loading", len (self.img_list))
  382. #override
  383. def on_clients_finalized(self):
  384. io.progress_bar_close()
  385. #override
  386. def process_info_generator(self):
  387. cpu_count = min(multiprocessing.cpu_count(), 8)
  388. io.log_info(f'Running on {cpu_count} CPUs')
  389. for i in range(cpu_count):
  390. yield 'CPU%d' % (i), {}, {'faster': self.faster}
  391. #override
  392. def get_data(self, host_dict):
  393. if len (self.img_list) > 0:
  394. return [self.img_list.pop(0)]
  395. return None
  396. #override
  397. def on_data_return (self, host_dict, data):
  398. self.img_list.insert(0, data[0])
  399. #override
  400. def on_result (self, host_dict, data, result):
  401. if result[0] == 0:
  402. self.result.append (result[1])
  403. else:
  404. self.result_trash.append (result[1])
  405. io.progress_bar_inc(1)
  406. #override
  407. def get_result(self):
  408. return self.result, self.result_trash
  409. class FinalHistDissimSubprocessor(Subprocessor):
  410. class Cli(Subprocessor.Cli):
  411. #override
  412. def process_data(self, data):
  413. idx, pitch_yaw_img_list = data
  414. for p in range ( len(pitch_yaw_img_list) ):
  415. img_list = pitch_yaw_img_list[p]
  416. if img_list is not None:
  417. for i in range( len(img_list) ):
  418. score_total = 0
  419. for j in range( len(img_list) ):
  420. if i == j:
  421. continue
  422. score_total += cv2.compareHist(img_list[i][2], img_list[j][2], cv2.HISTCMP_BHATTACHARYYA)
  423. img_list[i][3] = score_total
  424. pitch_yaw_img_list[p] = sorted(img_list, key=operator.itemgetter(3), reverse=True)
  425. return idx, pitch_yaw_img_list
  426. #override
  427. def get_data_name (self, data):
  428. return "Bunch of images"
  429. #override
  430. def __init__(self, pitch_yaw_sample_list ):
  431. self.pitch_yaw_sample_list = pitch_yaw_sample_list
  432. self.pitch_yaw_sample_list_len = len(pitch_yaw_sample_list)
  433. self.pitch_yaw_sample_list_idxs = [ i for i in range(self.pitch_yaw_sample_list_len) if self.pitch_yaw_sample_list[i] is not None ]
  434. self.result = [ None for _ in range(self.pitch_yaw_sample_list_len) ]
  435. super().__init__('FinalHistDissimSubprocessor', FinalHistDissimSubprocessor.Cli)
  436. #override
  437. def process_info_generator(self):
  438. cpu_count = min(multiprocessing.cpu_count(), 8)
  439. io.log_info(f'Running on {cpu_count} CPUs')
  440. for i in range(cpu_count):
  441. yield 'CPU%d' % (i), {}, {}
  442. #override
  443. def on_clients_initialized(self):
  444. io.progress_bar ("Sort by hist-dissim", len(self.pitch_yaw_sample_list_idxs) )
  445. #override
  446. def on_clients_finalized(self):
  447. io.progress_bar_close()
  448. #override
  449. def get_data(self, host_dict):
  450. if len (self.pitch_yaw_sample_list_idxs) > 0:
  451. idx = self.pitch_yaw_sample_list_idxs.pop(0)
  452. return idx, self.pitch_yaw_sample_list[idx]
  453. return None
  454. #override
  455. def on_data_return (self, host_dict, data):
  456. self.pitch_yaw_sample_list_idxs.insert(0, data[0])
  457. #override
  458. def on_result (self, host_dict, data, result):
  459. idx, yaws_sample_list = data
  460. self.result[idx] = yaws_sample_list
  461. io.progress_bar_inc(1)
  462. #override
  463. def get_result(self):
  464. return self.result
  465. def sort_best_faster(input_path):
  466. return sort_best(input_path, faster=True)
  467. def sort_best(input_path, faster=False):
  468. target_count = io.input_int ("Target number of faces?", 2000)
  469. io.log_info ("Performing sort by best faces.")
  470. if faster:
  471. io.log_info("Using faster algorithm. Faces will be sorted by source-rect-area instead of blur.")
  472. img_list, trash_img_list = FinalLoaderSubprocessor( pathex.get_image_paths(input_path), faster ).run()
  473. final_img_list = []
  474. grads = 128
  475. imgs_per_grad = round (target_count / grads)
  476. #instead of math.pi / 2, using -1.2,+1.2 because actually maximum yaw for 2DFAN landmarks are -1.2+1.2
  477. grads_space = np.linspace (-1.2, 1.2,grads)
  478. yaws_sample_list = [None]*grads
  479. for g in io.progress_bar_generator ( range(grads), "Sort by yaw"):
  480. yaw = grads_space[g]
  481. next_yaw = grads_space[g+1] if g < grads-1 else yaw
  482. yaw_samples = []
  483. for img in img_list:
  484. s_yaw = -img[3]
  485. if (g == 0 and s_yaw < next_yaw) or \
  486. (g < grads-1 and s_yaw >= yaw and s_yaw < next_yaw) or \
  487. (g == grads-1 and s_yaw >= yaw):
  488. yaw_samples += [ img ]
  489. if len(yaw_samples) > 0:
  490. yaws_sample_list[g] = yaw_samples
  491. total_lack = 0
  492. for g in io.progress_bar_generator ( range(grads), ""):
  493. img_list = yaws_sample_list[g]
  494. img_list_len = len(img_list) if img_list is not None else 0
  495. lack = imgs_per_grad - img_list_len
  496. total_lack += max(lack, 0)
  497. imgs_per_grad += total_lack // grads
  498. sharpned_imgs_per_grad = imgs_per_grad*10
  499. for g in io.progress_bar_generator ( range (grads), "Sort by blur"):
  500. img_list = yaws_sample_list[g]
  501. if img_list is None:
  502. continue
  503. img_list = sorted(img_list, key=operator.itemgetter(1), reverse=True)
  504. if len(img_list) > sharpned_imgs_per_grad:
  505. trash_img_list += img_list[sharpned_imgs_per_grad:]
  506. img_list = img_list[0:sharpned_imgs_per_grad]
  507. yaws_sample_list[g] = img_list
  508. yaw_pitch_sample_list = [None]*grads
  509. pitch_grads = imgs_per_grad
  510. for g in io.progress_bar_generator ( range (grads), "Sort by pitch"):
  511. img_list = yaws_sample_list[g]
  512. if img_list is None:
  513. continue
  514. pitch_sample_list = [None]*pitch_grads
  515. grads_space = np.linspace (-math.pi / 2,math.pi / 2, pitch_grads )
  516. for pg in range (pitch_grads):
  517. pitch = grads_space[pg]
  518. next_pitch = grads_space[pg+1] if pg < pitch_grads-1 else pitch
  519. pitch_samples = []
  520. for img in img_list:
  521. s_pitch = img[4]
  522. if (pg == 0 and s_pitch < next_pitch) or \
  523. (pg < pitch_grads-1 and s_pitch >= pitch and s_pitch < next_pitch) or \
  524. (pg == pitch_grads-1 and s_pitch >= pitch):
  525. pitch_samples += [ img ]
  526. if len(pitch_samples) > 0:
  527. pitch_sample_list[pg] = pitch_samples
  528. yaw_pitch_sample_list[g] = pitch_sample_list
  529. yaw_pitch_sample_list = FinalHistDissimSubprocessor(yaw_pitch_sample_list).run()
  530. for g in io.progress_bar_generator (range (grads), "Fetching the best"):
  531. pitch_sample_list = yaw_pitch_sample_list[g]
  532. if pitch_sample_list is None:
  533. continue
  534. n = imgs_per_grad
  535. while n > 0:
  536. n_prev = n
  537. for pg in range(pitch_grads):
  538. img_list = pitch_sample_list[pg]
  539. if img_list is None:
  540. continue
  541. final_img_list += [ img_list.pop(0) ]
  542. if len(img_list) == 0:
  543. pitch_sample_list[pg] = None
  544. n -= 1
  545. if n == 0:
  546. break
  547. if n_prev == n:
  548. break
  549. for pg in range(pitch_grads):
  550. img_list = pitch_sample_list[pg]
  551. if img_list is None:
  552. continue
  553. trash_img_list += img_list
  554. return final_img_list, trash_img_list
  555. """
  556. def sort_by_vggface(input_path):
  557. io.log_info ("Sorting by face similarity using VGGFace model...")
  558. model = VGGFace()
  559. final_img_list = []
  560. trash_img_list = []
  561. image_paths = pathex.get_image_paths(input_path)
  562. img_list = [ (x,) for x in image_paths ]
  563. img_list_len = len(img_list)
  564. img_list_range = [*range(img_list_len)]
  565. feats = [None]*img_list_len
  566. for i in io.progress_bar_generator(img_list_range, "Loading"):
  567. img = cv2_imread( img_list[i][0] ).astype(np.float32)
  568. img = imagelib.normalize_channels (img, 3)
  569. img = cv2.resize (img, (224,224) )
  570. img = img[..., ::-1]
  571. img[..., 0] -= 93.5940
  572. img[..., 1] -= 104.7624
  573. img[..., 2] -= 129.1863
  574. feats[i] = model.predict( img[None,...] )[0]
  575. tmp = np.zeros( (img_list_len,) )
  576. float_inf = float("inf")
  577. for i in io.progress_bar_generator ( range(img_list_len-1), "Sorting" ):
  578. i_feat = feats[i]
  579. for j in img_list_range:
  580. tmp[j] = npla.norm(i_feat-feats[j]) if j >= i+1 else float_inf
  581. idx = np.argmin(tmp)
  582. img_list[i+1], img_list[idx] = img_list[idx], img_list[i+1]
  583. feats[i+1], feats[idx] = feats[idx], feats[i+1]
  584. return img_list, trash_img_list
  585. """
  586. def sort_by_absdiff(input_path):
  587. io.log_info ("Sorting by absolute difference...")
  588. is_sim = io.input_bool ("Sort by similar?", True, help_message="Otherwise sort by dissimilar.")
  589. from core.leras import nn
  590. device_config = nn.DeviceConfig.ask_choose_device(choose_only_one=True)
  591. nn.initialize( device_config=device_config, data_format="NHWC" )
  592. tf = nn.tf
  593. image_paths = pathex.get_image_paths(input_path)
  594. image_paths_len = len(image_paths)
  595. batch_size = 512
  596. batch_size_remain = image_paths_len % batch_size
  597. i_t = tf.placeholder (tf.float32, (None,None,None,None) )
  598. j_t = tf.placeholder (tf.float32, (None,None,None,None) )
  599. outputs_full = []
  600. outputs_remain = []
  601. for i in range(batch_size):
  602. diff_t = tf.reduce_sum( tf.abs(i_t-j_t[i]), axis=[1,2,3] )
  603. outputs_full.append(diff_t)
  604. if i < batch_size_remain:
  605. outputs_remain.append(diff_t)
  606. def func_bs_full(i,j):
  607. return nn.tf_sess.run (outputs_full, feed_dict={i_t:i,j_t:j})
  608. def func_bs_remain(i,j):
  609. return nn.tf_sess.run (outputs_remain, feed_dict={i_t:i,j_t:j})
  610. import h5py
  611. db_file_path = Path(tempfile.gettempdir()) / 'sort_cache.hdf5'
  612. db_file = h5py.File( str(db_file_path), "w")
  613. db = db_file.create_dataset("results", (image_paths_len,image_paths_len), compression="gzip")
  614. pg_len = image_paths_len // batch_size
  615. if batch_size_remain != 0:
  616. pg_len += 1
  617. pg_len = int( ( pg_len*pg_len - pg_len ) / 2 + pg_len )
  618. io.progress_bar ("Computing", pg_len)
  619. j=0
  620. while j < image_paths_len:
  621. j_images = [ cv2_imread(x) for x in image_paths[j:j+batch_size] ]
  622. j_images_len = len(j_images)
  623. func = func_bs_remain if image_paths_len-j < batch_size else func_bs_full
  624. i=0
  625. while i < image_paths_len:
  626. if i >= j:
  627. i_images = [ cv2_imread(x) for x in image_paths[i:i+batch_size] ]
  628. i_images_len = len(i_images)
  629. result = func (i_images,j_images)
  630. db[j:j+j_images_len,i:i+i_images_len] = np.array(result)
  631. io.progress_bar_inc(1)
  632. i += batch_size
  633. db_file.flush()
  634. j += batch_size
  635. io.progress_bar_close()
  636. next_id = 0
  637. sorted = [next_id]
  638. for i in io.progress_bar_generator ( range(image_paths_len-1), "Sorting" ):
  639. id_ar = np.concatenate ( [ db[:next_id,next_id], db[next_id,next_id:] ] )
  640. id_ar = np.argsort(id_ar)
  641. next_id = np.setdiff1d(id_ar, sorted, True)[ 0 if is_sim else -1]
  642. sorted += [next_id]
  643. db_file.close()
  644. db_file_path.unlink()
  645. img_list = [ (image_paths[x],) for x in sorted]
  646. return img_list, []
  647. def final_process(input_path, img_list, trash_img_list):
  648. if len(trash_img_list) != 0:
  649. parent_input_path = input_path.parent
  650. trash_path = parent_input_path / (input_path.stem + '_trash')
  651. trash_path.mkdir (exist_ok=True)
  652. io.log_info ("Trashing %d items to %s" % ( len(trash_img_list), str(trash_path) ) )
  653. for filename in pathex.get_image_paths(trash_path):
  654. Path(filename).unlink()
  655. for i in io.progress_bar_generator( range(len(trash_img_list)), "Moving trash", leave=False):
  656. src = Path (trash_img_list[i][0])
  657. dst = trash_path / src.name
  658. try:
  659. src.rename (dst)
  660. except:
  661. io.log_info ('fail to trashing %s' % (src.name) )
  662. io.log_info ("")
  663. if len(img_list) != 0:
  664. for i in io.progress_bar_generator( [*range(len(img_list))], "Renaming", leave=False):
  665. src = Path (img_list[i][0])
  666. dst = input_path / ('%.5d_%s' % (i, src.name ))
  667. try:
  668. src.rename (dst)
  669. except:
  670. io.log_info ('fail to rename %s' % (src.name) )
  671. for i in io.progress_bar_generator( [*range(len(img_list))], "Renaming"):
  672. src = Path (img_list[i][0])
  673. src = input_path / ('%.5d_%s' % (i, src.name))
  674. dst = input_path / ('%.5d%s' % (i, src.suffix))
  675. try:
  676. src.rename (dst)
  677. except:
  678. io.log_info ('fail to rename %s' % (src.name) )
  679. sort_func_methods = {
  680. 'blur': ("blur", sort_by_blur),
  681. 'motion-blur': ("motion_blur", sort_by_motion_blur),
  682. 'face-yaw': ("face yaw direction", sort_by_face_yaw),
  683. 'face-pitch': ("face pitch direction", sort_by_face_pitch),
  684. 'face-source-rect-size' : ("face rect size in source image", sort_by_face_source_rect_size),
  685. 'hist': ("histogram similarity", sort_by_hist),
  686. 'hist-dissim': ("histogram dissimilarity", sort_by_hist_dissim),
  687. 'brightness': ("brightness", sort_by_brightness),
  688. 'hue': ("hue", sort_by_hue),
  689. 'black': ("amount of black pixels", sort_by_black),
  690. 'origname': ("original filename", sort_by_origname),
  691. 'oneface': ("one face in image", sort_by_oneface_in_image),
  692. 'absdiff': ("absolute pixel difference", sort_by_absdiff),
  693. 'final': ("best faces", sort_best),
  694. 'final-fast': ("best faces faster", sort_best_faster),
  695. }
  696. def main (input_path, sort_by_method=None):
  697. io.log_info ("Running sort tool.\r\n")
  698. if sort_by_method is None:
  699. io.log_info(f"Choose sorting method:")
  700. key_list = list(sort_func_methods.keys())
  701. for i, key in enumerate(key_list):
  702. desc, func = sort_func_methods[key]
  703. io.log_info(f"[{i}] {desc}")
  704. io.log_info("")
  705. id = io.input_int("", 5, valid_list=[*range(len(key_list))] )
  706. sort_by_method = key_list[id]
  707. else:
  708. sort_by_method = sort_by_method.lower()
  709. desc, func = sort_func_methods[sort_by_method]
  710. img_list, trash_img_list = func(input_path)
  711. final_process (input_path, img_list, trash_img_list)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...