opencv 物體外形相似度匹配 cv.matchShapes函數使用


opencv中 cv.matchShapes() 可以檢測兩個形狀之間的相似度,返回值越小,越相似。先讀入下面這張圖片:
實驗用圖
進行實驗:

import numpy as np 
import cv2 as cv
img = cv.imread('shapes.jpg', 0)
_, thresh = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)

contours, hierarchy = cv.findContours(thresh, 3, 2)
img_color = cv.cvtColor(thresh, cv.COLOR_GRAY2BGR)  # 用於繪制的彩色圖

cnt_a, cnt_b, cnt_c = contours[0], contours[1], contours[2]
cv.drawContours(img_color,[cnt_a],0,[255,0,0],2)
cv.drawContours(img_color,[cnt_b],0,[0,255,0],2)
cv.drawContours(img_color,[cnt_c],0,[0,0,255],2)

# 參數3:匹配方法;參數4:opencv預留參數
print('b,b = ',cv.matchShapes(cnt_b, cnt_b, 1, 0.0))  # 0.0
print('b,c = ',cv.matchShapes(cnt_b, cnt_c, 1, 0.0))  # 2.17e-05
print('b,a = ',cv.matchShapes(cnt_b, cnt_a, 1, 0.0))  # 0.418

cv.imshow('result',img_color)
cv.waitKey(0)
cv.destroyAllWindows()

實驗結果:
代碼輸出結果
可以看到,b和自己匹配,返回值最小,為0。b和c匹配返回的數值遠小於b和a匹配的數值,表示c相對a來說,和b形狀更相似。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM