Home > database >  Different images in Image.show() and Image.save() in PIL
Different images in Image.show() and Image.save() in PIL

Time:08-15

I generate a PIL image from a NumPy array. The image showed by show function differs from what is saved by the save function directly called after show. Why might that be the case? How can I solve this issue? I use TIFF file format. Viewing both images in Windows Photos App.

from PIL import Image
import numpy as np

orig_img = Image.open('img.tif'))
dent = Image.open('mask.tif')

img_np = np.asarray(orig_img)
dent_np = np.asarray(dent)

dented = img_np*0.5   dent_np*0.5

im = Image.fromarray(dented)
im.show('dented')
im.save("dented_2.tif", "TIFF")

Edit: I figured out that the save function saves correctly if the values for pixel in the NumPy array called 'dented' are normalized to 0,1 range. However then show function shows the image completely black.

CodePudding user response:

I suspect the problem is related to the dtype of your variable dented. Try:

print(img_np.dtype, dented.dtype)

As a possible solution, you could use:

im = Image.fromarray(dented.astype(np.uint8))

You don't actually need to go to Numpy to do the maths and then convert back if you want the mean of two images, because you can do that with PIL.

from PIL import ImageChops

mean = ImageChops.add(imA, imB, scale=2.0)
  • Related