opencv轮廓提取、轮廓识别相关要点

1、轮廓提取

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的轮廓参数,可以是整个轮廓,也可是其中一个。

函数原型:

cv2.threshold(src, thresh, maxval, type[, dst]) → retval, dst

type:THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → contours, hierarchy

mode:CV_RETR_EXTERNALCV_RETR_LIST, CV_RETR_CCOMP, CV_RETR_TREE

method:CV_CHAIN_APPROX_NONE, CV_CHAIN_APPROX_SIMPLE, CV_CHAIN_APPROX_TC89_L1, CV_CHAIN_APPROX_TC89_KCOS

contours:轮廓多边形点群数据

hierarchy:

? hierarchy[idx][0] 返回同等级层次结构的下一个轮廓索引
? hierarchy[idx][1] 返回同等级层次结构的上一个轮廓索引
? hierarchy[idx][2] 返回第一个子轮廓的索引
? hierarchy[idx][3] 返回父轮廓的索引
如果其中一个轮廓不存在,返回索引为负值

cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) → None

2、轮廓对比

(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

posted @ 2015-10-11 13:31  lulu47  阅读(7012)  评论(0编辑  收藏  举报