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 35 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
  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. import facelib
  13. import imagelib
  14. import mathlib
  15. from facelib import FaceType, LandmarksProcessor
  16. from interact import interact as io
  17. from joblib import Subprocessor
  18. from nnlib import TernausNet, nnlib
  19. from utils import Path_utils
  20. from utils.cv2_utils import *
  21. from DFLIMG import *
  22. DEBUG = False
  23. class ExtractSubprocessor(Subprocessor):
  24. class Data(object):
  25. def __init__(self, filename=None, rects=None, landmarks = None, landmarks_accurate=True, manual=False, force_output_path=None, final_output_files = None):
  26. self.filename = filename
  27. self.rects = rects or []
  28. self.rects_rotation = 0
  29. self.landmarks_accurate = landmarks_accurate
  30. self.manual = manual
  31. self.landmarks = landmarks or []
  32. self.force_output_path = force_output_path
  33. self.final_output_files = final_output_files or []
  34. self.faces_detected = 0
  35. class Cli(Subprocessor.Cli):
  36. #override
  37. def on_initialize(self, client_dict):
  38. self.type = client_dict['type']
  39. self.image_size = client_dict['image_size']
  40. self.face_type = client_dict['face_type']
  41. self.max_faces_from_image = client_dict['max_faces_from_image']
  42. self.device_idx = client_dict['device_idx']
  43. self.cpu_only = client_dict['device_type'] == 'CPU'
  44. self.final_output_path = Path(client_dict['final_output_dir']) if 'final_output_dir' in client_dict.keys() else None
  45. self.debug_dir = client_dict['debug_dir']
  46. #transfer and set stdin in order to work code.interact in debug subprocess
  47. stdin_fd = client_dict['stdin_fd']
  48. if stdin_fd is not None and DEBUG:
  49. sys.stdin = os.fdopen(stdin_fd)
  50. self.cached_image = (None, None)
  51. self.e = None
  52. device_config = nnlib.DeviceConfig ( cpu_only=self.cpu_only, force_gpu_idx=self.device_idx, allow_growth=True)
  53. self.device_vram = device_config.gpu_vram_gb[0]
  54. intro_str = 'Running on %s.' % (client_dict['device_name'])
  55. if not self.cpu_only and self.device_vram <= 2:
  56. intro_str += " Recommended to close all programs using this device."
  57. self.log_info (intro_str)
  58. if 'rects' in self.type:
  59. if self.type == 'rects-mt':
  60. nnlib.import_all (device_config)
  61. self.e = facelib.MTCExtractor()
  62. elif self.type == 'rects-dlib':
  63. nnlib.import_dlib (device_config)
  64. self.e = facelib.DLIBExtractor(nnlib.dlib)
  65. elif self.type == 'rects-s3fd':
  66. nnlib.import_all (device_config)
  67. self.e = facelib.S3FDExtractor(do_dummy_predict=True)
  68. else:
  69. raise ValueError ("Wrong type.")
  70. if self.e is not None:
  71. self.e.__enter__()
  72. elif self.type == 'landmarks':
  73. nnlib.import_all (device_config)
  74. self.e = facelib.FANExtractor()
  75. self.e.__enter__()
  76. if self.device_vram >= 2:
  77. self.second_pass_e = facelib.S3FDExtractor(do_dummy_predict=False)
  78. self.second_pass_e.__enter__()
  79. else:
  80. self.second_pass_e = None
  81. elif self.type == 'fanseg':
  82. nnlib.import_all (device_config)
  83. self.e = TernausNet(256, FaceType.toString(FaceType.FULL) )
  84. self.e.__enter__()
  85. elif self.type == 'final':
  86. pass
  87. #override
  88. def on_finalize(self):
  89. if self.e is not None:
  90. self.e.__exit__()
  91. #override
  92. def process_data(self, data):
  93. filename_path = Path( data.filename )
  94. filename_path_str = str(filename_path)
  95. if self.type == 'landmarks' and len(data.rects) == 0:
  96. return data
  97. if self.cached_image[0] == filename_path_str:
  98. image = self.cached_image[1] #cached image for manual extractor
  99. else:
  100. image = cv2_imread( filename_path_str )
  101. if image is None:
  102. self.log_err ( 'Failed to extract %s, reason: cv2_imread() fail.' % ( str(filename_path) ) )
  103. return data
  104. image = imagelib.normalize_channels(image, 3)
  105. h, w, ch = image.shape
  106. wm, hm = w % 2, h % 2
  107. if wm + hm != 0: #fix odd image
  108. image = image[0:h-hm,0:w-wm,:]
  109. self.cached_image = ( filename_path_str, image )
  110. src_dflimg = None
  111. h, w, ch = image.shape
  112. if h == w:
  113. #extracting from already extracted jpg image?
  114. src_dflimg = DFLIMG.load (filename_path)
  115. if 'rects' in self.type:
  116. if min(w,h) < 128:
  117. self.log_err ( 'Image is too small %s : [%d, %d]' % ( str(filename_path), w, h ) )
  118. data.rects = []
  119. else:
  120. for rot in ([0, 90, 270, 180]):
  121. data.rects_rotation = rot
  122. if rot == 0:
  123. rotated_image = image
  124. elif rot == 90:
  125. rotated_image = image.swapaxes( 0,1 )[:,::-1,:]
  126. elif rot == 180:
  127. rotated_image = image[::-1,::-1,:]
  128. elif rot == 270:
  129. rotated_image = image.swapaxes( 0,1 )[::-1,:,:]
  130. rects = data.rects = self.e.extract (rotated_image, is_bgr=True)
  131. if len(rects) != 0:
  132. break
  133. if self.max_faces_from_image != 0 and len(data.rects) > 1:
  134. data.rects = data.rects[0:self.max_faces_from_image]
  135. return data
  136. elif self.type == 'landmarks':
  137. if data.rects_rotation == 0:
  138. rotated_image = image
  139. elif data.rects_rotation == 90:
  140. rotated_image = image.swapaxes( 0,1 )[:,::-1,:]
  141. elif data.rects_rotation == 180:
  142. rotated_image = image[::-1,::-1,:]
  143. elif data.rects_rotation == 270:
  144. rotated_image = image.swapaxes( 0,1 )[::-1,:,:]
  145. data.landmarks = self.e.extract (rotated_image, data.rects, self.second_pass_e if (src_dflimg is None and data.landmarks_accurate) else None, is_bgr=True)
  146. if data.rects_rotation != 0:
  147. for i, (rect, lmrks) in enumerate(zip(data.rects, data.landmarks)):
  148. new_rect, new_lmrks = rect, lmrks
  149. (l,t,r,b) = rect
  150. if data.rects_rotation == 90:
  151. new_rect = ( t, h-l, b, h-r)
  152. if lmrks is not None:
  153. new_lmrks = lmrks[:,::-1].copy()
  154. new_lmrks[:,1] = h - new_lmrks[:,1]
  155. elif data.rects_rotation == 180:
  156. if lmrks is not None:
  157. new_rect = ( w-l, h-t, w-r, h-b)
  158. new_lmrks = lmrks.copy()
  159. new_lmrks[:,0] = w - new_lmrks[:,0]
  160. new_lmrks[:,1] = h - new_lmrks[:,1]
  161. elif data.rects_rotation == 270:
  162. new_rect = ( w-b, l, w-t, r )
  163. if lmrks is not None:
  164. new_lmrks = lmrks[:,::-1].copy()
  165. new_lmrks[:,0] = w - new_lmrks[:,0]
  166. data.rects[i], data.landmarks[i] = new_rect, new_lmrks
  167. return data
  168. elif self.type == 'final':
  169. data.final_output_files = []
  170. rects = data.rects
  171. landmarks = data.landmarks
  172. if self.debug_dir is not None:
  173. debug_output_file = str( Path(self.debug_dir) / (filename_path.stem+'.jpg') )
  174. debug_image = image.copy()
  175. if src_dflimg is not None and len(rects) != 1:
  176. #if re-extracting from dflimg and more than 1 or zero faces detected - dont process and just copy it
  177. print("src_dflimg is not None and len(rects) != 1", str(filename_path) )
  178. output_file = str(self.final_output_path / filename_path.name)
  179. if str(filename_path) != str(output_file):
  180. shutil.copy ( str(filename_path), str(output_file) )
  181. data.final_output_files.append (output_file)
  182. else:
  183. face_idx = 0
  184. for rect, image_landmarks in zip( rects, landmarks ):
  185. if src_dflimg is not None and face_idx > 1:
  186. #cannot extract more than 1 face from dflimg
  187. break
  188. if image_landmarks is None:
  189. continue
  190. rect = np.array(rect)
  191. if self.face_type == FaceType.MARK_ONLY:
  192. image_to_face_mat = None
  193. face_image = image
  194. face_image_landmarks = image_landmarks
  195. else:
  196. image_to_face_mat = LandmarksProcessor.get_transform_mat (image_landmarks, self.image_size, self.face_type)
  197. face_image = cv2.warpAffine(image, image_to_face_mat, (self.image_size, self.image_size), cv2.INTER_LANCZOS4)
  198. face_image_landmarks = LandmarksProcessor.transform_points (image_landmarks, image_to_face_mat)
  199. landmarks_bbox = LandmarksProcessor.transform_points ( [ (0,0), (0,self.image_size-1), (self.image_size-1, self.image_size-1), (self.image_size-1,0) ], image_to_face_mat, True)
  200. rect_area = mathlib.polygon_area(np.array(rect[[0,2,2,0]]), np.array(rect[[1,1,3,3]]))
  201. landmarks_area = mathlib.polygon_area(landmarks_bbox[:,0], landmarks_bbox[:,1] )
  202. if not data.manual and self.face_type <= FaceType.FULL_NO_ALIGN and landmarks_area > 4*rect_area: #get rid of faces which umeyama-landmark-area > 4*detector-rect-area
  203. continue
  204. if self.debug_dir is not None:
  205. LandmarksProcessor.draw_rect_landmarks (debug_image, rect, image_landmarks, self.image_size, self.face_type, transparent_mask=True)
  206. final_output_path = self.final_output_path
  207. if data.force_output_path is not None:
  208. final_output_path = data.force_output_path
  209. if src_dflimg is not None and filename_path.suffix == '.jpg':
  210. #if extracting from dflimg and jpg copy it in order not to lose quality
  211. output_file = str(final_output_path / filename_path.name)
  212. if str(filename_path) != str(output_file):
  213. shutil.copy ( str(filename_path), str(output_file) )
  214. else:
  215. output_file = '{}_{}{}'.format(str(final_output_path / filename_path.stem), str(face_idx), '.jpg')
  216. cv2_imwrite(output_file, face_image, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
  217. DFLJPG.embed_data(output_file, face_type=FaceType.toString(self.face_type),
  218. landmarks=face_image_landmarks.tolist(),
  219. source_filename=filename_path.name,
  220. source_rect=rect,
  221. source_landmarks=image_landmarks.tolist(),
  222. image_to_face_mat=image_to_face_mat
  223. )
  224. data.final_output_files.append (output_file)
  225. face_idx += 1
  226. data.faces_detected = face_idx
  227. if self.debug_dir is not None:
  228. cv2_imwrite(debug_output_file, debug_image, [int(cv2.IMWRITE_JPEG_QUALITY), 50] )
  229. return data
  230. elif self.type == 'fanseg':
  231. if src_dflimg is not None:
  232. fanseg_mask = self.e.extract( image / 255.0 )
  233. src_dflimg.embed_and_set( filename_path_str,
  234. fanseg_mask=fanseg_mask,
  235. )
  236. #overridable
  237. def get_data_name (self, data):
  238. #return string identificator of your data
  239. return data.filename
  240. #override
  241. def __init__(self, input_data, type, image_size=None, face_type=None, debug_dir=None, multi_gpu=False, cpu_only=False, manual=False, manual_window_size=0, max_faces_from_image=0, final_output_path=None):
  242. self.input_data = input_data
  243. self.type = type
  244. self.image_size = image_size
  245. self.face_type = face_type
  246. self.debug_dir = debug_dir
  247. self.final_output_path = final_output_path
  248. self.manual = manual
  249. self.manual_window_size = manual_window_size
  250. self.max_faces_from_image = max_faces_from_image
  251. self.result = []
  252. self.devices = ExtractSubprocessor.get_devices_for_config(self.manual, self.type, multi_gpu, cpu_only)
  253. if self.manual or DEBUG:
  254. no_response_time_sec = 999999
  255. elif nnlib.device.backend == 'plaidML':
  256. no_response_time_sec = 600
  257. else:
  258. no_response_time_sec = 60
  259. super().__init__('Extractor', ExtractSubprocessor.Cli, no_response_time_sec)
  260. #override
  261. def on_check_run(self):
  262. if len(self.devices) == 0:
  263. io.log_err("No devices found to start subprocessor.")
  264. return False
  265. return True
  266. #override
  267. def on_clients_initialized(self):
  268. if self.manual == True:
  269. self.wnd_name = 'Manual pass'
  270. io.named_window(self.wnd_name)
  271. io.capture_mouse(self.wnd_name)
  272. io.capture_keys(self.wnd_name)
  273. self.cache_original_image = (None, None)
  274. self.cache_image = (None, None)
  275. self.cache_text_lines_img = (None, None)
  276. self.hide_help = False
  277. self.landmarks_accurate = True
  278. self.landmarks = None
  279. self.x = 0
  280. self.y = 0
  281. self.rect_size = 100
  282. self.rect_locked = False
  283. self.extract_needed = True
  284. io.progress_bar (None, len (self.input_data))
  285. #override
  286. def on_clients_finalized(self):
  287. if self.manual == True:
  288. io.destroy_all_windows()
  289. io.progress_bar_close()
  290. #override
  291. def process_info_generator(self):
  292. base_dict = {'type' : self.type,
  293. 'image_size': self.image_size,
  294. 'face_type': self.face_type,
  295. 'max_faces_from_image':self.max_faces_from_image,
  296. 'debug_dir': self.debug_dir,
  297. 'final_output_dir': str(self.final_output_path),
  298. 'stdin_fd': sys.stdin.fileno() }
  299. for (device_idx, device_type, device_name, device_total_vram_gb) in self.devices:
  300. client_dict = base_dict.copy()
  301. client_dict['device_idx'] = device_idx
  302. client_dict['device_name'] = device_name
  303. client_dict['device_type'] = device_type
  304. yield client_dict['device_name'], {}, client_dict
  305. #override
  306. def get_data(self, host_dict):
  307. if not self.manual:
  308. if len (self.input_data) > 0:
  309. return self.input_data.pop(0)
  310. else:
  311. need_remark_face = False
  312. redraw_needed = False
  313. while len (self.input_data) > 0:
  314. data = self.input_data[0]
  315. filename, data_rects, data_landmarks = data.filename, data.rects, data.landmarks
  316. is_frame_done = False
  317. if need_remark_face: # need remark image from input data that already has a marked face?
  318. need_remark_face = False
  319. if len(data_rects) != 0: # If there was already a face then lock the rectangle to it until the mouse is clicked
  320. self.rect = data_rects.pop()
  321. self.landmarks = data_landmarks.pop()
  322. data_rects.clear()
  323. data_landmarks.clear()
  324. redraw_needed = True
  325. self.rect_locked = True
  326. self.rect_size = ( self.rect[2] - self.rect[0] ) / 2
  327. self.x = ( self.rect[0] + self.rect[2] ) / 2
  328. self.y = ( self.rect[1] + self.rect[3] ) / 2
  329. if len(data_rects) == 0:
  330. if self.cache_original_image[0] == filename:
  331. self.original_image = self.cache_original_image[1]
  332. else:
  333. self.original_image = imagelib.normalize_channels( cv2_imread( filename ), 3 )
  334. self.cache_original_image = (filename, self.original_image )
  335. (h,w,c) = self.original_image.shape
  336. self.view_scale = 1.0 if self.manual_window_size == 0 else self.manual_window_size / ( h * (16.0/9.0) )
  337. if self.cache_image[0] == (h,w,c) + (self.view_scale,filename):
  338. self.image = self.cache_image[1]
  339. else:
  340. self.image = cv2.resize (self.original_image, ( int(w*self.view_scale), int(h*self.view_scale) ), interpolation=cv2.INTER_LINEAR)
  341. self.cache_image = ( (h,w,c) + (self.view_scale,filename), self.image )
  342. (h,w,c) = self.image.shape
  343. sh = (0,0, w, min(100, h) )
  344. if self.cache_text_lines_img[0] == sh:
  345. self.text_lines_img = self.cache_text_lines_img[1]
  346. else:
  347. self.text_lines_img = (imagelib.get_draw_text_lines ( self.image, sh,
  348. [ '[Mouse click] - lock/unlock selection',
  349. '[Mouse wheel] - change rect',
  350. '[Enter] / [Space] - confirm / skip frame',
  351. '[,] [.]- prev frame, next frame. [Q] - skip remaining frames',
  352. '[a] - accuracy on/off (more fps)',
  353. '[h] - hide this help'
  354. ], (1, 1, 1) )*255).astype(np.uint8)
  355. self.cache_text_lines_img = (sh, self.text_lines_img)
  356. while True:
  357. io.process_messages(0.0001)
  358. new_x = self.x
  359. new_y = self.y
  360. new_rect_size = self.rect_size
  361. mouse_events = io.get_mouse_events(self.wnd_name)
  362. for ev in mouse_events:
  363. (x, y, ev, flags) = ev
  364. if ev == io.EVENT_MOUSEWHEEL and not self.rect_locked:
  365. mod = 1 if flags > 0 else -1
  366. diff = 1 if new_rect_size <= 40 else np.clip(new_rect_size / 10, 1, 10)
  367. new_rect_size = max (5, new_rect_size + diff*mod)
  368. elif ev == io.EVENT_LBUTTONDOWN:
  369. self.rect_locked = not self.rect_locked
  370. self.extract_needed = True
  371. elif not self.rect_locked:
  372. new_x = np.clip (x, 0, w-1) / self.view_scale
  373. new_y = np.clip (y, 0, h-1) / self.view_scale
  374. key_events = io.get_key_events(self.wnd_name)
  375. key, chr_key, ctrl_pressed, alt_pressed, shift_pressed = key_events[-1] if len(key_events) > 0 else (0,0,False,False,False)
  376. if key == ord('\r') or key == ord('\n'):
  377. #confirm frame
  378. is_frame_done = True
  379. data_rects.append (self.rect)
  380. data_landmarks.append (self.landmarks)
  381. break
  382. elif key == ord(' '):
  383. #confirm skip frame
  384. is_frame_done = True
  385. break
  386. elif key == ord(',') and len(self.result) > 0:
  387. #go prev frame
  388. if self.rect_locked:
  389. self.rect_locked = False
  390. # Only save the face if the rect is still locked
  391. data_rects.append (self.rect)
  392. data_landmarks.append (self.landmarks)
  393. self.input_data.insert(0, self.result.pop() )
  394. io.progress_bar_inc(-1)
  395. need_remark_face = True
  396. break
  397. elif key == ord('.'):
  398. #go next frame
  399. if self.rect_locked:
  400. self.rect_locked = False
  401. # Only save the face if the rect is still locked
  402. data_rects.append (self.rect)
  403. data_landmarks.append (self.landmarks)
  404. need_remark_face = True
  405. is_frame_done = True
  406. break
  407. elif key == ord('q'):
  408. #skip remaining
  409. if self.rect_locked:
  410. self.rect_locked = False
  411. data_rects.append (self.rect)
  412. data_landmarks.append (self.landmarks)
  413. while len(self.input_data) > 0:
  414. self.result.append( self.input_data.pop(0) )
  415. io.progress_bar_inc(1)
  416. break
  417. elif key == ord('h'):
  418. self.hide_help = not self.hide_help
  419. break
  420. elif key == ord('a'):
  421. self.landmarks_accurate = not self.landmarks_accurate
  422. break
  423. if self.x != new_x or \
  424. self.y != new_y or \
  425. self.rect_size != new_rect_size or \
  426. self.extract_needed or \
  427. redraw_needed:
  428. self.x = new_x
  429. self.y = new_y
  430. self.rect_size = new_rect_size
  431. self.rect = ( int(self.x-self.rect_size),
  432. int(self.y-self.rect_size),
  433. int(self.x+self.rect_size),
  434. int(self.y+self.rect_size) )
  435. if redraw_needed:
  436. redraw_needed = False
  437. return ExtractSubprocessor.Data (filename, landmarks_accurate=self.landmarks_accurate)
  438. else:
  439. return ExtractSubprocessor.Data (filename, rects=[self.rect], landmarks_accurate=self.landmarks_accurate)
  440. else:
  441. is_frame_done = True
  442. if is_frame_done:
  443. self.result.append ( data )
  444. self.input_data.pop(0)
  445. io.progress_bar_inc(1)
  446. self.extract_needed = True
  447. self.rect_locked = False
  448. return None
  449. #override
  450. def on_data_return (self, host_dict, data):
  451. if not self.manual:
  452. self.input_data.insert(0, data)
  453. #override
  454. def on_result (self, host_dict, data, result):
  455. if self.manual == True:
  456. filename, landmarks = result.filename, result.landmarks
  457. if len(landmarks) != 0 and landmarks[0] is not None:
  458. self.landmarks = landmarks[0]
  459. (h,w,c) = self.image.shape
  460. if not self.hide_help:
  461. image = cv2.addWeighted (self.image,1.0,self.text_lines_img,1.0,0)
  462. else:
  463. image = self.image.copy()
  464. view_rect = (np.array(self.rect) * self.view_scale).astype(np.int).tolist()
  465. view_landmarks = (np.array(self.landmarks) * self.view_scale).astype(np.int).tolist()
  466. if self.rect_size <= 40:
  467. scaled_rect_size = h // 3 if w > h else w // 3
  468. p1 = (self.x - self.rect_size, self.y - self.rect_size)
  469. p2 = (self.x + self.rect_size, self.y - self.rect_size)
  470. p3 = (self.x - self.rect_size, self.y + self.rect_size)
  471. wh = h if h < w else w
  472. np1 = (w / 2 - wh / 4, h / 2 - wh / 4)
  473. np2 = (w / 2 + wh / 4, h / 2 - wh / 4)
  474. np3 = (w / 2 - wh / 4, h / 2 + wh / 4)
  475. mat = cv2.getAffineTransform( np.float32([p1,p2,p3])*self.view_scale, np.float32([np1,np2,np3]) )
  476. image = cv2.warpAffine(image, mat,(w,h) )
  477. view_landmarks = LandmarksProcessor.transform_points (view_landmarks, mat)
  478. landmarks_color = (255,255,0) if self.rect_locked else (0,255,0)
  479. LandmarksProcessor.draw_rect_landmarks (image, view_rect, view_landmarks, self.image_size, self.face_type, landmarks_color=landmarks_color)
  480. self.extract_needed = False
  481. io.show_image (self.wnd_name, image)
  482. else:
  483. self.result.append ( result )
  484. io.progress_bar_inc(1)
  485. #override
  486. def get_result(self):
  487. return self.result
  488. @staticmethod
  489. def get_devices_for_config (manual, type, multi_gpu, cpu_only):
  490. backend = nnlib.device.backend
  491. if 'cpu' in backend:
  492. cpu_only = True
  493. if 'rects' in type or type == 'landmarks' or type == 'fanseg':
  494. if not cpu_only and type == 'rects-mt' and backend == "plaidML": #plaidML works with MT very slowly
  495. cpu_only = True
  496. if not cpu_only:
  497. devices = []
  498. if not manual and multi_gpu:
  499. devices = nnlib.device.getValidDevicesWithAtLeastTotalMemoryGB(2)
  500. if len(devices) == 0:
  501. idx = nnlib.device.getBestValidDeviceIdx()
  502. if idx != -1:
  503. devices = [idx]
  504. if len(devices) == 0:
  505. cpu_only = True
  506. result = []
  507. for idx in devices:
  508. dev_name = nnlib.device.getDeviceName(idx)
  509. dev_vram = nnlib.device.getDeviceVRAMTotalGb(idx)
  510. count = 1
  511. if not manual:
  512. if (type == 'rects-mt' ):
  513. count = int (max (1, dev_vram / 2) )
  514. if count == 1:
  515. result += [ (idx, 'GPU', dev_name, dev_vram) ]
  516. else:
  517. for i in range (count):
  518. result += [ (idx, 'GPU', '%s #%d' % (dev_name,i) , dev_vram) ]
  519. return result
  520. if cpu_only:
  521. if manual:
  522. return [ (0, 'CPU', 'CPU', 0 ) ]
  523. else:
  524. return [ (i, 'CPU', 'CPU%d' % (i), 0 ) for i in range( min(8, multiprocessing.cpu_count() // 2) ) ]
  525. elif type == 'final':
  526. return [ (i, 'CPU', 'CPU%d' % (i), 0 ) for i in (range(min(8, multiprocessing.cpu_count())) if not DEBUG else [0]) ]
  527. class DeletedFilesSearcherSubprocessor(Subprocessor):
  528. class Cli(Subprocessor.Cli):
  529. #override
  530. def on_initialize(self, client_dict):
  531. self.debug_paths_stems = client_dict['debug_paths_stems']
  532. return None
  533. #override
  534. def process_data(self, data):
  535. input_path_stem = Path(data[0]).stem
  536. return any ( [ input_path_stem == d_stem for d_stem in self.debug_paths_stems] )
  537. #override
  538. def get_data_name (self, data):
  539. #return string identificator of your data
  540. return data[0]
  541. #override
  542. def __init__(self, input_paths, debug_paths ):
  543. self.input_paths = input_paths
  544. self.debug_paths_stems = [ Path(d).stem for d in debug_paths]
  545. self.result = []
  546. super().__init__('DeletedFilesSearcherSubprocessor', DeletedFilesSearcherSubprocessor.Cli, 60)
  547. #override
  548. def process_info_generator(self):
  549. for i in range(min(multiprocessing.cpu_count(), 8)):
  550. yield 'CPU%d' % (i), {}, {'debug_paths_stems' : self.debug_paths_stems}
  551. #override
  552. def on_clients_initialized(self):
  553. io.progress_bar ("Searching deleted files", len (self.input_paths))
  554. #override
  555. def on_clients_finalized(self):
  556. io.progress_bar_close()
  557. #override
  558. def get_data(self, host_dict):
  559. if len (self.input_paths) > 0:
  560. return [self.input_paths.pop(0)]
  561. return None
  562. #override
  563. def on_data_return (self, host_dict, data):
  564. self.input_paths.insert(0, data[0])
  565. #override
  566. def on_result (self, host_dict, data, result):
  567. if result == False:
  568. self.result.append( data[0] )
  569. io.progress_bar_inc(1)
  570. #override
  571. def get_result(self):
  572. return self.result
  573. def main(input_dir,
  574. output_dir,
  575. debug_dir=None,
  576. detector='mt',
  577. manual_fix=False,
  578. manual_output_debug_fix=False,
  579. manual_window_size=1368,
  580. image_size=256,
  581. face_type='full_face',
  582. max_faces_from_image=0,
  583. device_args={}):
  584. input_path = Path(input_dir)
  585. output_path = Path(output_dir)
  586. face_type = FaceType.fromString(face_type)
  587. multi_gpu = device_args.get('multi_gpu', False)
  588. cpu_only = device_args.get('cpu_only', False)
  589. if not input_path.exists():
  590. raise ValueError('Input directory not found. Please ensure it exists.')
  591. if output_path.exists():
  592. if not manual_output_debug_fix and input_path != output_path:
  593. output_images_paths = Path_utils.get_image_paths(output_path)
  594. if len(output_images_paths) > 0:
  595. io.input_bool("WARNING !!! \n %s contains files! \n They will be deleted. \n Press enter to continue." % (str(output_path)), False )
  596. for filename in output_images_paths:
  597. Path(filename).unlink()
  598. else:
  599. output_path.mkdir(parents=True, exist_ok=True)
  600. if manual_output_debug_fix:
  601. if debug_dir is None:
  602. raise ValueError('debug-dir must be specified')
  603. detector = 'manual'
  604. io.log_info('Performing re-extract frames which were deleted from _debug directory.')
  605. input_path_image_paths = Path_utils.get_image_unique_filestem_paths(input_path, verbose_print_func=io.log_info)
  606. if debug_dir is not None:
  607. debug_output_path = Path(debug_dir)
  608. if manual_output_debug_fix:
  609. if not debug_output_path.exists():
  610. raise ValueError("%s not found " % ( str(debug_output_path) ))
  611. input_path_image_paths = DeletedFilesSearcherSubprocessor (input_path_image_paths, Path_utils.get_image_paths(debug_output_path) ).run()
  612. input_path_image_paths = sorted (input_path_image_paths)
  613. io.log_info('Found %d images.' % (len(input_path_image_paths)))
  614. else:
  615. if debug_output_path.exists():
  616. for filename in Path_utils.get_image_paths(debug_output_path):
  617. Path(filename).unlink()
  618. else:
  619. debug_output_path.mkdir(parents=True, exist_ok=True)
  620. images_found = len(input_path_image_paths)
  621. faces_detected = 0
  622. if images_found != 0:
  623. if detector == 'manual':
  624. io.log_info ('Performing manual extract...')
  625. data = ExtractSubprocessor ([ ExtractSubprocessor.Data(filename, manual=True) for filename in input_path_image_paths ], 'landmarks', image_size, face_type, debug_dir, cpu_only=cpu_only, manual=True, manual_window_size=manual_window_size).run()
  626. else:
  627. io.log_info ('Performing 1st pass...')
  628. data = ExtractSubprocessor ([ ExtractSubprocessor.Data(filename) for filename in input_path_image_paths ], 'rects-'+detector, image_size, face_type, debug_dir, multi_gpu=multi_gpu, cpu_only=cpu_only, manual=False, max_faces_from_image=max_faces_from_image).run()
  629. io.log_info ('Performing 2nd pass...')
  630. data = ExtractSubprocessor (data, 'landmarks', image_size, face_type, debug_dir, multi_gpu=multi_gpu, cpu_only=cpu_only, manual=False).run()
  631. io.log_info ('Performing 3rd pass...')
  632. data = ExtractSubprocessor (data, 'final', image_size, face_type, debug_dir, multi_gpu=multi_gpu, cpu_only=cpu_only, manual=False, final_output_path=output_path).run()
  633. faces_detected += sum([d.faces_detected for d in data])
  634. if manual_fix:
  635. if all ( np.array ( [ d.faces_detected > 0 for d in data] ) == True ):
  636. io.log_info ('All faces are detected, manual fix not needed.')
  637. else:
  638. fix_data = [ ExtractSubprocessor.Data(d.filename, manual=True) for d in data if d.faces_detected == 0 ]
  639. io.log_info ('Performing manual fix for %d images...' % (len(fix_data)) )
  640. fix_data = ExtractSubprocessor (fix_data, 'landmarks', image_size, face_type, debug_dir, manual=True, manual_window_size=manual_window_size).run()
  641. fix_data = ExtractSubprocessor (fix_data, 'final', image_size, face_type, debug_dir, multi_gpu=multi_gpu, cpu_only=cpu_only, manual=False, final_output_path=output_path).run()
  642. faces_detected += sum([d.faces_detected for d in fix_data])
  643. io.log_info ('-------------------------')
  644. io.log_info ('Images found: %d' % (images_found) )
  645. io.log_info ('Faces detected: %d' % (faces_detected) )
  646. io.log_info ('-------------------------')
Tip!

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

Comments

Loading...