temp
temp

Reputation: 45

Image to numpy array to Image and finally again to array resulting in wrong array

I converted an image to numpy array using:

arr = np.array(PIL.Image.open('1.jpg'))

Then I modified part of the array:

arr[0][0][0] = 128

and converted the array back to an image:

img = PIL.Image.fromarray(np.uint8(arr))
im.save('2.jpg')

Then, I converted the 2.jpg image into numpy array and checked value of arr:

arr = np.array(PIL.Image.open('2.jpg'))
print(arr)

I am getting a completely different array than I got before. Why is this happening?

Upvotes: 4

Views: 1742

Answers (3)

Steve Barnes
Steve Barnes

Reputation: 28370

The reason that your arrays don't match is that you are storing the image as JPEG and this is a lossy format - the two images are visually identical but have been compressed.

If you save your image as a bitmap then load it into an array, they will be identical.

Upvotes: 1

seralouk
seralouk

Reputation: 33147

The way you save the image affects the results. The jpg compresses the image and alters the values.

About the image formats see here: http://pillow.readthedocs.io/en/3.1.x/handbook/image-file-formats.html

Use this:

arr = np.array(PIL.Image.open('1.jpg')
arr[0][0][0] = 128

img = PIL.Image.fromarray(np.uint8(arr))
im.save('2.bmp')

arr2 = np.array(PIL.Image.open('2.bmp'))
print(arr)
print(arr2)

This works fine.

Upvotes: 2

Kei Minagawa
Kei Minagawa

Reputation: 4501

Because .jpg is not lossless image format. If you want to save image as is, save as lossless image format like bmp, tiff, etc.

Upvotes: 2

Related Questions