opencv 輪廓 缺陷檢測
阿新 • • 發佈:2018-12-15
1.凸性缺陷
物體與凸殼任何偏差都可以認為是凸性缺陷。
cv.convexityDefects()
import cv2 as cv import numpy as np img = cv.imread('star.jpg') img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) ret,thresh = cv.threshold(img_gray, 127, 255,0) im2,contours,hierarchy = cv.findContours(thresh,2,1) cnt = contours[0] hull = cv.convexHull(cnt,returnPoints = False) defects = cv.convexityDefects(cnt,hull) for i in range(defects.shape[0]): s,e,f,d = defects[i,0] start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) cv.line(img,start,end,[0,255,0],2) cv.circle(img,far,5,[0,0,255],-1) cv.imshow('img',img) cv.waitKey(0) cv.destroyAllWindows()
2.多邊形點測試
dist = cv.pointPolygonTest(cnt,(50,50),True)
3.形狀匹配
cv.matchShapes()
import cv2 as cv import numpy as np img1 = cv.imread('star.jpg',0) img2 = cv.imread('star2.jpg',0) ret, thresh = cv.threshold(img1, 127, 255,0) ret, thresh2 = cv.threshold(img2, 127, 255,0) im2,contours,hierarchy = cv.findContours(thresh,2,1) cnt1 = contours[0] im2,contours,hierarchy = cv.findContours(thresh2,2,1) cnt2 = contours[0] ret = cv.matchShapes(cnt1,cnt2,1,0.0) print( ret )