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

Extractor.py 38 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
  1. import traceback
  2. import math
  3. import multiprocessing
  4. import operator
  5. import os
  6. import shutil
  7. import sys
  8. import time
  9. from pathlib import Path
  10. import cv2
  11. import numpy as np
  12. from numpy import linalg as npla
  13. import facelib
  14. from core import imagelib
  15. from core import mathlib
  16. from facelib import FaceType, LandmarksProcessor
  17. from core.interact import interact as io
  18. from core.joblib import Subprocessor
  19. from core.leras import nn
  20. from core import pathex
  21. from core.cv2ex import *
  22. from DFLIMG import *
  23. DEBUG = False
  24. class ExtractSubprocessor(Subprocessor):
  25. class Data(object):
  26. def __init__(self, filepath=None, rects=None, landmarks = None, landmarks_accurate=True, manual=False, force_output_path=None, final_output_files = None):
  27. self.filepath = filepath
  28. self.rects = rects or []
  29. self.rects_rotation = 0
  30. self.landmarks_accurate = landmarks_accurate
  31. self.manual = manual
  32. self.landmarks = landmarks or []
  33. self.force_output_path = force_output_path
  34. self.final_output_files = final_output_files or []
  35. self.faces_detected = 0
  36. class Cli(Subprocessor.Cli):
  37. #override
  38. def on_initialize(self, client_dict):
  39. self.type = client_dict['type']
  40. self.image_size = client_dict['image_size']
  41. self.jpeg_quality = client_dict['jpeg_quality']
  42. self.face_type = client_dict['face_type']
  43. self.max_faces_from_image = client_dict['max_faces_from_image']
  44. self.device_idx = client_dict['device_idx']
  45. self.cpu_only = client_dict['device_type'] == 'CPU'
  46. self.final_output_path = client_dict['final_output_path']
  47. self.output_debug_path = client_dict['output_debug_path']
  48. #transfer and set stdin in order to work code.interact in debug subprocess
  49. stdin_fd = client_dict['stdin_fd']
  50. if stdin_fd is not None and DEBUG:
  51. sys.stdin = os.fdopen(stdin_fd)
  52. if self.cpu_only:
  53. device_config = nn.DeviceConfig.CPU()
  54. place_model_on_cpu = True
  55. else:
  56. device_config = nn.DeviceConfig.GPUIndexes ([self.device_idx])
  57. place_model_on_cpu = device_config.devices[0].total_mem_gb < 4
  58. if self.type == 'all' or 'rects' in self.type or 'landmarks' in self.type:
  59. nn.initialize (device_config)
  60. self.log_info (f"Running on {client_dict['device_name'] }")
  61. if self.type == 'all' or self.type == 'rects-s3fd' or 'landmarks' in self.type:
  62. self.rects_extractor = facelib.S3FDExtractor(place_model_on_cpu=place_model_on_cpu)
  63. if self.type == 'all' or 'landmarks' in self.type:
  64. # for head type, extract "3D landmarks"
  65. self.landmarks_extractor = facelib.FANExtractor(landmarks_3D=self.face_type >= FaceType.HEAD,
  66. place_model_on_cpu=place_model_on_cpu)
  67. self.cached_image = (None, None)
  68. #override
  69. def process_data(self, data):
  70. if 'landmarks' in self.type and len(data.rects) == 0:
  71. return data
  72. filepath = data.filepath
  73. cached_filepath, image = self.cached_image
  74. if cached_filepath != filepath:
  75. image = cv2_imread( filepath )
  76. if image is None:
  77. self.log_err (f'Failed to open {filepath}, reason: cv2_imread() fail.')
  78. return data
  79. image = imagelib.normalize_channels(image, 3)
  80. image = imagelib.cut_odd_image(image)
  81. self.cached_image = ( filepath, image )
  82. h, w, c = image.shape
  83. if 'rects' in self.type or self.type == 'all':
  84. data = ExtractSubprocessor.Cli.rects_stage (data=data,
  85. image=image,
  86. max_faces_from_image=self.max_faces_from_image,
  87. rects_extractor=self.rects_extractor,
  88. )
  89. if 'landmarks' in self.type or self.type == 'all':
  90. data = ExtractSubprocessor.Cli.landmarks_stage (data=data,
  91. image=image,
  92. landmarks_extractor=self.landmarks_extractor,
  93. rects_extractor=self.rects_extractor,
  94. )
  95. if self.type == 'final' or self.type == 'all':
  96. data = ExtractSubprocessor.Cli.final_stage(data=data,
  97. image=image,
  98. face_type=self.face_type,
  99. image_size=self.image_size,
  100. jpeg_quality=self.jpeg_quality,
  101. output_debug_path=self.output_debug_path,
  102. final_output_path=self.final_output_path,
  103. )
  104. return data
  105. @staticmethod
  106. def rects_stage(data,
  107. image,
  108. max_faces_from_image,
  109. rects_extractor,
  110. ):
  111. h,w,c = image.shape
  112. if min(h,w) < 128:
  113. # Image is too small
  114. data.rects = []
  115. else:
  116. for rot in ([0, 90, 270, 180]):
  117. if rot == 0:
  118. rotated_image = image
  119. elif rot == 90:
  120. rotated_image = image.swapaxes( 0,1 )[:,::-1,:]
  121. elif rot == 180:
  122. rotated_image = image[::-1,::-1,:]
  123. elif rot == 270:
  124. rotated_image = image.swapaxes( 0,1 )[::-1,:,:]
  125. rects = data.rects = rects_extractor.extract (rotated_image, is_bgr=True)
  126. if len(rects) != 0:
  127. data.rects_rotation = rot
  128. break
  129. if max_faces_from_image is not None and \
  130. max_faces_from_image > 0 and \
  131. len(data.rects) > 0:
  132. data.rects = data.rects[0:max_faces_from_image]
  133. return data
  134. @staticmethod
  135. def landmarks_stage(data,
  136. image,
  137. landmarks_extractor,
  138. rects_extractor,
  139. ):
  140. h, w, ch = image.shape
  141. if data.rects_rotation == 0:
  142. rotated_image = image
  143. elif data.rects_rotation == 90:
  144. rotated_image = image.swapaxes( 0,1 )[:,::-1,:]
  145. elif data.rects_rotation == 180:
  146. rotated_image = image[::-1,::-1,:]
  147. elif data.rects_rotation == 270:
  148. rotated_image = image.swapaxes( 0,1 )[::-1,:,:]
  149. data.landmarks = landmarks_extractor.extract (rotated_image, data.rects, rects_extractor if (data.landmarks_accurate) else None, is_bgr=True)
  150. if data.rects_rotation != 0:
  151. for i, (rect, lmrks) in enumerate(zip(data.rects, data.landmarks)):
  152. new_rect, new_lmrks = rect, lmrks
  153. (l,t,r,b) = rect
  154. if data.rects_rotation == 90:
  155. new_rect = ( t, h-l, b, h-r)
  156. if lmrks is not None:
  157. new_lmrks = lmrks[:,::-1].copy()
  158. new_lmrks[:,1] = h - new_lmrks[:,1]
  159. elif data.rects_rotation == 180:
  160. if lmrks is not None:
  161. new_rect = ( w-l, h-t, w-r, h-b)
  162. new_lmrks = lmrks.copy()
  163. new_lmrks[:,0] = w - new_lmrks[:,0]
  164. new_lmrks[:,1] = h - new_lmrks[:,1]
  165. elif data.rects_rotation == 270:
  166. new_rect = ( w-b, l, w-t, r )
  167. if lmrks is not None:
  168. new_lmrks = lmrks[:,::-1].copy()
  169. new_lmrks[:,0] = w - new_lmrks[:,0]
  170. data.rects[i], data.landmarks[i] = new_rect, new_lmrks
  171. return data
  172. @staticmethod
  173. def final_stage(data,
  174. image,
  175. face_type,
  176. image_size,
  177. jpeg_quality,
  178. output_debug_path=None,
  179. final_output_path=None,
  180. ):
  181. data.final_output_files = []
  182. filepath = data.filepath
  183. rects = data.rects
  184. landmarks = data.landmarks
  185. if output_debug_path is not None:
  186. debug_image = image.copy()
  187. face_idx = 0
  188. for rect, image_landmarks in zip( rects, landmarks ):
  189. if image_landmarks is None:
  190. continue
  191. rect = np.array(rect)
  192. if face_type == FaceType.MARK_ONLY:
  193. image_to_face_mat = None
  194. face_image = image
  195. face_image_landmarks = image_landmarks
  196. else:
  197. image_to_face_mat = LandmarksProcessor.get_transform_mat (image_landmarks, image_size, face_type)
  198. face_image = cv2.warpAffine(image, image_to_face_mat, (image_size, image_size), cv2.INTER_LANCZOS4)
  199. face_image_landmarks = LandmarksProcessor.transform_points (image_landmarks, image_to_face_mat)
  200. landmarks_bbox = LandmarksProcessor.transform_points ( [ (0,0), (0,image_size-1), (image_size-1, image_size-1), (image_size-1,0) ], image_to_face_mat, True)
  201. rect_area = mathlib.polygon_area(np.array(rect[[0,2,2,0]]).astype(np.float32), np.array(rect[[1,1,3,3]]).astype(np.float32))
  202. landmarks_area = mathlib.polygon_area(landmarks_bbox[:,0].astype(np.float32), landmarks_bbox[:,1].astype(np.float32) )
  203. if not data.manual and face_type <= FaceType.FULL_NO_ALIGN and landmarks_area > 4*rect_area: #get rid of faces which umeyama-landmark-area > 4*detector-rect-area
  204. continue
  205. if output_debug_path is not None:
  206. LandmarksProcessor.draw_rect_landmarks (debug_image, rect, image_landmarks, face_type, image_size, transparent_mask=True)
  207. output_path = final_output_path
  208. if data.force_output_path is not None:
  209. output_path = data.force_output_path
  210. output_filepath = output_path / f"{filepath.stem}_{face_idx}.jpg"
  211. cv2_imwrite(output_filepath, face_image, [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_quality ] )
  212. dflimg = DFLJPG.load(output_filepath)
  213. dflimg.set_face_type(FaceType.toString(face_type))
  214. dflimg.set_landmarks(face_image_landmarks.tolist())
  215. dflimg.set_source_filename(filepath.name)
  216. dflimg.set_source_rect(rect)
  217. dflimg.set_source_landmarks(image_landmarks.tolist())
  218. dflimg.set_image_to_face_mat(image_to_face_mat)
  219. dflimg.save()
  220. data.final_output_files.append (output_filepath)
  221. face_idx += 1
  222. data.faces_detected = face_idx
  223. if output_debug_path is not None:
  224. cv2_imwrite( output_debug_path / (filepath.stem+'.jpg'), debug_image, [int(cv2.IMWRITE_JPEG_QUALITY), 50] )
  225. return data
  226. #overridable
  227. def get_data_name (self, data):
  228. #return string identificator of your data
  229. return data.filepath
  230. @staticmethod
  231. def get_devices_for_config (type, device_config):
  232. devices = device_config.devices
  233. cpu_only = len(devices) == 0
  234. if 'rects' in type or \
  235. 'landmarks' in type or \
  236. 'all' in type:
  237. if not cpu_only:
  238. if type == 'landmarks-manual':
  239. devices = [devices.get_best_device()]
  240. result = []
  241. for device in devices:
  242. count = 1
  243. if count == 1:
  244. result += [ (device.index, 'GPU', device.name, device.total_mem_gb) ]
  245. else:
  246. for i in range(count):
  247. result += [ (device.index, 'GPU', f"{device.name} #{i}", device.total_mem_gb) ]
  248. return result
  249. else:
  250. if type == 'landmarks-manual':
  251. return [ (0, 'CPU', 'CPU', 0 ) ]
  252. else:
  253. return [ (i, 'CPU', 'CPU%d' % (i), 0 ) for i in range( min(8, multiprocessing.cpu_count() // 2) ) ]
  254. elif type == 'final':
  255. return [ (i, 'CPU', 'CPU%d' % (i), 0 ) for i in (range(min(8, multiprocessing.cpu_count())) if not DEBUG else [0]) ]
  256. def __init__(self, input_data, type, image_size=None, jpeg_quality=None, face_type=None, output_debug_path=None, manual_window_size=0, max_faces_from_image=0, final_output_path=None, device_config=None):
  257. if type == 'landmarks-manual':
  258. for x in input_data:
  259. x.manual = True
  260. self.input_data = input_data
  261. self.type = type
  262. self.image_size = image_size
  263. self.jpeg_quality = jpeg_quality
  264. self.face_type = face_type
  265. self.output_debug_path = output_debug_path
  266. self.final_output_path = final_output_path
  267. self.manual_window_size = manual_window_size
  268. self.max_faces_from_image = max_faces_from_image
  269. self.result = []
  270. self.devices = ExtractSubprocessor.get_devices_for_config(self.type, device_config)
  271. super().__init__('Extractor', ExtractSubprocessor.Cli,
  272. 999999 if type == 'landmarks-manual' or DEBUG else 120)
  273. #override
  274. def on_clients_initialized(self):
  275. if self.type == 'landmarks-manual':
  276. self.wnd_name = 'Manual pass'
  277. io.named_window(self.wnd_name)
  278. io.capture_mouse(self.wnd_name)
  279. io.capture_keys(self.wnd_name)
  280. self.cache_original_image = (None, None)
  281. self.cache_image = (None, None)
  282. self.cache_text_lines_img = (None, None)
  283. self.hide_help = False
  284. self.landmarks_accurate = True
  285. self.force_landmarks = False
  286. self.landmarks = None
  287. self.x = 0
  288. self.y = 0
  289. self.rect_size = 100
  290. self.rect_locked = False
  291. self.extract_needed = True
  292. self.image = None
  293. self.image_filepath = None
  294. io.progress_bar (None, len (self.input_data))
  295. #override
  296. def on_clients_finalized(self):
  297. if self.type == 'landmarks-manual':
  298. io.destroy_all_windows()
  299. io.progress_bar_close()
  300. #override
  301. def process_info_generator(self):
  302. base_dict = {'type' : self.type,
  303. 'image_size': self.image_size,
  304. 'jpeg_quality' : self.jpeg_quality,
  305. 'face_type': self.face_type,
  306. 'max_faces_from_image':self.max_faces_from_image,
  307. 'output_debug_path': self.output_debug_path,
  308. 'final_output_path': self.final_output_path,
  309. 'stdin_fd': sys.stdin.fileno() }
  310. for (device_idx, device_type, device_name, device_total_vram_gb) in self.devices:
  311. client_dict = base_dict.copy()
  312. client_dict['device_idx'] = device_idx
  313. client_dict['device_name'] = device_name
  314. client_dict['device_type'] = device_type
  315. yield client_dict['device_name'], {}, client_dict
  316. #override
  317. def get_data(self, host_dict):
  318. if self.type == 'landmarks-manual':
  319. need_remark_face = False
  320. while len (self.input_data) > 0:
  321. data = self.input_data[0]
  322. filepath, data_rects, data_landmarks = data.filepath, data.rects, data.landmarks
  323. is_frame_done = False
  324. if self.image_filepath != filepath:
  325. self.image_filepath = filepath
  326. if self.cache_original_image[0] == filepath:
  327. self.original_image = self.cache_original_image[1]
  328. else:
  329. self.original_image = imagelib.normalize_channels( cv2_imread( filepath ), 3 )
  330. self.cache_original_image = (filepath, self.original_image )
  331. (h,w,c) = self.original_image.shape
  332. self.view_scale = 1.0 if self.manual_window_size == 0 else self.manual_window_size / ( h * (16.0/9.0) )
  333. if self.cache_image[0] == (h,w,c) + (self.view_scale,filepath):
  334. self.image = self.cache_image[1]
  335. else:
  336. self.image = cv2.resize (self.original_image, ( int(w*self.view_scale), int(h*self.view_scale) ), interpolation=cv2.INTER_LINEAR)
  337. self.cache_image = ( (h,w,c) + (self.view_scale,filepath), self.image )
  338. (h,w,c) = self.image.shape
  339. sh = (0,0, w, min(100, h) )
  340. if self.cache_text_lines_img[0] == sh:
  341. self.text_lines_img = self.cache_text_lines_img[1]
  342. else:
  343. self.text_lines_img = (imagelib.get_draw_text_lines ( self.image, sh,
  344. [ '[L Mouse click] - lock/unlock selection. [Mouse wheel] - change rect',
  345. '[R Mouse Click] - manual face rectangle',
  346. '[Enter] / [Space] - confirm / skip frame',
  347. '[,] [.]- prev frame, next frame. [Q] - skip remaining frames',
  348. '[a] - accuracy on/off (more fps)',
  349. '[h] - hide this help'
  350. ], (1, 1, 1) )*255).astype(np.uint8)
  351. self.cache_text_lines_img = (sh, self.text_lines_img)
  352. if need_remark_face: # need remark image from input data that already has a marked face?
  353. need_remark_face = False
  354. if len(data_rects) != 0: # If there was already a face then lock the rectangle to it until the mouse is clicked
  355. self.rect = data_rects.pop()
  356. self.landmarks = data_landmarks.pop()
  357. data_rects.clear()
  358. data_landmarks.clear()
  359. self.rect_locked = True
  360. self.rect_size = ( self.rect[2] - self.rect[0] ) / 2
  361. self.x = ( self.rect[0] + self.rect[2] ) / 2
  362. self.y = ( self.rect[1] + self.rect[3] ) / 2
  363. self.redraw()
  364. if len(data_rects) == 0:
  365. (h,w,c) = self.image.shape
  366. while True:
  367. io.process_messages(0.0001)
  368. if not self.force_landmarks:
  369. new_x = self.x
  370. new_y = self.y
  371. new_rect_size = self.rect_size
  372. mouse_events = io.get_mouse_events(self.wnd_name)
  373. for ev in mouse_events:
  374. (x, y, ev, flags) = ev
  375. if ev == io.EVENT_MOUSEWHEEL and not self.rect_locked:
  376. mod = 1 if flags > 0 else -1
  377. diff = 1 if new_rect_size <= 40 else np.clip(new_rect_size / 10, 1, 10)
  378. new_rect_size = max (5, new_rect_size + diff*mod)
  379. elif ev == io.EVENT_LBUTTONDOWN:
  380. if self.force_landmarks:
  381. self.x = new_x
  382. self.y = new_y
  383. self.force_landmarks = False
  384. self.rect_locked = True
  385. self.redraw()
  386. else:
  387. self.rect_locked = not self.rect_locked
  388. self.extract_needed = True
  389. elif ev == io.EVENT_RBUTTONDOWN:
  390. self.force_landmarks = not self.force_landmarks
  391. if self.force_landmarks:
  392. self.rect_locked = False
  393. elif not self.rect_locked:
  394. new_x = np.clip (x, 0, w-1) / self.view_scale
  395. new_y = np.clip (y, 0, h-1) / self.view_scale
  396. key_events = io.get_key_events(self.wnd_name)
  397. key, chr_key, ctrl_pressed, alt_pressed, shift_pressed = key_events[-1] if len(key_events) > 0 else (0,0,False,False,False)
  398. if key == ord('\r') or key == ord('\n'):
  399. #confirm frame
  400. is_frame_done = True
  401. data_rects.append (self.rect)
  402. data_landmarks.append (self.landmarks)
  403. break
  404. elif key == ord(' '):
  405. #confirm skip frame
  406. is_frame_done = True
  407. break
  408. elif key == ord(',') and len(self.result) > 0:
  409. #go prev frame
  410. if self.rect_locked:
  411. self.rect_locked = False
  412. # Only save the face if the rect is still locked
  413. data_rects.append (self.rect)
  414. data_landmarks.append (self.landmarks)
  415. self.input_data.insert(0, self.result.pop() )
  416. io.progress_bar_inc(-1)
  417. need_remark_face = True
  418. break
  419. elif key == ord('.'):
  420. #go next frame
  421. if self.rect_locked:
  422. self.rect_locked = False
  423. # Only save the face if the rect is still locked
  424. data_rects.append (self.rect)
  425. data_landmarks.append (self.landmarks)
  426. need_remark_face = True
  427. is_frame_done = True
  428. break
  429. elif key == ord('q'):
  430. #skip remaining
  431. if self.rect_locked:
  432. self.rect_locked = False
  433. data_rects.append (self.rect)
  434. data_landmarks.append (self.landmarks)
  435. while len(self.input_data) > 0:
  436. self.result.append( self.input_data.pop(0) )
  437. io.progress_bar_inc(1)
  438. break
  439. elif key == ord('h'):
  440. self.hide_help = not self.hide_help
  441. break
  442. elif key == ord('a'):
  443. self.landmarks_accurate = not self.landmarks_accurate
  444. break
  445. if self.force_landmarks:
  446. pt2 = np.float32([new_x, new_y])
  447. pt1 = np.float32([self.x, self.y])
  448. pt_vec_len = npla.norm(pt2-pt1)
  449. pt_vec = pt2-pt1
  450. if pt_vec_len != 0:
  451. pt_vec /= pt_vec_len
  452. self.rect_size = pt_vec_len
  453. self.rect = ( int(self.x-self.rect_size),
  454. int(self.y-self.rect_size),
  455. int(self.x+self.rect_size),
  456. int(self.y+self.rect_size) )
  457. if pt_vec_len > 0:
  458. lmrks = np.concatenate ( (np.zeros ((17,2), np.float32), LandmarksProcessor.landmarks_2D), axis=0 )
  459. lmrks -= lmrks[30:31,:]
  460. mat = cv2.getRotationMatrix2D( (0, 0), -np.arctan2( pt_vec[1], pt_vec[0] )*180/math.pi , pt_vec_len)
  461. mat[:, 2] += (self.x, self.y)
  462. self.landmarks = LandmarksProcessor.transform_points(lmrks, mat )
  463. self.redraw()
  464. elif self.x != new_x or \
  465. self.y != new_y or \
  466. self.rect_size != new_rect_size or \
  467. self.extract_needed:
  468. self.x = new_x
  469. self.y = new_y
  470. self.rect_size = new_rect_size
  471. self.rect = ( int(self.x-self.rect_size),
  472. int(self.y-self.rect_size),
  473. int(self.x+self.rect_size),
  474. int(self.y+self.rect_size) )
  475. return ExtractSubprocessor.Data (filepath, rects=[self.rect], landmarks_accurate=self.landmarks_accurate)
  476. else:
  477. is_frame_done = True
  478. if is_frame_done:
  479. self.result.append ( data )
  480. self.input_data.pop(0)
  481. io.progress_bar_inc(1)
  482. self.extract_needed = True
  483. self.rect_locked = False
  484. else:
  485. if len (self.input_data) > 0:
  486. return self.input_data.pop(0)
  487. return None
  488. #override
  489. def on_data_return (self, host_dict, data):
  490. if not self.type != 'landmarks-manual':
  491. self.input_data.insert(0, data)
  492. def redraw(self):
  493. (h,w,c) = self.image.shape
  494. if not self.hide_help:
  495. image = cv2.addWeighted (self.image,1.0,self.text_lines_img,1.0,0)
  496. else:
  497. image = self.image.copy()
  498. view_rect = (np.array(self.rect) * self.view_scale).astype(np.int).tolist()
  499. view_landmarks = (np.array(self.landmarks) * self.view_scale).astype(np.int).tolist()
  500. if self.rect_size <= 40:
  501. scaled_rect_size = h // 3 if w > h else w // 3
  502. p1 = (self.x - self.rect_size, self.y - self.rect_size)
  503. p2 = (self.x + self.rect_size, self.y - self.rect_size)
  504. p3 = (self.x - self.rect_size, self.y + self.rect_size)
  505. wh = h if h < w else w
  506. np1 = (w / 2 - wh / 4, h / 2 - wh / 4)
  507. np2 = (w / 2 + wh / 4, h / 2 - wh / 4)
  508. np3 = (w / 2 - wh / 4, h / 2 + wh / 4)
  509. mat = cv2.getAffineTransform( np.float32([p1,p2,p3])*self.view_scale, np.float32([np1,np2,np3]) )
  510. image = cv2.warpAffine(image, mat,(w,h) )
  511. view_landmarks = LandmarksProcessor.transform_points (view_landmarks, mat)
  512. landmarks_color = (255,255,0) if self.rect_locked else (0,255,0)
  513. LandmarksProcessor.draw_rect_landmarks (image, view_rect, view_landmarks, self.face_type, self.image_size, landmarks_color=landmarks_color)
  514. self.extract_needed = False
  515. io.show_image (self.wnd_name, image)
  516. #override
  517. def on_result (self, host_dict, data, result):
  518. if self.type == 'landmarks-manual':
  519. filepath, landmarks = result.filepath, result.landmarks
  520. if len(landmarks) != 0 and landmarks[0] is not None:
  521. self.landmarks = landmarks[0]
  522. self.redraw()
  523. else:
  524. self.result.append ( result )
  525. io.progress_bar_inc(1)
  526. #override
  527. def get_result(self):
  528. return self.result
  529. class DeletedFilesSearcherSubprocessor(Subprocessor):
  530. class Cli(Subprocessor.Cli):
  531. #override
  532. def on_initialize(self, client_dict):
  533. self.debug_paths_stems = client_dict['debug_paths_stems']
  534. return None
  535. #override
  536. def process_data(self, data):
  537. input_path_stem = Path(data[0]).stem
  538. return any ( [ input_path_stem == d_stem for d_stem in self.debug_paths_stems] )
  539. #override
  540. def get_data_name (self, data):
  541. #return string identificator of your data
  542. return data[0]
  543. #override
  544. def __init__(self, input_paths, debug_paths ):
  545. self.input_paths = input_paths
  546. self.debug_paths_stems = [ Path(d).stem for d in debug_paths]
  547. self.result = []
  548. super().__init__('DeletedFilesSearcherSubprocessor', DeletedFilesSearcherSubprocessor.Cli, 60)
  549. #override
  550. def process_info_generator(self):
  551. for i in range(min(multiprocessing.cpu_count(), 8)):
  552. yield 'CPU%d' % (i), {}, {'debug_paths_stems' : self.debug_paths_stems}
  553. #override
  554. def on_clients_initialized(self):
  555. io.progress_bar ("Searching deleted files", len (self.input_paths))
  556. #override
  557. def on_clients_finalized(self):
  558. io.progress_bar_close()
  559. #override
  560. def get_data(self, host_dict):
  561. if len (self.input_paths) > 0:
  562. return [self.input_paths.pop(0)]
  563. return None
  564. #override
  565. def on_data_return (self, host_dict, data):
  566. self.input_paths.insert(0, data[0])
  567. #override
  568. def on_result (self, host_dict, data, result):
  569. if result == False:
  570. self.result.append( data[0] )
  571. io.progress_bar_inc(1)
  572. #override
  573. def get_result(self):
  574. return self.result
  575. def main(detector=None,
  576. input_path=None,
  577. output_path=None,
  578. output_debug=None,
  579. manual_fix=False,
  580. manual_output_debug_fix=False,
  581. manual_window_size=1368,
  582. face_type='full_face',
  583. max_faces_from_image=None,
  584. image_size=None,
  585. jpeg_quality=None,
  586. cpu_only = False,
  587. force_gpu_idxs = None,
  588. ):
  589. if not input_path.exists():
  590. io.log_err ('Input directory not found. Please ensure it exists.')
  591. return
  592. if not output_path.exists():
  593. output_path.mkdir(parents=True, exist_ok=True)
  594. if face_type is not None:
  595. face_type = FaceType.fromString(face_type)
  596. if face_type is None:
  597. if manual_output_debug_fix:
  598. files = pathex.get_image_paths(output_path)
  599. if len(files) != 0:
  600. dflimg = DFLIMG.load(Path(files[0]))
  601. if dflimg is not None and dflimg.has_data():
  602. face_type = FaceType.fromString ( dflimg.get_face_type() )
  603. input_image_paths = pathex.get_image_unique_filestem_paths(input_path, verbose_print_func=io.log_info)
  604. output_images_paths = pathex.get_image_paths(output_path)
  605. output_debug_path = output_path.parent / (output_path.name + '_debug')
  606. continue_extraction = False
  607. if not manual_output_debug_fix and len(output_images_paths) > 0:
  608. if len(output_images_paths) > 128:
  609. continue_extraction = io.input_bool ("Continue extraction?", True, help_message="Extraction can be continued, but you must specify the same options again.")
  610. if len(output_images_paths) > 128 and continue_extraction:
  611. try:
  612. input_image_paths = input_image_paths[ [ Path(x).stem for x in input_image_paths ].index ( Path(output_images_paths[-128]).stem.split('_')[0] ) : ]
  613. except:
  614. io.log_err("Error in fetching the last index. Extraction cannot be continued.")
  615. return
  616. elif input_path != output_path:
  617. io.input(f"\n WARNING !!! \n {output_path} contains files! \n They will be deleted. \n Press enter to continue.\n")
  618. for filename in output_images_paths:
  619. Path(filename).unlink()
  620. device_config = nn.DeviceConfig.GPUIndexes( force_gpu_idxs or nn.ask_choose_device_idxs(choose_only_one=detector=='manual', suggest_all_gpu=True) ) \
  621. if not cpu_only else nn.DeviceConfig.CPU()
  622. if face_type is None:
  623. face_type = io.input_str ("Face type", 'wf', ['f','wf','head'], help_message="Full face / whole face / head. 'Whole face' covers full area of face include forehead. 'head' covers full head, but requires XSeg for src and dst faceset.").lower()
  624. face_type = {'f' : FaceType.FULL,
  625. 'wf' : FaceType.WHOLE_FACE,
  626. 'head' : FaceType.HEAD}[face_type]
  627. if max_faces_from_image is None:
  628. max_faces_from_image = io.input_int(f"Max number of faces from image", 0, help_message="If you extract a src faceset that has frames with a large number of faces, it is advisable to set max faces to 3 to speed up extraction. 0 - unlimited")
  629. if image_size is None:
  630. image_size = io.input_int(f"Image size", 512 if face_type < FaceType.HEAD else 768, valid_range=[256,2048], help_message="Output image size. The higher image size, the worse face-enhancer works. Use higher than 512 value only if the source image is sharp enough and the face does not need to be enhanced.")
  631. if jpeg_quality is None:
  632. jpeg_quality = io.input_int(f"Jpeg quality", 90, valid_range=[1,100], help_message="Jpeg quality. The higher jpeg quality the larger the output file size.")
  633. if detector is None:
  634. io.log_info ("Choose detector type.")
  635. io.log_info ("[0] S3FD")
  636. io.log_info ("[1] manual")
  637. detector = {0:'s3fd', 1:'manual'}[ io.input_int("", 0, [0,1]) ]
  638. if output_debug is None:
  639. output_debug = io.input_bool (f"Write debug images to {output_debug_path.name}?", False)
  640. if output_debug:
  641. output_debug_path.mkdir(parents=True, exist_ok=True)
  642. if manual_output_debug_fix:
  643. if not output_debug_path.exists():
  644. io.log_err(f'{output_debug_path} not found. Re-extract faces with "Write debug images" option.')
  645. return
  646. else:
  647. detector = 'manual'
  648. io.log_info('Performing re-extract frames which were deleted from _debug directory.')
  649. input_image_paths = DeletedFilesSearcherSubprocessor (input_image_paths, pathex.get_image_paths(output_debug_path) ).run()
  650. input_image_paths = sorted (input_image_paths)
  651. io.log_info('Found %d images.' % (len(input_image_paths)))
  652. else:
  653. if not continue_extraction and output_debug_path.exists():
  654. for filename in pathex.get_image_paths(output_debug_path):
  655. Path(filename).unlink()
  656. images_found = len(input_image_paths)
  657. faces_detected = 0
  658. if images_found != 0:
  659. if detector == 'manual':
  660. io.log_info ('Performing manual extract...')
  661. data = ExtractSubprocessor ([ ExtractSubprocessor.Data(Path(filename)) for filename in input_image_paths ], 'landmarks-manual', image_size, jpeg_quality, face_type, output_debug_path if output_debug else None, manual_window_size=manual_window_size, device_config=device_config).run()
  662. io.log_info ('Performing 3rd pass...')
  663. data = ExtractSubprocessor (data, 'final', image_size, jpeg_quality, face_type, output_debug_path if output_debug else None, final_output_path=output_path, device_config=device_config).run()
  664. else:
  665. io.log_info ('Extracting faces...')
  666. data = ExtractSubprocessor ([ ExtractSubprocessor.Data(Path(filename)) for filename in input_image_paths ],
  667. 'all',
  668. image_size,
  669. jpeg_quality,
  670. face_type,
  671. output_debug_path if output_debug else None,
  672. max_faces_from_image=max_faces_from_image,
  673. final_output_path=output_path,
  674. device_config=device_config).run()
  675. faces_detected += sum([d.faces_detected for d in data])
  676. if manual_fix:
  677. if all ( np.array ( [ d.faces_detected > 0 for d in data] ) == True ):
  678. io.log_info ('All faces are detected, manual fix not needed.')
  679. else:
  680. fix_data = [ ExtractSubprocessor.Data(d.filepath) for d in data if d.faces_detected == 0 ]
  681. io.log_info ('Performing manual fix for %d images...' % (len(fix_data)) )
  682. fix_data = ExtractSubprocessor (fix_data, 'landmarks-manual', image_size, jpeg_quality, face_type, output_debug_path if output_debug else None, manual_window_size=manual_window_size, device_config=device_config).run()
  683. fix_data = ExtractSubprocessor (fix_data, 'final', image_size, jpeg_quality, face_type, output_debug_path if output_debug else None, final_output_path=output_path, device_config=device_config).run()
  684. faces_detected += sum([d.faces_detected for d in fix_data])
  685. io.log_info ('-------------------------')
  686. io.log_info ('Images found: %d' % (images_found) )
  687. io.log_info ('Faces detected: %d' % (faces_detected) )
  688. io.log_info ('-------------------------')
Tip!

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

Comments

Loading...