For some reason
im_data = np.array(im.getdata()).reshape(im.size[0], im.size[1], 3)
p1 = im.getpixel((i, j))
p2 = im_data[i, j]
p1 and p2 are the same rgb values most of the time, except when they're not. Any idea why?
The reason is that numpy works column-based and PIL works row-based when converting one dimensional arrays to matrices or the other way around. This means that the getdata function places the pixel from position (1,0) to the second place in the array, and numpy places the second pixel in the array to position (0,1). Therefore, you need to change the order of the sizes in reshape, and to reverse i and j in your comparison. The code below shows that there are no differences then.
The reason that most of your pixels are equal is a coincidence and depends on your image. I tried it with a photo, and almost all pixels were different, except for the pixels on the diagonal.
import numpy as np
from PIL import Image
def reshape_img(img: Image):
img_data = np.array(img.getdata()).reshape(img.size[1], img.size[0], 3)
difference_found = False
for i in range(img.size[0]):
for j in range(img.size[1]):
get_pixel = img.getpixel((i, j))
data = img_data[j, i]
if any(get_pixel != data):
difference_found = True
msg = 'Difference in pixel {pixel}: img.getpixel={getpixel}, ' \
'img_data={data}'.format(pixel=(i, j), getpixel=get_pixel, data=data)
print(msg)
if not difference_found:
msg = 'The two images are identical'
print(msg)
if __name__ == '__main__':
ams = Image.open('amsterdam_small.jpg')
reshape_img(ams)

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