jdfr glenn-jocher commited on
Commit
15e8c4c
1 Parent(s): db3bbdd

take EXIF orientation tags into account when fixing corrupt images (#5270)

Browse files

* take EXIF orientation tags into account when fixing corrupt images

* fit 120 char

* sort imports

* Update local exif_transpose comment

We have a local inplace version that is faster than the official as the image is not copied. AutoShape() uses this for Hub models, but here it is not important as the datasets.py usage is infrequent (AutoShape() it is applied every image).

* Update datasets.py

Co-authored-by: Glenn Jocher <[email protected]>

Files changed (1) hide show
  1. utils/datasets.py +3 -3
utils/datasets.py CHANGED
@@ -22,7 +22,7 @@ import numpy as np
22
  import torch
23
  import torch.nn.functional as F
24
  import yaml
25
- from PIL import Image, ExifTags
26
  from torch.utils.data import Dataset
27
  from tqdm import tqdm
28
 
@@ -69,7 +69,7 @@ def exif_size(img):
69
  def exif_transpose(image):
70
  """
71
  Transpose a PIL image accordingly if it has an EXIF Orientation tag.
72
- From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py
73
 
74
  :param image: The image to transpose.
75
  :return: An image.
@@ -896,7 +896,7 @@ def verify_image_label(args):
896
  with open(im_file, 'rb') as f:
897
  f.seek(-2, 2)
898
  if f.read() != b'\xff\xd9': # corrupt JPEG
899
- Image.open(im_file).save(im_file, format='JPEG', subsampling=0, quality=100) # re-save image
900
  msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
901
 
902
  # verify labels
 
22
  import torch
23
  import torch.nn.functional as F
24
  import yaml
25
+ from PIL import Image, ImageOps, ExifTags
26
  from torch.utils.data import Dataset
27
  from tqdm import tqdm
28
 
 
69
  def exif_transpose(image):
70
  """
71
  Transpose a PIL image accordingly if it has an EXIF Orientation tag.
72
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
73
 
74
  :param image: The image to transpose.
75
  :return: An image.
 
896
  with open(im_file, 'rb') as f:
897
  f.seek(-2, 2)
898
  if f.read() != b'\xff\xd9': # corrupt JPEG
899
+ ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
900
  msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
901
 
902
  # verify labels