An acquaintance said that I needed a program to compare the differences between images, so I built it with Python and OpenCV. The point is to search for mistakes using OpenCV, but ** the condition is that there is no discrepancy between the images **, so it may not be suitable for practical use. If you need a more robust spot the difference, you may want to refer to this article. I think the implementation is about 10 times lighter than the method in this article ...
The following image is output.
(The image is Wikipedia Quoted from)
import cv2
import matplotlib.pyplot as plt
img1 = cv2.imread('img1.png')
img1 = cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)
img1 = img1/255
img2 = cv2.imread('img2.png')
img2 = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
img2 = img2/255
dif = cv2.absdiff(img1,img2)
dif[dif>0] = 1
fig,axs = plt.subplots(2,2)
ar = axs.ravel()
ar[0].imshow(img1)
ar[1].imshow(img2)
ar[2].imshow(img1*dif*0.8 + img1*0.2)
ar[3].imshow(img2*dif*0.8 + img2*0.2)
plt.show()
The essential processing is only a few lines by OpenCV, but the preprocessing for displaying with matplotlib takes quite a few lines. The point is that you can get a difference image with cv2.absdiff
, so I use it as a mask. If diff is left as it is, the difference is taken for each RGB channel, so it is masked by the operation dif [dif> 0] = 1
.
The point that took more time than I expected is that the image data of OpenCV can take both ʻinttype and
floattype, which is usually convenient, but this time the mask did not work well. As a result, when the image is read, it is
/ 255 and forcibly cast to
float`.
Recommended Posts