[英]How do I calculate the percentage of difference between two images using Python and OpenCV?
I am trying to write a program in Python (with OpenCV) that compares 2 images, shows the difference between them, and then informs the user of the percentage of difference between the images.我正在尝试用 Python(使用 OpenCV)编写一个程序来比较 2 张图像,显示它们之间的差异,然后通知用户图像之间的差异百分比。 I have already made it so it generates a .jpg showing the difference, but I can't figure out how to make it calculate a percentage.我已经做到了,所以它会生成一个 .jpg 来显示差异,但我不知道如何让它计算百分比。 Does anyone know how to do this?有谁知道如何做到这一点?
Thanks in advance.提前致谢。
Here is a simple idea you can adapt.这是一个您可以适应的简单想法。 But always ensure the images being compared are of the same shape.但始终确保被比较的图像具有相同的形状。
Code:代码:
img1 = cv2.imread('dog.jpg', 0)
img2 = cv2.imread('cat.jpg', 0)
#--- take the absolute difference of the images ---
res = cv2.absdiff(img1, img2)
#--- convert the result to integer type ---
res = res.astype(np.uint8)
#--- find percentage difference based on number of pixels that are not zero ---
percentage = (numpy.count_nonzero(res) * 100)/ res.size
img1
and img2
are similar most of the pixels in res
would be 0
resulting in a lower percentage.如果img1
和img2
相似,则res
大多数像素将为0
从而导致百分比较低。img1
and img2
are different this percentage would be higher.如果img1
和img2
不同,这个百分比会更高。Note: I have shown for a single channel image and the same can be extended for multi-channel images.注意:我已经展示了单通道图像,同样可以扩展到多通道图像。
You will need to calculate this on your own.您需要自行计算。 You will need the count of diferent pixels and the size of your original image then a simple math: (diferentPixelsCount / (mainImage.width * mainImage.height))*100
您将需要不同像素的数量和原始图像的大小,然后进行简单的数学运算: (diferentPixelsCount / (mainImage.width * mainImage.height))*100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.