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

FacesetRelighter.py 10 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
  1. import traceback
  2. from pathlib import Path
  3. import imagelib
  4. from interact import interact as io
  5. from nnlib import DeepPortraitRelighting
  6. from utils import Path_utils
  7. from utils.cv2_utils import *
  8. from DFLIMG import *
  9. class RelightEditor:
  10. def __init__(self, image_paths, dpr, lighten):
  11. self.image_paths = image_paths
  12. self.dpr = dpr
  13. self.lighten = lighten
  14. self.current_img_path = None
  15. self.current_img = None
  16. self.current_img_shape = None
  17. self.pick_new_face()
  18. self.alt_azi_ar = [ [0,0,1.0] ]
  19. self.alt_azi_cur = 0
  20. self.mouse_x = self.mouse_y = 9999
  21. self.screen_status_block = None
  22. self.screen_status_block_dirty = True
  23. self.screen_changed = True
  24. def pick_new_face(self):
  25. self.current_img_path = self.image_paths[ np.random.randint(len(self.image_paths)) ]
  26. self.current_img = cv2_imread (str(self.current_img_path))
  27. self.current_img_shape = self.current_img.shape
  28. self.set_screen_changed()
  29. def set_screen_changed(self):
  30. self.screen_changed = True
  31. def switch_screen_changed(self):
  32. result = self.screen_changed
  33. self.screen_changed = False
  34. return result
  35. def make_screen(self):
  36. alt,azi,inten=self.alt_azi_ar[self.alt_azi_cur]
  37. img = self.dpr.relight (self.current_img, alt, azi, inten, self.lighten)
  38. h,w,c = img.shape
  39. lines = ['Pick light directions for whole faceset.',
  40. '[q]-new test face',
  41. '[w][e]-navigate',
  42. '[a][s]-intensity',
  43. '[r]-new [t]-delete [enter]-process',
  44. '']
  45. for i, (alt,azi,inten) in enumerate(self.alt_azi_ar):
  46. s = '>:' if self.alt_azi_cur == i else ' :'
  47. s += f'alt=[{ int(alt):03}] azi=[{ int(azi):03}] int=[{inten:01.1f}]'
  48. lines += [ s ]
  49. lines_count = len(lines)
  50. h_line = 16
  51. sh = lines_count * h_line
  52. sw = 400
  53. sc = c
  54. status_img = np.ones ( (sh,sw,sc) ) * 0.1
  55. for i in range(lines_count):
  56. status_img[ i*h_line:(i+1)*h_line, 0:sw] += \
  57. imagelib.get_text_image ( (h_line,sw,c), lines[i], color=[0.8]*c )
  58. status_img = np.clip(status_img*255, 0, 255).astype(np.uint8)
  59. #combine screens
  60. if sh > h:
  61. img = np.concatenate ([img, np.zeros( (sh-h,w,c), dtype=img.dtype ) ], axis=0)
  62. elif h > sh:
  63. status_img = np.concatenate ([status_img, np.zeros( (h-sh,sw,sc), dtype=img.dtype ) ], axis=0)
  64. img = np.concatenate ([img, status_img], axis=1)
  65. return img
  66. def run(self):
  67. wnd_name = "Relighter"
  68. io.named_window(wnd_name)
  69. io.capture_keys(wnd_name)
  70. io.capture_mouse(wnd_name)
  71. zoom_factor = 1.0
  72. is_angle_editing = False
  73. is_exit = False
  74. while not is_exit:
  75. io.process_messages(0.0001)
  76. mouse_events = io.get_mouse_events(wnd_name)
  77. for ev in mouse_events:
  78. (x, y, ev, flags) = ev
  79. if ev == io.EVENT_LBUTTONDOWN:
  80. is_angle_editing = True
  81. if ev == io.EVENT_LBUTTONUP:
  82. is_angle_editing = False
  83. if is_angle_editing:
  84. h,w,c = self.current_img_shape
  85. alt,azi,inten = self.alt_azi_ar[self.alt_azi_cur]
  86. alt = np.clip ( ( 0.5-y/w )*2.0, -1, 1)*90
  87. azi = np.clip ( (x / h - 0.5)*2.0, -1, 1)*90
  88. self.alt_azi_ar[self.alt_azi_cur] = (alt,azi,inten)
  89. self.set_screen_changed()
  90. key_events = io.get_key_events(wnd_name)
  91. key, chr_key, ctrl_pressed, alt_pressed, shift_pressed = key_events[-1] if len(key_events) > 0 else (0,0,False,False,False)
  92. if key != 0:
  93. if chr_key == 'q':
  94. self.pick_new_face()
  95. elif chr_key == 'w':
  96. self.alt_azi_cur = np.clip (self.alt_azi_cur-1, 0, len(self.alt_azi_ar)-1)
  97. self.set_screen_changed()
  98. elif chr_key == 'e':
  99. self.alt_azi_cur = np.clip (self.alt_azi_cur+1, 0, len(self.alt_azi_ar)-1)
  100. self.set_screen_changed()
  101. elif chr_key == 'r':
  102. #add direction
  103. self.alt_azi_ar += [ [0,0,1.0] ]
  104. self.alt_azi_cur +=1
  105. self.set_screen_changed()
  106. elif chr_key == 't':
  107. if len(self.alt_azi_ar) > 1:
  108. self.alt_azi_ar.pop(self.alt_azi_cur)
  109. self.alt_azi_cur = np.clip (self.alt_azi_cur, 0, len(self.alt_azi_ar)-1)
  110. self.set_screen_changed()
  111. elif chr_key == 'a':
  112. alt,azi,inten = self.alt_azi_ar[self.alt_azi_cur]
  113. inten = np.clip ( inten-0.1, 0.0, 1.0)
  114. self.alt_azi_ar[self.alt_azi_cur] = (alt,azi,inten)
  115. self.set_screen_changed()
  116. elif chr_key == 's':
  117. alt,azi,inten = self.alt_azi_ar[self.alt_azi_cur]
  118. inten = np.clip ( inten+0.1, 0.0, 1.0)
  119. self.alt_azi_ar[self.alt_azi_cur] = (alt,azi,inten)
  120. self.set_screen_changed()
  121. elif key == 27 or chr_key == '\r' or chr_key == '\n': #esc
  122. is_exit = True
  123. if self.switch_screen_changed():
  124. screen = self.make_screen()
  125. if zoom_factor != 1.0:
  126. h,w,c = screen.shape
  127. screen = cv2.resize ( screen, ( int(w*zoom_factor), int(h*zoom_factor) ) )
  128. io.show_image (wnd_name, screen )
  129. io.destroy_window(wnd_name)
  130. return self.alt_azi_ar
  131. def relight(input_dir, lighten=None, random_one=None):
  132. if lighten is None:
  133. lighten = io.input_bool ("Lighten the faces? ( y/n default:n ?:help ) : ", False, help_message="Lighten the faces instead of shadow. May produce artifacts." )
  134. if io.is_colab():
  135. io.log_info("In colab version you cannot choose light directions manually.")
  136. manual = False
  137. else:
  138. manual = io.input_bool ("Choose light directions manually? ( y/n default:y ) : ", True)
  139. if not manual:
  140. if random_one is None:
  141. random_one = io.input_bool ("Relight the faces only with one random direction and random intensity? ( y/n default:y ?:help) : ", True, help_message="Otherwise faceset will be relighted with predefined 7 light directions but with random intensity.")
  142. image_paths = [Path(x) for x in Path_utils.get_image_paths(input_dir)]
  143. filtered_image_paths = []
  144. for filepath in io.progress_bar_generator(image_paths, "Collecting fileinfo"):
  145. try:
  146. dflimg = DFLIMG.load (Path(filepath))
  147. if dflimg is None:
  148. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  149. else:
  150. if not dflimg.get_relighted():
  151. filtered_image_paths += [filepath]
  152. except:
  153. io.log_err (f"Exception occured while processing file {filepath.name}. Error: {traceback.format_exc()}")
  154. image_paths = filtered_image_paths
  155. if len(image_paths) == 0:
  156. io.log_info("No files to process.")
  157. return
  158. dpr = DeepPortraitRelighting()
  159. if manual:
  160. alt_azi_ar = RelightEditor(image_paths, dpr, lighten).run()
  161. for filepath in io.progress_bar_generator(image_paths, "Relighting"):
  162. try:
  163. dflimg = DFLIMG.load ( Path(filepath) )
  164. if dflimg is None:
  165. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  166. continue
  167. else:
  168. if dflimg.get_relighted():
  169. continue
  170. img = cv2_imread (str(filepath))
  171. if random_one:
  172. alt = np.random.randint(-90,91)
  173. azi = np.random.randint(-90,91)
  174. inten = np.random.random()*0.3+0.3
  175. relighted_imgs = [dpr.relight(img,alt=alt,azi=azi,intensity=inten,lighten=lighten)]
  176. else:
  177. if not manual and not random_one:
  178. inten = np.random.random()*0.3+0.3
  179. alt_azi_ar = [(60,0,inten), (60,60,inten), (0,60,inten), (-60,60,inten), (-60,0,inten), (-60,-60,inten), (0,-60,inten), (60,-60,inten)]
  180. relighted_imgs = [dpr.relight(img,alt=alt,azi=azi,intensity=inten,lighten=lighten) for (alt,azi,inten) in alt_azi_ar ]
  181. i = 0
  182. for i,relighted_img in enumerate(relighted_imgs):
  183. im_flags = []
  184. if filepath.suffix == '.jpg':
  185. im_flags += [int(cv2.IMWRITE_JPEG_QUALITY), 100]
  186. while True:
  187. relighted_filepath = filepath.parent / (filepath.stem+f'_relighted_{i}'+filepath.suffix)
  188. if not relighted_filepath.exists():
  189. break
  190. i += 1
  191. cv2_imwrite (relighted_filepath, relighted_img )
  192. dflimg.remove_source_filename()
  193. dflimg.embed_and_set (relighted_filepath, relighted=True )
  194. except:
  195. io.log_err (f"Exception occured while processing file {filepath.name}. Error: {traceback.format_exc()}")
  196. def delete_relighted(input_dir):
  197. input_path = Path(input_dir)
  198. image_paths = [Path(x) for x in Path_utils.get_image_paths(input_path)]
  199. files_to_delete = []
  200. for filepath in io.progress_bar_generator(image_paths, "Loading"):
  201. dflimg = DFLIMG.load ( Path(filepath) )
  202. if dflimg is None:
  203. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  204. continue
  205. else:
  206. if dflimg.get_relighted():
  207. files_to_delete += [filepath]
  208. for file in io.progress_bar_generator(files_to_delete, "Deleting"):
  209. file.unlink()
Tip!

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

Comments

Loading...