Loading...

How keras.preprocessing.image.array_to_img work


I am using keras.preprocessing.image.array_to_img to convert array data (representative of an image) to an image. Then when I use .save(), I notice that the data got transformed.

I have no idea why.

Thus I created a simple example and it turns out that array_to_img() really does something unexpected, or I am missing something:


from keras.preprocessing.image import image
import matplotlib.pyplot as plt
import numpy as np

array1=np.array([[[255,0,0],[100,0,0]],
               [[0,0,0],[0,0,0]]])
plt.imshow(array1)
plt.show()

img_4=image.array_to_img()
img_4.save('img_4.jpg')

img_4load = image.load_img('img_4.jpg', target_size=(2, 2))
img_4load_array = image.img_to_array(img_4load)
print(img_4load_array)

Results:

[[[117.  39.  39.]
  [ 97.  19.  19.]]

 [[ 65.   0.   0.]
  [ 55.   0.   0.]]]

My array data has been changed!!

Why does this happen and how can I avoid this?

- - Source

Answers

answered 1 week ago Hemerson Tacon #1

The jpeg is a format which is compressed. This means that when you save an image with this format it will be passed by a compaction process with loss or simply compression. The purpose of this is to save storage space. With a real image and within a certain range of loss, our eyes are not able to distinguish the difference between the real image and the compressed one. Since your image is very small the modifications were huge. To keep the values unaltered, save the image in a format that does not compress the image, for instance, the png format. You just need to change the extension when saving:

img_4.save('img_4.png')

You can see here the available image formats in PIL module and you can read more about image compression here

comments powered by Disqus