Skip to content

Commit 565eb47

Browse files
marcenacpThe TensorFlow Datasets Authors
authored andcommitted
Allows truncated images in PIL.
PiperOrigin-RevId: 684820302
1 parent 960a2df commit 565eb47

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

tensorflow_datasets/core/utils/image_utils.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from __future__ import annotations
2121

2222
import csv
23+
import functools
2324
import subprocess
2425
from typing import Any, List, Optional
2526

@@ -34,6 +35,21 @@
3435
THUMBNAIL_SIZE = 128
3536

3637

38+
@functools.cache
39+
def _allow_pil_to_load_truncated_images():
40+
"""Allows truncated images.
41+
42+
The function is cached to be called only once. Activating this flag solves
43+
issues where the image cannot be converted to RGB.
44+
"""
45+
try:
46+
from PIL import ImageFile # pylint: disable=g-import-not-at-top
47+
48+
ImageFile.LOAD_TRUNCATED_IMAGES = True
49+
except ImportError:
50+
pass
51+
52+
3753
@py_utils.memoize()
3854
def _get_runner():
3955
return tf_utils.TFGraphRunner()
@@ -148,6 +164,7 @@ def _postprocess_noop(img: PilImage) -> PilImage:
148164

149165

150166
def _postprocess_convert_rgb(img: PilImage) -> PilImage:
167+
_allow_pil_to_load_truncated_images()
151168
return img.convert('RGB')
152169

153170

0 commit comments

Comments
 (0)