Applies the exif orientation correctly. This code exists per the bug: https://github.com/python-pillow/Pillow/issues/3973 with the function `ImageOps.exif_transpose`. The Pillow source raises errors with various methods, especially `tobytes` Function based on: http
(image)
| 116 | |
| 117 | |
| 118 | def _apply_exif_orientation(image): |
| 119 | """ |
| 120 | Applies the exif orientation correctly. |
| 121 | |
| 122 | This code exists per the bug: |
| 123 | https://github.com/python-pillow/Pillow/issues/3973 |
| 124 | with the function `ImageOps.exif_transpose`. The Pillow source raises errors with |
| 125 | various methods, especially `tobytes` |
| 126 | |
| 127 | Function based on: |
| 128 | https://github.com/wkentaro/labelme/blob/v4.5.4/labelme/utils/image.py#L59 |
| 129 | https://github.com/python-pillow/Pillow/blob/7.1.2/src/PIL/ImageOps.py#L527 |
| 130 | |
| 131 | Args: |
| 132 | image (PIL.Image): a PIL image |
| 133 | |
| 134 | Returns: |
| 135 | (PIL.Image): the PIL image with exif orientation applied, if applicable |
| 136 | """ |
| 137 | if not hasattr(image, "getexif"): |
| 138 | return image |
| 139 | |
| 140 | try: |
| 141 | exif = image.getexif() |
| 142 | except Exception: # https://github.com/facebookresearch/detectron2/issues/1885 |
| 143 | exif = None |
| 144 | |
| 145 | if exif is None: |
| 146 | return image |
| 147 | |
| 148 | orientation = exif.get(_EXIF_ORIENT) |
| 149 | |
| 150 | method = { |
| 151 | 2: Image.FLIP_LEFT_RIGHT, |
| 152 | 3: Image.ROTATE_180, |
| 153 | 4: Image.FLIP_TOP_BOTTOM, |
| 154 | 5: Image.TRANSPOSE, |
| 155 | 6: Image.ROTATE_270, |
| 156 | 7: Image.TRANSVERSE, |
| 157 | 8: Image.ROTATE_90, |
| 158 | }.get(orientation) |
| 159 | |
| 160 | if method is not None: |
| 161 | return image.transpose(method) |
| 162 | return image |
| 163 | |
| 164 | |
| 165 | def read_image(file_name, format=None): |