Remove image.copy() op from exif_transpose()

This version of the function avoids image copy and a dictionary build for the majority use case of missing exif tags / no action needed on call.

As implemented in YOLOv5 in https://github.com/ultralytics/yolov5/pull/3852
This commit is contained in:
Glenn Jocher 2021-07-02 12:13:38 +02:00 committed by GitHub
parent 53ce23c749
commit 7fb93f4540
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -568,27 +568,24 @@ def solarize(image, threshold=128):
def exif_transpose(image): def exif_transpose(image):
""" """
If an image has an EXIF Orientation tag, return a new image that is Transpose an image accordingly if it has an EXIF Orientation tag
transposed accordingly. Otherwise, return a copy of the image.
:param image: The image to transpose. :param image: The image to transpose.
:return: An image. :return: An image.
""" """
exif = image.getexif() exif = image.getexif()
orientation = exif.get(0x0112) orientation = exif.get(0x0112)
method = { if orientation is not None:
2: Image.FLIP_LEFT_RIGHT, method = {2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180, 3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM, 4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE, 5: Image.TRANSPOSE,
6: Image.ROTATE_270, 6: Image.ROTATE_270,
7: Image.TRANSVERSE, 7: Image.TRANSVERSE,
8: Image.ROTATE_90, 8: Image.ROTATE_90,
}.get(orientation) }.get(orientation)
if method is not None: if method is not None:
transposed_image = image.transpose(method) image = image.transpose(method)
transposed_exif = transposed_image.getexif() del exif[0x0112]
del transposed_exif[0x0112] image.info["exif"] = exif.tobytes()
transposed_image.info["exif"] = transposed_exif.tobytes() return image
return transposed_image
return image.copy()