- 凸缺陷,以及如何找到凸缺陷
- 找某一點到一個多邊形的最短距離
- 不同形狀的匹配
1.凸缺陷
前面已經設計了輪廓的凸包和凸性缺陷的概念。OpenCV中有一個函數cv2.convexityDefect()可以幫助我們找到凸缺陷:
hull = cv2.convexHull(cnt,returnPoints=False)#這里必須是False
defect = cv2.convexityDefects(cnt,hull)
它會返回一個數組,每一行的值為[起點,終點,最遠的點,到最遠點的近似距離]。我們可以在一張圖上顯示它。我們將起點和終點用一天綠線連接,在最遠點畫一個圓圈。記住返回的前三個值是點在輪廓中的索引,所以要到輪廓中去找到它們:
# -*- coding:utf-8 -*-
import numpy as np
import cv2
from matplotlib import pyplot as plt
im = cv2.imread('10.png')
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)#用這個方式轉換的原因是最后輸出時希望能看到彩色的的輪廓圖
ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(thresh,1,2)
cnt = contours[0]
hull = cv2.convexHull(cnt,returnPoints=False)#這里必須是False
defect = cv2.convexityDefects(cnt,hull)
#它的輸出包含很多項,可以嘗試輸出一下便可以知道該list的排列格式
for i in range(defect.shape[0]):
s,e,f,d = defect[i,0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv2.line(im,start,end,[0,255,0],2)
cv2.circle(im,far,5,[0,0,255],-1)
cv2.imshow('img',im)
cv2.waitKey(0)
2.Point Polygon Test
求解圖像中的一個點到一個對象的輪廓的最短距離。如果點在輪廓外部,返回值為負。如果在輪廓上,返回值為0,。如果在輪廓外部,返回值為正。例子如下
dist = cv2.pointPolygonTest(cnt,(50,50),True)
其中第三個參數是measureDist。如果設為True,會返回最短距離;如果設為False,則只會判斷這個點和輪廓之間的位置關系(返回+1,-1,0).
如果實際運轉中不需要知道最短距離,建議設為False,這樣可以使速度提升2到3倍。
3.形狀匹配
cv2.matchShape()可以幫我們比較兩個形狀或輪廓的相似度。如果返回值越小,則匹配越好。它是根據Hull矩來確定的。
# -*- coding:utf-8 -*-
import numpy as np
import cv2
from matplotlib import pyplot as plt
im = cv2.imread('10.png')
im2 = cv2.imread('11.png')
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)#用這個方式轉換的原因是最后輸出時希望能看到彩色的的輪廓圖
img2 = cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(img,127,255,0)
ret,thresh2 = cv2.threshold(img2,127,255,0)
img,contours,hierarchy = cv2.findContours(thresh,1,2)
cnt = contours[0]
img2,contours,hierarchy = cv2.findContours(thresh2,1,2)
cnt2 = contours[0]
ret = cv2.matchShapes(cnt,cnt2,1,0.0)#后面的兩個參數有啥用暫時不知道
print(ret)
根據測試,該匹配對於某些變化如縮放,旋轉,鏡像映射都具有較好的匹配效果