Ndarray can be displayed as image with plotly, but when I try to save it with PIL it gets corrupted

Viewed 32

The image has shape (224, 224, 3) and is generated by the LIME algorithm, if that is relevant...

I can display it in jupyter notebook with plotly imshow(),

enter image description here

but when I try to make it into a png (or jpg) with PIL Image.fromarray, it becomes corrupted somehow.

enter image description here

Here's the code, help much appreciated! :)

img_boundry = mark_boundaries(temp/255.0, mask)
print(img_boundry.shape)
# try to convert to image somehow
imgg = Image.fromarray(img_boundry, "RGB") # np.swapaxes(img_boundry, 0, 1)
imgg.save("TEST.png")
fig=px.imshow(img_boundry)
fig.show()
1 Answers

When you create an RGB PIL Image from a Numpy array, the array must have dtype=np.uint8 and values in range 0..255. See modes.

You can check the dtype, shape and min and max values like this:

print(f'shape: {im.shape}, dtype: {im.dtype}, min: {im.min()}, max: {im.max()}')

By contrast, plotly is probably happy to automagically scale floats if they are in the range 0..1.

Related