简体   繁体   中英

Is it possible for two images to have the same pixel values but still be different?

I'm working on a Python project where I encrypt and decrypt an image. However, every time I run it, the decrypted image is different from the original although it has the same pixel values.

My code

img = Image.open(path)
pixel_values =np.asarray(img)
img2 = Image.open("decrypted.png")
pixel_values_2 =np.asarray(img2)
print(pixel_values_2==pixel_values)

gives an output of:

[[ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 ...
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]]

Does anyone know what I might be missing here or if I haven't considered something?

Original image:

原来的

Decrypted image:

解密

The linked, original image has mode P , thus is a palettised image. So, it seems that the actual values in the original image (not mapped to the palette) are the same as in the "decrypted" image. (What does your encryption and decryption actually do?) Thus, the compared NumPy arrays are identical. If you convert the original image to mode L (grayscale), the resulting NumPy arrays are different, cf. the following code:

import numpy as np
from PIL import Image

img = Image.open('original.png')
img2 = Image.open('decrypted.png')

print('Mode original:', img.mode)
print('Mode decrypted:', img2.mode)

print(np.all(np.array(img) == np.array(img2)))

img = img.convert('L')

print(np.all(np.array(img) == np.array(img2)))

That'd be the output:

Mode original: P
Mode decrypted: L
True
False

So, the actual question is, what is the expected behaviour within the scope of your encryption/decryption? Are you aware of the mode P in the original image?

As a side note: When opening both images using OpenCV, for example, the resulting NumPy arrays are different from the beginning, since OpenCV can't handle palettised images.

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
NumPy:         1.20.1
Pillow:        8.1.0
----------------------------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM