Skip to content

Commit 0011213

Browse files
author
The TensorFlow Datasets Authors
committed
Fix PIL image conversion for uint16 multi-channel arrays.
PiperOrigin-RevId: 911782033
1 parent 1dac9e9 commit 0011213

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

tensorflow_datasets/core/utils/image_utils.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,16 +177,25 @@ def create_thumbnail(
177177
if use_colormap: # Apply the colormap first as it modify the shape/dtype
178178
ex = apply_colormap(ex)
179179

180-
_, _, c = ex.shape
180+
c = ex.shape[-1] if ex.ndim == 3 else 1
181181
postprocess = _postprocess_noop
182182
if c == 1:
183183
ex = ex.squeeze(axis=-1)
184-
mode = 'L'
184+
if ex.dtype == np.uint16:
185+
mode = 'I;16'
186+
postprocess = _postprocess_convert_rgb
187+
else:
188+
mode = 'L'
185189
elif ex.dtype == np.uint16:
186-
mode = 'I;16'
190+
# PIL.Image.fromarray doesn't support uint16 for >1 channels.
191+
# https://github.com/python-pillow/Pillow/blob/11.0.0/src/PIL/Image.py#L3225
192+
# Scale to 8-bit for visualization.
193+
ex = (ex / 257).astype(np.uint8)
194+
mode = None
187195
postprocess = _postprocess_convert_rgb
188196
else:
189197
mode = None
198+
postprocess = _postprocess_convert_rgb
190199
img = PIL_Image.fromarray(ex, mode=mode)
191200
img = postprocess(img)
192201
if default_dimensions:

0 commit comments

Comments
 (0)