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 | class Image:
"""A class representing an image.
Attributes:
_path (Path): The path to the image file.
_value_array (np.ndarray): Numpy array containing pixel values. If available, it can be accessed with `Image.value`.
_width (int): The width of the image in pixels.
_height (int): The height of the image in pixels.
_exif_data (dict): The EXIF metadata of the image, if available.
_date_time (datetime): The date and time the image was taken, if available.
"""
def __init__(self, path: Union[str, Path]) -> None:
"""
__init__ Create Image object as a lazy loader for image data
Args:
path (Union[str, Path]): path to the image
"""
self._path = Path(path)
if not self._path.exists():
raise FileNotFoundError(f"Invalid input path. Image {self._path} not found.")
self._value_array = None
self._width = None
self._height = None
self._exif_data = None
self._date_time = None
self.read_exif()
def __repr__(self) -> str:
"""Returns a string representation of the image"""
return f"Image {self._path}"
@property
def height(self) -> int:
"""Returns the height of the image"""
if self._height:
return int(self._height)
else:
logger.error("Image height not available. Read it from exif first")
return None
@property
def width(self) -> int:
"""Returns the width of the image"""
if self._width:
return int(self._width)
else:
logger.error("Image width not available. Read it from exif first")
return None
@property
def name(self) -> str:
"""Returns the name of the image (including extension)"""
return self._path.name
@property
def stem(self) -> str:
"""Returns the name of the image (excluding extension)"""
return self._path.stem
@property
def path(self) -> str:
"""Path of the image"""
return self._path
@property
def parent(self) -> str:
"""Path to the parent folder of the image"""
return self._path.parent
@property
def extension(self) -> str:
"""Returns the extension of the image"""
return self._path.suffix
@property
def exif(self) -> dict:
"""
exif Returns the exif of the image
Returns:
dict: Dictionary containing Exif information
"""
return self._exif_data
@property
def date(self) -> str:
"""
Returns the date and time of the image in a string format.
Returns:
str: The date and time of the image.
"""
if self._date_time is not None:
return self._date_time.strftime(DATE_FMT)
else:
logger.error("No exif data available.")
return
@property
def time(self) -> str:
"""
time Returns the time of the image from exif as a string
"""
if self._date_time is not None:
return self._date_time.strftime(TIME_FMT)
else:
logger.error("No exif data available.")
return None
@property
def datetime(self) -> datetime:
"""
Returns the date and time of the image as datetime object.
Returns:
datetime: The date and time of the image as datetime object
"""
if self._date_time is not None:
return self._date_time
else:
logger.error("No exif data available.")
return
@property
def timestamp(self) -> str:
"""
Returns the date and time of the image in a string format.
Returns:
str: The date and time of the image as datetime object
"""
if self._date_time is not None:
return self._date_time.strftime(DATETIME_FMT)
else:
logger.error("No exif data available.")
return
@property
def value(self) -> np.ndarray:
"""
Returns the image (pixel values) as numpy array
"""
if self._value_array is not None:
return self._value_array
else:
return self.read_image(self._path)
def read_image(
self,
# path: Union[str, Path],
col: bool = True,
resize: List[int] = [-1],
crop: List[int] = None,
) -> np.ndarray:
"""Wrapper around the function read_image to be a class method."""
# path = Path(path)
if self.path.exists():
self._value_array = read_image(self.path, col, resize, crop)
self.read_exif()
return self._value_array
else:
logger.error(f"Input paht {self.path} not valid.")
return None
def reset_image(self) -> None:
self._value_array = None
def read_exif(self) -> None:
"""Read image exif with exifread and store them in a dictionary"""
try:
with open(self._path, "rb") as f:
self._exif_data = exifread.process_file(f, details=False, debug=False)
except OSError:
logger.error("No exif data available.")
# Get image size
if (
"Image ImageWidth" in self._exif_data.keys()
and "Image ImageLength" in self._exif_data.keys()
):
self._width = self._exif_data["Image ImageWidth"].printable
self._height = self._exif_data["Image ImageLength"].printable
elif (
"EXIF ExifImageWidth" in self._exif_data.keys()
and "EXIF ExifImageLength" in self._exif_data.keys()
):
self._width = self._exif_data["EXIF ExifImageWidth"].printable
self._height = self._exif_data["EXIF ExifImageLength"].printable
else:
logger.error(
"Image width and height found in exif. Try to load the image and get image size from numpy array"
)
try:
img = Image(self.path)
self.height, self.width = img.height, img.width
except OSError:
raise RuntimeError("Unable to get image dimensions.")
# Get Image Date and Time
self._date_time_fmt = "%Y:%m:%d %H:%M:%S"
if "Image DateTime" in self._exif_data.keys():
date_str = self._exif_data["Image DateTime"].printable
elif "EXIF DateTimeOriginal" in self._exif_data.keys():
date_str = self._exif_data["EXIF DateTimeOriginal"].printable
else:
logger.error("Date not available in exif.")
return
self._date_time = datetime.strptime(date_str, self._date_time_fmt)
def extract_patch(self, limits: List[int]) -> np.ndarray:
"""Extract image patch
Parameters
__________
- limits (List[int]): List containing the bounding box coordinates as: [xmin, ymin, xmax, ymax]
__________
Return: patch (np.ndarray)
"""
image = read_image(self._path)
patch = image[
limits[1] : limits[3],
limits[0] : limits[2],
]
return patch
def get_intrinsics_from_exif(self) -> np.ndarray:
"""Constructs the camera intrinsics from exif tag.
Equation: focal_px=max(w_px,h_px)*focal_mm / ccdw_mm
Note:
References for this functions can be found:
* https://github.com/colmap/colmap/blob/e3948b2098b73ae080b97901c3a1f9065b976a45/src/util/bitmap.cc#L282
* https://openmvg.readthedocs.io/en/latest/software/SfM/SfMInit_ImageListing/
* https://photo.stackexchange.com/questions/40865/how-can-i-get-the-image-sensor-dimensions-in-mm-to-get-circle-of-confusion-from # noqa: E501
Returns:
K (np.ndarray): intrinsics matrix (3x3 numpy array).
"""
if self._exif_data is None or len(self._exif_data) == 0:
try:
self.read_exif()
except OSError:
logger.error("Unable to read exif data.")
return None
try:
focal_length_mm = float(self._exif_data["EXIF FocalLength"].printable)
except OSError:
logger.error("Focal length non found in exif data.")
return None
try:
sensor_width_db = SensorWidthDatabase()
sensor_width_mm = sensor_width_db.lookup(
self._exif_data["Image Make"].printable,
self._exif_data["Image Model"].printable,
)
except OSError:
logger.error("Unable to get sensor size in mm from sensor database")
return None
img_w_px = self.width
img_h_px = self.height
focal_length_px = max(img_h_px, img_w_px) * focal_length_mm / sensor_width_mm
center_x = img_w_px / 2
center_y = img_h_px / 2
K = np.array(
[
[focal_length_px, 0.0, center_x],
[0.0, focal_length_px, center_y],
[0.0, 0.0, 1.0],
],
dtype=float,
)
return K
def undistort_image(self, camera: Camera, out_path: str = None) -> np.ndarray:
"""
undistort_image Wrapper around undistort_image function icepy4d.sfm.geometry module
Args:
camera (Camera): Camera object containing K and dist arrays.
out_path (str, optional): Path for writing the undistorted image to disk. If out_path is None, undistorted image is not saved to disk. Defaults to None.
Returns:
np.ndarray: undistored image
"""
self.read_image()
und_imge = cv2.undistort(
cv2.cvtColor(self._value_array, cv2.COLOR_RGB2BGR),
camera.K,
camera.dist,
None,
camera.K,
)
if out_path is not None:
cv2.imwrite(out_path, und_imge)
return und_imge
|