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

image_preprocessing.py 8.2 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
  1. import os
  2. import sys
  3. import inspect
  4. currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
  5. parentdir = os.path.dirname(currentdir)
  6. sys.path.insert(0, parentdir)
  7. import cv2
  8. import click
  9. import subprocess
  10. from tqdm import tqdm
  11. from pathlib import Path
  12. from segmentation.inference.inference import segmentation
  13. import numpy as np
  14. import quaternion
  15. import json
  16. @click.group()
  17. def main():
  18. """Entrypoint for scripts"""
  19. pass
  20. CAMERA_ID = 0
  21. def parse_meta(meta_):
  22. """
  23. In-place parser
  24. :param meta_: metadata dict
  25. :return: None
  26. """
  27. meta_["l"] = float(meta_["camera_distance"])
  28. meta_["h"] = float(meta_["camera_height"]) - float(meta_["stand_height"])
  29. meta_["l"] /= meta_["h"]
  30. meta_["h"] /= meta_["h"]
  31. meta_['theta_direction'] = int(meta_.get('theta_direction', 1))
  32. trim_ = meta_.get('trim', [0, 99999999999])
  33. meta_['trim'] = [int(trim_[0]), int(trim_[1])]
  34. def get_theta(n_fr, lookup=None, meta_=None):
  35. """
  36. Main callable to get theta rotation angle from the frame number
  37. :param n_fr: int number of frame
  38. :param lookup: a lookup table. if not None the thetas will be sampled from there
  39. :param meta_: a metadata dict
  40. :return: theta angle in radians preserving direction sign
  41. """
  42. if lookup is not None:
  43. return lookup[n_fr]
  44. if n_fr < meta_['trim'][0]:
  45. return 0
  46. elif n_fr > meta_['trim'][1]:
  47. return meta_['theta_direction'] * 2 * np.pi
  48. else:
  49. return meta_['theta_direction'] * 2 * np.pi * (n_fr - meta_['trim'][0]) / (meta_['trim'][1] - meta_['trim'][0])
  50. def get_camera_init_qt(meta_):
  51. """
  52. Return two initial camera quaternion parameters (R|T)
  53. :param meta_: parsed metadata
  54. :return: tuple of (R|T) quaternions
  55. """
  56. R_acute = quaternion.from_rotation_vector(
  57. [-(np.pi / 2 + np.arcsin(meta_["h"] / meta_["l"])), 0, 0]
  58. )
  59. T = quaternion.from_vector_part(
  60. [0, -np.sqrt(meta_["l"] ** 2 - meta_["h"] ** 2), meta_["h"]]
  61. )
  62. return R_acute, T
  63. def rotate_by_theta(theta_, camera_position):
  64. """
  65. Return new camera position as a tuple of quaternions (R|T)
  66. :param theta_: scalar angle in radians with preserved sign
  67. :param camera_position: tuple of position quaternions (R|T)
  68. :return: new tuple of position quaternions at the angle theta
  69. """
  70. theta_rot = quaternion.from_rotation_vector([0, 0, theta_])
  71. R = theta_rot * camera_position[0]
  72. T = theta_rot * camera_position[1] * theta_rot.conjugate()
  73. return R, T
  74. @main.command()
  75. @click.option("--path_to_video", default="video/video_blue.MP4", type=str)
  76. @click.option("--path_to_images_folder", default="images/", type=str)
  77. @click.option("--amount_of_frames", default=150, type=int)
  78. @click.option("--metadata", default="data/raw/meta/meta.json", type=str)
  79. @click.option("--theta_path", default="None")
  80. @click.option("--colmap_text_folder", default="data/processed/colmap_db/colmap_text")
  81. def extract_images_from_video(
  82. path_to_video: str,
  83. path_to_images_folder: str,
  84. amount_of_frames: int,
  85. metadata: str,
  86. theta_path: str,
  87. colmap_text_folder: str,
  88. ) -> None:
  89. """
  90. Extract predefined number of images from video
  91. @param path_to_video: path to video file
  92. @param path_to_images_folder: path to image folder
  93. @param amount_of_frames: desirable amount of images to extract
  94. @param metadata: metadata of the video
  95. @param theta_path: path to json file containing theta angles per frame
  96. @param colmap_text_folder: folder to save colmap images
  97. @return: None
  98. """
  99. os.makedirs(colmap_text_folder, exist_ok=True)
  100. if not os.path.exists(metadata):
  101. raise FileNotFoundError("A meta.json file is required")
  102. with open(metadata) as j:
  103. meta = json.load(j)
  104. parse_meta(meta)
  105. if os.path.exists(theta_path):
  106. theta_lookup = {}
  107. with open(theta_path) as th:
  108. theta_f = json.load(th)
  109. for k, v in theta_f.items():
  110. theta_lookup[int(k)] = float(v)
  111. else:
  112. theta_lookup = None
  113. print("start extract_images_from_video")
  114. os.makedirs(path_to_images_folder, exist_ok=True)
  115. path_to_images_folder = Path(path_to_images_folder)
  116. # Read the video from specified path
  117. cam = cv2.VideoCapture(path_to_video)
  118. frame_count = int(cam.get(cv2.CAP_PROP_FRAME_COUNT))
  119. reducer = (meta['trim'][1] - meta['trim'][0]) // amount_of_frames
  120. # frame
  121. frame_number = 0
  122. frame_to_write_number = 0
  123. camera_init_pose = get_camera_init_qt(meta)
  124. with open(os.path.join(colmap_text_folder, "images.txt"), "w") as out:
  125. pass
  126. with tqdm(total=meta['trim'][1] - meta['trim'][0]) as pbar:
  127. while True:
  128. # reading from frame
  129. ret, frame = cam.read()
  130. # frame = cv2.rotate(frame, cv2.ROTATE_180)
  131. if not ret:
  132. break
  133. if not meta['trim'][0] <= frame_number <= meta['trim'][1]:
  134. frame_number += 1
  135. continue
  136. if (frame_number - meta['trim'][0]) % reducer == 0:
  137. name = path_to_images_folder / f"{frame_to_write_number:03d}.jpg"
  138. cv2.imwrite(str(name), frame)
  139. theta = get_theta(frame_number, lookup=theta_lookup, meta_=meta)
  140. r, t = rotate_by_theta(theta, camera_init_pose)
  141. r = r.conjugate() # make it a world to camera transform
  142. t = -r * t * r.conjugate()
  143. with open(
  144. os.path.join(colmap_text_folder, "images.txt"), "a"
  145. ) as out:
  146. out.write(
  147. f"{frame_to_write_number} {r.w} {r.x} {r.y} {r.z} {t.x} "
  148. f"{t.y} {t.z} {CAMERA_ID} "
  149. f"{frame_to_write_number:03d}.png\n0 0 -1\n"
  150. ) # 0 0 -1 is a placeholder
  151. frame_to_write_number += 1
  152. frame_number += 1
  153. pbar.update()
  154. @main.command()
  155. @click.option("--path_to_images_folder", default="images/", type=str)
  156. @click.option("--path_to_cropped_images_folder", default="cropped_images/", type=str)
  157. def crop_resize_images(
  158. path_to_images_folder: str,
  159. path_to_cropped_images_folder: str,
  160. ) -> None:
  161. """
  162. Crop and resize images
  163. @param path_to_images_folder: path to extracted images
  164. @param path_to_cropped_images_folder: path to save cropped images
  165. @return: None
  166. """
  167. print("start crop_resize_images")
  168. os.makedirs(path_to_cropped_images_folder, exist_ok=True)
  169. path_to_cropped_images_folder = Path(path_to_cropped_images_folder)
  170. images = [x for x in Path(path_to_images_folder).glob("*.jpg")]
  171. h, w, _ = cv2.imread(str(images[0])).shape
  172. for image_path in tqdm(images, total=len(images)):
  173. image = cv2.imread(str(image_path))
  174. image = image[170: h - 410, 710: w - 710]
  175. # image = image[delta: h - delta, delta: w - delta]
  176. width = 800
  177. height = 800
  178. dim = (width, height)
  179. # resize image
  180. image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
  181. cv2.imwrite(
  182. str(path_to_cropped_images_folder / (image_path.stem + ".png")), image
  183. )
  184. @main.command()
  185. @click.option("--path_to_cropped_images_folder", default="cropped_images/", type=str)
  186. @click.option("--images_no_background", default="images_no_background/", type=str)
  187. @click.option("--model_type", default="new", type=click.Choice(["new", "old"]))
  188. def remove_background(
  189. path_to_cropped_images_folder: str, images_no_background: str, model_type: str
  190. ) -> None:
  191. """
  192. Run background removal net.
  193. !pip install rembg
  194. @param path_to_cropped_images_folder: path to images with bg
  195. @param images_no_background: path to save processed images
  196. @return: None
  197. """
  198. print("start remove_background")
  199. os.makedirs(images_no_background, exist_ok=True)
  200. if model_type == "new":
  201. subprocess.run(
  202. [
  203. "rembg",
  204. "p",
  205. # "-a",
  206. # "-ae",
  207. # "7",
  208. path_to_cropped_images_folder,
  209. images_no_background,
  210. ]
  211. )
  212. else:
  213. segmentation(path_to_cropped_images_folder, images_no_background)
  214. if __name__ == "__main__":
  215. main()
Tip!

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

Comments

Loading...