Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PIL.ImageChops.difference and np.array difference have different results?

Why PIL.ImageChops.difference and np.array absolute difference have different results? Pillow document says ImageChops.difference acts just like absolute difference(https://pillow.readthedocs.io/en/3.1.x/reference/ImageChops.html).

tamp_image = Image.open(tamp_file_path).convert("RGB")
orig_image = Image.open(orig_file_path).convert("RGB")
diff = ImageChops.difference(orig_image, tamp_image)
diff.show() #1
Image.fromarray(abs(np.array(tamp_image)-np.array(orig_image))).show() #2

results(top:#1, bottom:#2):

PIL.Chops.difference np.array difference

Interestingly, if I convert diff to np.array and then Image object again, it shows like #1.

like image 555
Cauchy Avatar asked Jan 27 '26 22:01

Cauchy


1 Answers

I had a similar problem. The solution is quite simple, the converted numpy arrays have the datatype uint8. By subtracting large values, the bits will flip entirely, and you get some weird looking result.

So the solution is to convert the images to a datatype with an appropriate range, like int8.

img1 = np.array(tamp_image, dtype='int8')
img2 = np.array(orig_image, dtype='int8')
diff = np.abs(img1 - img2)
Image.fromarray(np.array(diff, dtype='uint8')).show()
like image 105
Josef Avatar answered Jan 30 '26 12:01

Josef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!