From 7fb93f45403390c0fb0c0fce97b889f3e009c2fb Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Fri, 2 Jul 2021 12:13:38 +0200 Subject: [PATCH] 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 --- src/PIL/ImageOps.py | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py index 711a519fc..f210f0d32 100644 --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -568,27 +568,24 @@ def solarize(image, threshold=128): def exif_transpose(image): """ - If an image has an EXIF Orientation tag, return a new image that is - transposed accordingly. Otherwise, return a copy of the image. + Transpose an image accordingly if it has an EXIF Orientation tag :param image: The image to transpose. :return: An image. """ exif = image.getexif() orientation = exif.get(0x0112) - method = { - 2: Image.FLIP_LEFT_RIGHT, - 3: Image.ROTATE_180, - 4: Image.FLIP_TOP_BOTTOM, - 5: Image.TRANSPOSE, - 6: Image.ROTATE_270, - 7: Image.TRANSVERSE, - 8: Image.ROTATE_90, - }.get(orientation) - if method is not None: - transposed_image = image.transpose(method) - transposed_exif = transposed_image.getexif() - del transposed_exif[0x0112] - transposed_image.info["exif"] = transposed_exif.tobytes() - return transposed_image - return image.copy() + if orientation is not None: + method = {2: Image.FLIP_LEFT_RIGHT, + 3: Image.ROTATE_180, + 4: Image.FLIP_TOP_BOTTOM, + 5: Image.TRANSPOSE, + 6: Image.ROTATE_270, + 7: Image.TRANSVERSE, + 8: Image.ROTATE_90, + }.get(orientation) + if method is not None: + image = image.transpose(method) + del exif[0x0112] + image.info["exif"] = exif.tobytes() + return image