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

DFLJPG.py 11 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
  1. import pickle
  2. import struct
  3. import traceback
  4. import cv2
  5. import numpy as np
  6. from core import imagelib
  7. from core.cv2ex import *
  8. from core.imagelib import SegIEPolys
  9. from core.interact import interact as io
  10. from core.structex import *
  11. from facelib import FaceType
  12. class DFLJPG(object):
  13. def __init__(self, filename):
  14. self.filename = filename
  15. self.data = b""
  16. self.length = 0
  17. self.chunks = []
  18. self.dfl_dict = None
  19. self.shape = None
  20. self.img = None
  21. @staticmethod
  22. def load_raw(filename, loader_func=None):
  23. try:
  24. if loader_func is not None:
  25. data = loader_func(filename)
  26. else:
  27. with open(filename, "rb") as f:
  28. data = f.read()
  29. except:
  30. raise FileNotFoundError(filename)
  31. try:
  32. inst = DFLJPG(filename)
  33. inst.data = data
  34. inst.length = len(data)
  35. inst_length = inst.length
  36. chunks = []
  37. data_counter = 0
  38. while data_counter < inst_length:
  39. chunk_m_l, chunk_m_h = struct.unpack ("BB", data[data_counter:data_counter+2])
  40. data_counter += 2
  41. if chunk_m_l != 0xFF:
  42. raise ValueError(f"No Valid JPG info in {filename}")
  43. chunk_name = None
  44. chunk_size = None
  45. chunk_data = None
  46. chunk_ex_data = None
  47. is_unk_chunk = False
  48. if chunk_m_h & 0xF0 == 0xD0:
  49. n = chunk_m_h & 0x0F
  50. if n >= 0 and n <= 7:
  51. chunk_name = "RST%d" % (n)
  52. chunk_size = 0
  53. elif n == 0x8:
  54. chunk_name = "SOI"
  55. chunk_size = 0
  56. if len(chunks) != 0:
  57. raise Exception("")
  58. elif n == 0x9:
  59. chunk_name = "EOI"
  60. chunk_size = 0
  61. elif n == 0xA:
  62. chunk_name = "SOS"
  63. elif n == 0xB:
  64. chunk_name = "DQT"
  65. elif n == 0xD:
  66. chunk_name = "DRI"
  67. chunk_size = 2
  68. else:
  69. is_unk_chunk = True
  70. elif chunk_m_h & 0xF0 == 0xC0:
  71. n = chunk_m_h & 0x0F
  72. if n == 0:
  73. chunk_name = "SOF0"
  74. elif n == 2:
  75. chunk_name = "SOF2"
  76. elif n == 4:
  77. chunk_name = "DHT"
  78. else:
  79. is_unk_chunk = True
  80. elif chunk_m_h & 0xF0 == 0xE0:
  81. n = chunk_m_h & 0x0F
  82. chunk_name = "APP%d" % (n)
  83. else:
  84. is_unk_chunk = True
  85. #if is_unk_chunk:
  86. # #raise ValueError(f"Unknown chunk {chunk_m_h} in {filename}")
  87. # io.log_info(f"Unknown chunk {chunk_m_h} in {filename}")
  88. if chunk_size == None: #variable size
  89. chunk_size, = struct.unpack (">H", data[data_counter:data_counter+2])
  90. chunk_size -= 2
  91. data_counter += 2
  92. if chunk_size > 0:
  93. chunk_data = data[data_counter:data_counter+chunk_size]
  94. data_counter += chunk_size
  95. if chunk_name == "SOS":
  96. c = data_counter
  97. while c < inst_length and (data[c] != 0xFF or data[c+1] != 0xD9):
  98. c += 1
  99. chunk_ex_data = data[data_counter:c]
  100. data_counter = c
  101. chunks.append ({'name' : chunk_name,
  102. 'm_h' : chunk_m_h,
  103. 'data' : chunk_data,
  104. 'ex_data' : chunk_ex_data,
  105. })
  106. inst.chunks = chunks
  107. return inst
  108. except Exception as e:
  109. raise Exception (f"Corrupted JPG file {filename} {e}")
  110. @staticmethod
  111. def load(filename, loader_func=None):
  112. try:
  113. inst = DFLJPG.load_raw (filename, loader_func=loader_func)
  114. inst.dfl_dict = {}
  115. for chunk in inst.chunks:
  116. if chunk['name'] == 'APP0':
  117. d, c = chunk['data'], 0
  118. c, id, _ = struct_unpack (d, c, "=4sB")
  119. if id == b"JFIF":
  120. c, ver_major, ver_minor, units, Xdensity, Ydensity, Xthumbnail, Ythumbnail = struct_unpack (d, c, "=BBBHHBB")
  121. else:
  122. raise Exception("Unknown jpeg ID: %s" % (id) )
  123. elif chunk['name'] == 'SOF0' or chunk['name'] == 'SOF2':
  124. d, c = chunk['data'], 0
  125. c, precision, height, width = struct_unpack (d, c, ">BHH")
  126. inst.shape = (height, width, 3)
  127. elif chunk['name'] == 'APP15':
  128. if type(chunk['data']) == bytes:
  129. inst.dfl_dict = pickle.loads(chunk['data'])
  130. return inst
  131. except Exception as e:
  132. io.log_err (f'Exception occured while DFLJPG.load : {traceback.format_exc()}')
  133. return None
  134. def has_data(self):
  135. return len(self.dfl_dict.keys()) != 0
  136. def save(self):
  137. try:
  138. with open(self.filename, "wb") as f:
  139. f.write ( self.dump() )
  140. except:
  141. raise Exception( f'cannot save {self.filename}' )
  142. def dump(self):
  143. data = b""
  144. dict_data = self.dfl_dict
  145. # Remove None keys
  146. for key in list(dict_data.keys()):
  147. if dict_data[key] is None:
  148. dict_data.pop(key)
  149. for chunk in self.chunks:
  150. if chunk['name'] == 'APP15':
  151. self.chunks.remove(chunk)
  152. break
  153. last_app_chunk = 0
  154. for i, chunk in enumerate (self.chunks):
  155. if chunk['m_h'] & 0xF0 == 0xE0:
  156. last_app_chunk = i
  157. dflchunk = {'name' : 'APP15',
  158. 'm_h' : 0xEF,
  159. 'data' : pickle.dumps(dict_data),
  160. 'ex_data' : None,
  161. }
  162. self.chunks.insert (last_app_chunk+1, dflchunk)
  163. for chunk in self.chunks:
  164. data += struct.pack ("BB", 0xFF, chunk['m_h'] )
  165. chunk_data = chunk['data']
  166. if chunk_data is not None:
  167. data += struct.pack (">H", len(chunk_data)+2 )
  168. data += chunk_data
  169. chunk_ex_data = chunk['ex_data']
  170. if chunk_ex_data is not None:
  171. data += chunk_ex_data
  172. return data
  173. def get_img(self):
  174. if self.img is None:
  175. self.img = cv2_imread(self.filename)
  176. return self.img
  177. def get_shape(self):
  178. if self.shape is None:
  179. img = self.get_img()
  180. if img is not None:
  181. self.shape = img.shape
  182. return self.shape
  183. def get_height(self):
  184. for chunk in self.chunks:
  185. if type(chunk) == IHDR:
  186. return chunk.height
  187. return 0
  188. def get_dict(self):
  189. return self.dfl_dict
  190. def set_dict (self, dict_data=None):
  191. self.dfl_dict = dict_data
  192. def get_face_type(self): return self.dfl_dict.get('face_type', FaceType.toString (FaceType.FULL) )
  193. def set_face_type(self, face_type): self.dfl_dict['face_type'] = face_type
  194. def get_landmarks(self): return np.array ( self.dfl_dict['landmarks'] )
  195. def set_landmarks(self, landmarks): self.dfl_dict['landmarks'] = landmarks
  196. def get_eyebrows_expand_mod(self): return self.dfl_dict.get ('eyebrows_expand_mod', 1.0)
  197. def set_eyebrows_expand_mod(self, eyebrows_expand_mod): self.dfl_dict['eyebrows_expand_mod'] = eyebrows_expand_mod
  198. def get_source_filename(self): return self.dfl_dict.get ('source_filename', None)
  199. def set_source_filename(self, source_filename): self.dfl_dict['source_filename'] = source_filename
  200. def get_source_rect(self): return self.dfl_dict.get ('source_rect', None)
  201. def set_source_rect(self, source_rect): self.dfl_dict['source_rect'] = source_rect
  202. def get_source_landmarks(self): return np.array ( self.dfl_dict.get('source_landmarks', None) )
  203. def set_source_landmarks(self, source_landmarks): self.dfl_dict['source_landmarks'] = source_landmarks
  204. def get_image_to_face_mat(self):
  205. mat = self.dfl_dict.get ('image_to_face_mat', None)
  206. if mat is not None:
  207. return np.array (mat)
  208. return None
  209. def set_image_to_face_mat(self, image_to_face_mat): self.dfl_dict['image_to_face_mat'] = image_to_face_mat
  210. def has_seg_ie_polys(self):
  211. return self.dfl_dict.get('seg_ie_polys',None) is not None
  212. def get_seg_ie_polys(self):
  213. d = self.dfl_dict.get('seg_ie_polys',None)
  214. if d is not None:
  215. d = SegIEPolys.load(d)
  216. else:
  217. d = SegIEPolys()
  218. return d
  219. def set_seg_ie_polys(self, seg_ie_polys):
  220. if seg_ie_polys is not None:
  221. if not isinstance(seg_ie_polys, SegIEPolys):
  222. raise ValueError('seg_ie_polys should be instance of SegIEPolys')
  223. if seg_ie_polys.has_polys():
  224. seg_ie_polys = seg_ie_polys.dump()
  225. else:
  226. seg_ie_polys = None
  227. self.dfl_dict['seg_ie_polys'] = seg_ie_polys
  228. def has_xseg_mask(self):
  229. return self.dfl_dict.get('xseg_mask',None) is not None
  230. def get_xseg_mask_compressed(self):
  231. mask_buf = self.dfl_dict.get('xseg_mask',None)
  232. if mask_buf is None:
  233. return None
  234. return mask_buf
  235. def get_xseg_mask(self):
  236. mask_buf = self.dfl_dict.get('xseg_mask',None)
  237. if mask_buf is None:
  238. return None
  239. img = cv2.imdecode(mask_buf, cv2.IMREAD_UNCHANGED)
  240. if len(img.shape) == 2:
  241. img = img[...,None]
  242. return img.astype(np.float32) / 255.0
  243. def set_xseg_mask(self, mask_a):
  244. if mask_a is None:
  245. self.dfl_dict['xseg_mask'] = None
  246. return
  247. mask_a = imagelib.normalize_channels(mask_a, 1)
  248. img_data = np.clip( mask_a*255, 0, 255 ).astype(np.uint8)
  249. data_max_len = 50000
  250. ret, buf = cv2.imencode('.png', img_data)
  251. if not ret or len(buf) > data_max_len:
  252. for jpeg_quality in range(100,-1,-1):
  253. ret, buf = cv2.imencode( '.jpg', img_data, [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_quality] )
  254. if ret and len(buf) <= data_max_len:
  255. break
  256. if not ret:
  257. raise Exception("set_xseg_mask: unable to generate image data for set_xseg_mask")
  258. self.dfl_dict['xseg_mask'] = buf
Tip!

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

Comments

Loading...