'How to get difference of two images using cv2 in a format that it can be reapplied later?
I am looking to get the difference between img1 and img2 using cv2 in python, in a way that I can reapply the difference to img1.
Essentially: Difference = img2 - img1
In a format where I can later declare: img2 = img1 + difference
I am well aware of the cv2 functions absdiff, subtract and add. However I have not managed to extract the diff in a format that would allow addition later on.
Any help is much appreciated.
P.S. In case anybody is wondering why? The difference would be sent over socket and reapplied to img1 which was sent or constructed prior.
Solution 1:[1]
Original image use dtype uint8 with values 0..255 but when you substract then you can get values -255..255 (0-255)..(255-0) and it needs to convert to int16
import cv2
img1 = cv2.imread('lenna.png')
print('img1:', img1.shape, img1.dtype)
img2 = cv2.imread('lenna_flip.png')
print('img2:', img2.shape, img2.dtype)
diff = img2.astype('int16') - img1.astype('int16')
print('diff:', diff.shape, diff.dtype)
cv2.imshow('diff', diff)
cv2.waitKey(0)
back = (img1.astype('int16') + diff).astype('uint8')
print('back:', back.shape, back.dtype)
cv2.imshow('back', back)
cv2.waitKey(0)
cv2.destroyAllWindows()
back gives correct image but diff gives gray image (because it has values -255...255 which it converts to 0..255 when it displays) so it is useless to display it.
But now you have to send array diff with int16 so it may need to send more bytes then using original image and maybe it would be faster to send original image.
Image Lenna from Wikipedia
lenna.png
lenna_flip.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | furas |


