1 src = cv2.imread("***.jpg", cv2.IMREAD_COLOR) 2 gray = cv2.cvtColor(src ,cv2.COLOR_BGR2GRAY) 3 ret, binary = cv2.threshold(gray,100,255,cv2.THRESH_BINARY) 4 contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 5 cv2.drawContours(src,contours[32],-1,(0,0,255),1) 6 cv2.imshow("Src", src)
其中,threshold函數第2參數,肯定黑白分界點。除此以外,還有canny等方法,造成二值圖。函數
drawContours的輪廓參數,能夠是整個輪廓,也但是其中一個。spa
函數原型:索引
cv2.threshold(src, thresh, maxval, type[, dst]) → retval, dst原型
type:THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INVchannel
cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → contours, hierarchy方法
mode:CV_RETR_EXTERNAL, CV_RETR_LIST, CV_RETR_CCOMP, CV_RETR_TREEim
method:CV_CHAIN_APPROX_NONE, CV_CHAIN_APPROX_SIMPLE, CV_CHAIN_APPROX_TC89_L1, CV_CHAIN_APPROX_TC89_KCOS數據
contours:輪廓多邊形點羣數據img
hierarchy:co
? hierarchy[idx][0] 返回同等級層次結構的下一個輪廓索引
? hierarchy[idx][1] 返回同等級層次結構的上一個輪廓索引
? hierarchy[idx][2] 返回第一個子輪廓的索引
? hierarchy[idx][3] 返回父輪廓的索引
若是其中一個輪廓不存在,返回索引爲負值
cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) → None
(1)輪廓矩對比
1 cv2.matchShapes(contours1[0], contours2[0], cv2.cv.CV_CONTOURS_MATCH_I1, 0.0)
函數原型:
cv2.matchShapes(contour1, contour2, method, parameter) → retval
method:CV_CONTOURS_MATCH_I1, CV_CONTOURS_MATCH_I2, CV_CONTOURS_MATCH_I3
(2)輪廓hist對比
1 hist1 = cv2.calcHist(src1, [0], None, [256], [0, 256]) 2 hist2 = cv2.calcHist(src2, [0], None, [256], [0, 256]) 3 print cv2.compareHist(hist1, hist2, cv2.cv.CV_COMP_BHATTACHARYYA)
函數原型:
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) → hist
cv2.compareHist(H1, H2, method) → retval