I'm trying to read and write tiff-images with the PIL library. While testing, I noticed that saving the seemingly same numpy array generated in different ways leads to different images on disk. Why is this and how can I fix it?
For testing purposes, I created an image with GIMP (upscaled from 8x8) which I saved as TIF, read to a numpy array and wrote back to a tif file:
img_gimp = Image.open('img_gimp.tif')
imgarray_gimp = np.array(img_gimp)
img_gimp = Image.fromarray(imgarray_gimp, mode = 'I;16')
img_gimp.save('final_gimp.tif')
The result is as expected, it is the same image as the original. So far so good.
Now I generated the same image directly in python code:
imgarray_direct = np.zeros(shape = (8, 8)).astype(int)
for i in range(2):
for j in range(2):
image[i][j] = 65535
Writing this array to disk...
img_direct = Image.fromarray(imgarray_direct, mode = 'I;16')
img_direct.save('final_direct.tif')
doesn't give me the expected result, instead I find this: image generated by for loop (upscaled from 8x8)
Doing
print(np.array_equal(imgarray_gimp, imgarray_direct))
gives True, and looking at print(imgarray_gimp) and print(imgarray_direct), one cannot see any difference.
Is this intended behaviour? If yes, whats the reason for it?
Thank you for your answers!
As @MarkSetchell hinted in the comments, the issue is that your dtype for the numpy array of raw data does not match the PIL image mode string you are supplying afterwards. Changing the parameter passed into astype or simply passing in the right type on array creation fixed this issue for me. Here is what the modified code looks like:
import numpy as np
from PIL import Image
#Generate raw image data (16-bit!)
image_data = np.zeros(shape = (8, 8), dtype=np.uint16)#this is the big change
for i in range(2):
for j in range(2):
image_data[i][j] = 65535
#Save image as TIF to disk
image_direct = Image.fromarray(image_data, mode = 'I;16')
image_direct.save('final_direct.tif')
As a side note, I am surprised that the mode string I;16 you have used is valid; I could not find any mention about it in pillow's documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With