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

MaskEditorTool.py 20 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
  1. import os
  2. import sys
  3. import time
  4. import traceback
  5. from pathlib import Path
  6. import cv2
  7. import numpy as np
  8. import numpy.linalg as npl
  9. import imagelib
  10. from DFLIMG import *
  11. from facelib import LandmarksProcessor
  12. from imagelib import IEPolys
  13. from interact import interact as io
  14. from utils import Path_utils
  15. from utils.cv2_utils import *
  16. class MaskEditor:
  17. STATE_NONE=0
  18. STATE_MASKING=1
  19. def __init__(self, img, prev_images, next_images, mask=None, ie_polys=None, get_status_lines_func=None):
  20. self.img = imagelib.normalize_channels (img,3)
  21. h, w, c = img.shape
  22. if h != w and w != 256:
  23. #to support any square res, scale img,mask and ie_polys to 256, then scale ie_polys back on .get_ie_polys()
  24. raise Exception ("MaskEditor does not support image size != 256x256")
  25. ph, pw = h // 4, w // 4 #pad wh
  26. self.prev_images = prev_images
  27. self.next_images = next_images
  28. if mask is not None:
  29. self.mask = imagelib.normalize_channels (mask,3)
  30. else:
  31. self.mask = np.zeros ( (h,w,3) )
  32. self.get_status_lines_func = get_status_lines_func
  33. self.state_prop = self.STATE_NONE
  34. self.w, self.h = w, h
  35. self.pw, self.ph = pw, ph
  36. self.pwh = np.array([self.pw, self.ph])
  37. self.pwh2 = np.array([self.pw*2, self.ph*2])
  38. self.sw, self.sh = w+pw*2, h+ph*2
  39. self.prwh = 64 #preview wh
  40. if ie_polys is None:
  41. ie_polys = IEPolys()
  42. self.ie_polys = ie_polys
  43. self.polys_mask = None
  44. self.preview_images = None
  45. self.mouse_x = self.mouse_y = 9999
  46. self.screen_status_block = None
  47. self.screen_status_block_dirty = True
  48. self.screen_changed = True
  49. def set_state(self, state):
  50. self.state = state
  51. @property
  52. def state(self):
  53. return self.state_prop
  54. @state.setter
  55. def state(self, value):
  56. self.state_prop = value
  57. if value == self.STATE_MASKING:
  58. self.ie_polys.dirty = True
  59. def get_mask(self):
  60. if self.ie_polys.switch_dirty():
  61. self.screen_status_block_dirty = True
  62. self.ie_mask = img = self.mask.copy()
  63. self.ie_polys.overlay_mask(img)
  64. return img
  65. return self.ie_mask
  66. def get_screen_overlay(self):
  67. img = np.zeros ( (self.sh, self.sw, 3) )
  68. if self.state == self.STATE_MASKING:
  69. mouse_xy = self.mouse_xy.copy() + self.pwh
  70. l = self.ie_polys.n_list()
  71. if l.n > 0:
  72. p = l.cur_point().copy() + self.pwh
  73. color = (0,1,0) if l.type == 1 else (0,0,1)
  74. cv2.line(img, tuple(p), tuple(mouse_xy), color )
  75. return img
  76. def undo_to_begin_point(self):
  77. while not self.undo_point():
  78. pass
  79. def undo_point(self):
  80. self.screen_changed = True
  81. if self.state == self.STATE_NONE:
  82. if self.ie_polys.n > 0:
  83. self.state = self.STATE_MASKING
  84. if self.state == self.STATE_MASKING:
  85. if self.ie_polys.n_list().n_dec() == 0 and \
  86. self.ie_polys.n_dec() == 0:
  87. self.state = self.STATE_NONE
  88. else:
  89. return False
  90. return True
  91. def redo_to_end_point(self):
  92. while not self.redo_point():
  93. pass
  94. def redo_point(self):
  95. self.screen_changed = True
  96. if self.state == self.STATE_NONE:
  97. if self.ie_polys.n_max > 0:
  98. self.state = self.STATE_MASKING
  99. if self.ie_polys.n == 0:
  100. self.ie_polys.n_inc()
  101. if self.state == self.STATE_MASKING:
  102. while True:
  103. l = self.ie_polys.n_list()
  104. if l.n_inc() == l.n_max:
  105. if self.ie_polys.n == self.ie_polys.n_max:
  106. break
  107. self.ie_polys.n_inc()
  108. else:
  109. return False
  110. return True
  111. def combine_screens(self, screens):
  112. screens_len = len(screens)
  113. new_screens = []
  114. for screen, padded_overlay in screens:
  115. screen_img = np.zeros( (self.sh, self.sw, 3), dtype=np.float32 )
  116. screen = imagelib.normalize_channels (screen, 3)
  117. h,w,c = screen.shape
  118. screen_img[self.ph:-self.ph, self.pw:-self.pw, :] = screen
  119. if padded_overlay is not None:
  120. screen_img = screen_img + padded_overlay
  121. screen_img = np.clip(screen_img*255, 0, 255).astype(np.uint8)
  122. new_screens.append(screen_img)
  123. return np.concatenate (new_screens, axis=1)
  124. def get_screen_status_block(self, w, c):
  125. if self.screen_status_block_dirty:
  126. self.screen_status_block_dirty = False
  127. lines = [
  128. 'Polys current/max = %d/%d' % (self.ie_polys.n, self.ie_polys.n_max),
  129. ]
  130. if self.get_status_lines_func is not None:
  131. lines += self.get_status_lines_func()
  132. lines_count = len(lines)
  133. h_line = 21
  134. h = lines_count * h_line
  135. img = np.ones ( (h,w,c) ) * 0.1
  136. for i in range(lines_count):
  137. img[ i*h_line:(i+1)*h_line, 0:w] += \
  138. imagelib.get_text_image ( (h_line,w,c), lines[i], color=[0.8]*c )
  139. self.screen_status_block = np.clip(img*255, 0, 255).astype(np.uint8)
  140. return self.screen_status_block
  141. def set_screen_status_block_dirty(self):
  142. self.screen_status_block_dirty = True
  143. def set_screen_changed(self):
  144. self.screen_changed = True
  145. def switch_screen_changed(self):
  146. result = self.screen_changed
  147. self.screen_changed = False
  148. return result
  149. def make_screen(self):
  150. screen_overlay = self.get_screen_overlay()
  151. final_mask = self.get_mask()
  152. masked_img = self.img*final_mask*0.5 + self.img*(1-final_mask)
  153. pink = np.full ( (self.h, self.w, 3), (1,0,1) )
  154. pink_masked_img = self.img*final_mask + pink*(1-final_mask)
  155. screens = [ (self.img, screen_overlay),
  156. (masked_img, screen_overlay),
  157. (pink_masked_img, screen_overlay),
  158. ]
  159. screens = self.combine_screens(screens)
  160. if self.preview_images is None:
  161. sh,sw,sc = screens.shape
  162. prh, prw = self.prwh, self.prwh
  163. total_w = sum ([ img.shape[1] for (t,img) in self.prev_images ]) + \
  164. sum ([ img.shape[1] for (t,img) in self.next_images ])
  165. total_images_len = len(self.prev_images) + len(self.next_images)
  166. max_hor_images_count = sw // prw
  167. max_side_images_count = (max_hor_images_count - 1) // 2
  168. prev_images = self.prev_images[-max_side_images_count:]
  169. next_images = self.next_images[:max_side_images_count]
  170. border = 2
  171. max_wh_bordered = (prw-border*2, prh-border*2)
  172. prev_images = [ (t, cv2.resize( imagelib.normalize_channels(img, 3), max_wh_bordered )) for t,img in prev_images ]
  173. next_images = [ (t, cv2.resize( imagelib.normalize_channels(img, 3), max_wh_bordered )) for t,img in next_images ]
  174. for images in [prev_images, next_images]:
  175. for i, (t, img) in enumerate(images):
  176. new_img = np.zeros ( (prh,prw, sc) )
  177. new_img[border:-border,border:-border] = img
  178. if t == 2:
  179. cv2.line (new_img, ( prw//2, int(prh//1.5) ), (int(prw/1.5), prh ) , (0,1,0), thickness=2 )
  180. cv2.line (new_img, ( int(prw/1.5), prh ), ( prw, prh // 2 ) , (0,1,0), thickness=2 )
  181. elif t == 1:
  182. cv2.line (new_img, ( prw//2, prh//2 ), ( prw, prh ) , (0,0,1), thickness=2 )
  183. cv2.line (new_img, ( prw//2, prh ), ( prw, prh // 2 ) , (0,0,1), thickness=2 )
  184. images[i] = new_img
  185. preview_images = []
  186. if len(prev_images) > 0:
  187. preview_images += [ np.concatenate (prev_images, axis=1) ]
  188. img = np.full ( (prh,prw, sc), (0,0,1), dtype=np.float )
  189. img[border:-border,border:-border] = cv2.resize( self.img, max_wh_bordered )
  190. preview_images += [ img ]
  191. if len(next_images) > 0:
  192. preview_images += [ np.concatenate (next_images, axis=1) ]
  193. preview_images = np.concatenate ( preview_images, axis=1 )
  194. left_pad = sw // 2 - len(prev_images) * prw - prw // 2
  195. right_pad = sw // 2 - len(next_images) * prw - prw // 2
  196. preview_images = np.concatenate ([np.zeros ( (preview_images.shape[0], left_pad, preview_images.shape[2]) ),
  197. preview_images,
  198. np.zeros ( (preview_images.shape[0], right_pad, preview_images.shape[2]) )
  199. ], axis=1)
  200. self.preview_images = np.clip(preview_images * 255, 0, 255 ).astype(np.uint8)
  201. status_img = self.get_screen_status_block( screens.shape[1], screens.shape[2] )
  202. result = np.concatenate ( [self.preview_images, screens, status_img], axis=0 )
  203. return result
  204. def mask_finish(self, n_clip=True):
  205. if self.state == self.STATE_MASKING:
  206. self.screen_changed = True
  207. if self.ie_polys.n_list().n <= 2:
  208. self.ie_polys.n_dec()
  209. self.state = self.STATE_NONE
  210. if n_clip:
  211. self.ie_polys.n_clip()
  212. def set_mouse_pos(self,x,y):
  213. if self.preview_images is not None:
  214. y -= self.preview_images.shape[0]
  215. mouse_x = x % (self.sw) - self.pw
  216. mouse_y = y % (self.sh) - self.ph
  217. if mouse_x != self.mouse_x or mouse_y != self.mouse_y:
  218. self.mouse_xy = np.array( [mouse_x, mouse_y] )
  219. self.mouse_x, self.mouse_y = self.mouse_xy
  220. self.screen_changed = True
  221. def mask_point(self, type):
  222. self.screen_changed = True
  223. if self.state == self.STATE_MASKING and \
  224. self.ie_polys.n_list().type != type:
  225. self.mask_finish()
  226. elif self.state == self.STATE_NONE:
  227. self.state = self.STATE_MASKING
  228. self.ie_polys.add(type)
  229. if self.state == self.STATE_MASKING:
  230. self.ie_polys.n_list().add (self.mouse_x, self.mouse_y)
  231. def get_ie_polys(self):
  232. return self.ie_polys
  233. def set_ie_polys(self, saved_ie_polys):
  234. self.state = self.STATE_NONE
  235. self.ie_polys = saved_ie_polys
  236. self.redo_to_end_point()
  237. self.mask_finish()
  238. def mask_editor_main(input_dir, confirmed_dir=None, skipped_dir=None, no_default_mask=False):
  239. input_path = Path(input_dir)
  240. confirmed_path = Path(confirmed_dir)
  241. skipped_path = Path(skipped_dir)
  242. if not input_path.exists():
  243. raise ValueError('Input directory not found. Please ensure it exists.')
  244. if not confirmed_path.exists():
  245. confirmed_path.mkdir(parents=True)
  246. if not skipped_path.exists():
  247. skipped_path.mkdir(parents=True)
  248. if not no_default_mask:
  249. eyebrows_expand_mod = np.clip ( io.input_int ("Default eyebrows expand modifier? (0..400, skip:100) : ", 100), 0, 400 ) / 100.0
  250. else:
  251. eyebrows_expand_mod = None
  252. wnd_name = "MaskEditor tool"
  253. io.named_window (wnd_name)
  254. io.capture_mouse(wnd_name)
  255. io.capture_keys(wnd_name)
  256. cached_images = {}
  257. image_paths = [ Path(x) for x in Path_utils.get_image_paths(input_path)]
  258. done_paths = []
  259. done_images_types = {}
  260. image_paths_total = len(image_paths)
  261. saved_ie_polys = IEPolys()
  262. zoom_factor = 1.0
  263. preview_images_count = 9
  264. target_wh = 256
  265. do_prev_count = 0
  266. do_save_move_count = 0
  267. do_save_count = 0
  268. do_skip_move_count = 0
  269. do_skip_count = 0
  270. def jobs_count():
  271. return do_prev_count + do_save_move_count + do_save_count + do_skip_move_count + do_skip_count
  272. is_exit = False
  273. while not is_exit:
  274. if len(image_paths) > 0:
  275. filepath = image_paths.pop(0)
  276. else:
  277. filepath = None
  278. next_image_paths = image_paths[0:preview_images_count]
  279. next_image_paths_names = [ path.name for path in next_image_paths ]
  280. prev_image_paths = done_paths[-preview_images_count:]
  281. prev_image_paths_names = [ path.name for path in prev_image_paths ]
  282. for key in list( cached_images.keys() ):
  283. if key not in prev_image_paths_names and \
  284. key not in next_image_paths_names:
  285. cached_images.pop(key)
  286. for paths in [prev_image_paths, next_image_paths]:
  287. for path in paths:
  288. if path.name not in cached_images:
  289. cached_images[path.name] = cv2_imread(str(path)) / 255.0
  290. if filepath is not None:
  291. dflimg = DFLIMG.load (filepath)
  292. if dflimg is None:
  293. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  294. continue
  295. else:
  296. lmrks = dflimg.get_landmarks()
  297. ie_polys = IEPolys.load(dflimg.get_ie_polys())
  298. fanseg_mask = dflimg.get_fanseg_mask()
  299. if filepath.name in cached_images:
  300. img = cached_images[filepath.name]
  301. else:
  302. img = cached_images[filepath.name] = cv2_imread(str(filepath)) / 255.0
  303. if fanseg_mask is not None:
  304. mask = fanseg_mask
  305. else:
  306. if no_default_mask:
  307. mask = np.zeros ( (target_wh,target_wh,3) )
  308. else:
  309. mask = LandmarksProcessor.get_image_hull_mask( img.shape, lmrks, eyebrows_expand_mod=eyebrows_expand_mod)
  310. else:
  311. img = np.zeros ( (target_wh,target_wh,3) )
  312. mask = np.ones ( (target_wh,target_wh,3) )
  313. ie_polys = None
  314. def get_status_lines_func():
  315. return ['Progress: %d / %d . Current file: %s' % (len(done_paths), image_paths_total, str(filepath.name) if filepath is not None else "end" ),
  316. '[Left mouse button] - mark include mask.',
  317. '[Right mouse button] - mark exclude mask.',
  318. '[Middle mouse button] - finish current poly.',
  319. '[Mouse wheel] - undo/redo poly or point. [+ctrl] - undo to begin/redo to end',
  320. '[r] - applies edits made to last saved image.',
  321. '[q] - prev image. [w] - skip and move to %s. [e] - save and move to %s. ' % (skipped_path.name, confirmed_path.name),
  322. '[z] - prev image. [x] - skip. [c] - save. ',
  323. 'hold [shift] - speed up the frame counter by 10.',
  324. '[-/+] - window zoom [esc] - quit',
  325. ]
  326. try:
  327. ed = MaskEditor(img,
  328. [ (done_images_types[name], cached_images[name]) for name in prev_image_paths_names ],
  329. [ (0, cached_images[name]) for name in next_image_paths_names ],
  330. mask, ie_polys, get_status_lines_func)
  331. except Exception as e:
  332. print(e)
  333. continue
  334. next = False
  335. while not next:
  336. io.process_messages(0.005)
  337. if jobs_count() == 0:
  338. for (x,y,ev,flags) in io.get_mouse_events(wnd_name):
  339. x, y = int (x / zoom_factor), int(y / zoom_factor)
  340. ed.set_mouse_pos(x, y)
  341. if filepath is not None:
  342. if ev == io.EVENT_LBUTTONDOWN:
  343. ed.mask_point(1)
  344. elif ev == io.EVENT_RBUTTONDOWN:
  345. ed.mask_point(0)
  346. elif ev == io.EVENT_MBUTTONDOWN:
  347. ed.mask_finish()
  348. elif ev == io.EVENT_MOUSEWHEEL:
  349. if flags & 0x80000000 != 0:
  350. if flags & 0x8 != 0:
  351. ed.undo_to_begin_point()
  352. else:
  353. ed.undo_point()
  354. else:
  355. if flags & 0x8 != 0:
  356. ed.redo_to_end_point()
  357. else:
  358. ed.redo_point()
  359. for key, chr_key, ctrl_pressed, alt_pressed, shift_pressed in io.get_key_events(wnd_name):
  360. if chr_key == 'q' or chr_key == 'z':
  361. do_prev_count = 1 if not shift_pressed else 10
  362. elif chr_key == '-':
  363. zoom_factor = np.clip (zoom_factor-0.1, 0.1, 4.0)
  364. ed.set_screen_changed()
  365. elif chr_key == '+':
  366. zoom_factor = np.clip (zoom_factor+0.1, 0.1, 4.0)
  367. ed.set_screen_changed()
  368. elif key == 27: #esc
  369. is_exit = True
  370. next = True
  371. break
  372. elif filepath is not None:
  373. if chr_key == 'e':
  374. saved_ie_polys = ed.ie_polys
  375. do_save_move_count = 1 if not shift_pressed else 10
  376. elif chr_key == 'c':
  377. saved_ie_polys = ed.ie_polys
  378. do_save_count = 1 if not shift_pressed else 10
  379. elif chr_key == 'w':
  380. do_skip_move_count = 1 if not shift_pressed else 10
  381. elif chr_key == 'x':
  382. do_skip_count = 1 if not shift_pressed else 10
  383. elif chr_key == 'r' and saved_ie_polys != None:
  384. ed.set_ie_polys(saved_ie_polys)
  385. if do_prev_count > 0:
  386. do_prev_count -= 1
  387. if len(done_paths) > 0:
  388. if filepath is not None:
  389. image_paths.insert(0, filepath)
  390. filepath = done_paths.pop(-1)
  391. done_images_types[filepath.name] = 0
  392. if filepath.parent != input_path:
  393. new_filename_path = input_path / filepath.name
  394. filepath.rename ( new_filename_path )
  395. image_paths.insert(0, new_filename_path)
  396. else:
  397. image_paths.insert(0, filepath)
  398. next = True
  399. elif filepath is not None:
  400. if do_save_move_count > 0:
  401. do_save_move_count -= 1
  402. ed.mask_finish()
  403. dflimg.embed_and_set (str(filepath), ie_polys=ed.get_ie_polys(), eyebrows_expand_mod=eyebrows_expand_mod )
  404. done_paths += [ confirmed_path / filepath.name ]
  405. done_images_types[filepath.name] = 2
  406. filepath.rename(done_paths[-1])
  407. next = True
  408. elif do_save_count > 0:
  409. do_save_count -= 1
  410. ed.mask_finish()
  411. dflimg.embed_and_set (str(filepath), ie_polys=ed.get_ie_polys(), eyebrows_expand_mod=eyebrows_expand_mod )
  412. done_paths += [ filepath ]
  413. done_images_types[filepath.name] = 2
  414. next = True
  415. elif do_skip_move_count > 0:
  416. do_skip_move_count -= 1
  417. done_paths += [ skipped_path / filepath.name ]
  418. done_images_types[filepath.name] = 1
  419. filepath.rename(done_paths[-1])
  420. next = True
  421. elif do_skip_count > 0:
  422. do_skip_count -= 1
  423. done_paths += [ filepath ]
  424. done_images_types[filepath.name] = 1
  425. next = True
  426. else:
  427. do_save_move_count = do_save_count = do_skip_move_count = do_skip_count = 0
  428. if jobs_count() == 0:
  429. if ed.switch_screen_changed():
  430. screen = ed.make_screen()
  431. if zoom_factor != 1.0:
  432. h,w,c = screen.shape
  433. screen = cv2.resize ( screen, ( int(w*zoom_factor), int(h*zoom_factor) ) )
  434. io.show_image (wnd_name, screen )
  435. io.process_messages(0.005)
  436. io.destroy_all_windows()
Tip!

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

Comments

Loading...