簡體   English   中英

如何使用 Python 和 OpenCV 計算兩個圖像之間的差異百分比?

[英]How do I calculate the percentage of difference between two images using Python and OpenCV?

我正在嘗試用 Python(使用 OpenCV)編寫一個程序來比較 2 張圖像,顯示它們之間的差異,然后通知用戶圖像之間的差異百分比。 我已經做到了,所以它會生成一個 .jpg 來顯示差異,但我不知道如何讓它計算百分比。 有誰知道如何做到這一點?

提前致謝。

這是一個您可以適應的簡單想法。 但始終確保被比較的圖像具有相同的形狀。

代碼:

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
  • 如果img1img2相似,則res大多數像素將為0從而導致百分比較低。
  • 如果img1img2不同,這個百分比會更高。

注意:我已經展示了單通道圖像,同樣可以擴展到多通道圖像。

您需要自行計算。 您將需要不同像素的數量和原始圖像的大小,然后進行簡單的數學運算: (diferentPixelsCount / (mainImage.width * mainImage.height))*100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM