Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transpose images with EXIF Orientation tag #6739

Merged
merged 1 commit into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/datasets/features/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ def decode_example(self, value: dict, token_per_repo_id=None) -> "PIL.Image.Imag

if config.PIL_AVAILABLE:
import PIL.Image
import PIL.ImageOps
else:
raise ImportError("To support decoding images, please install 'Pillow'.")

Expand Down Expand Up @@ -186,6 +187,8 @@ def decode_example(self, value: dict, token_per_repo_id=None) -> "PIL.Image.Imag
else:
image = PIL.Image.open(BytesIO(bytes_))
image.load() # to avoid "Too many open files" errors
if image.getexif().get(PIL.Image.ExifTags.Base.Orientation) is not None:
image = PIL.ImageOps.exif_transpose(image)
if self.mode and self.mode != image.mode:
image = image.convert(self.mode)
return image
Expand Down
19 changes: 19 additions & 0 deletions tests/features/test_image.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import tarfile
import warnings
from io import BytesIO

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -90,6 +91,24 @@ def test_image_decode_example(shared_datadir):
Image(decode=False).decode_example(image_path)


@require_pil
def test_image_decode_example_with_exif_orientation_tag(shared_datadir):
import PIL.Image

image_path = str(shared_datadir / "test_image_rgb.jpg")
buffer = BytesIO()
exif = PIL.Image.Exif()
exif[PIL.Image.ExifTags.Base.Orientation] = 8 # rotate the image for 90°
PIL.Image.open(image_path).save(buffer, format="JPEG", exif=exif.tobytes())
image = Image()

decoded_example = image.decode_example({"path": None, "bytes": buffer.getvalue()})

assert isinstance(decoded_example, PIL.Image.Image)
assert decoded_example.size == (480, 640) # rotated
assert decoded_example.mode == "RGB"


@require_pil
def test_image_change_mode(shared_datadir):
import PIL.Image
Expand Down
Loading