contours, hierarchy = cv2.findContours(image,mode,method)
cv2.RETR_EXTERNAL只检测外轮廓
cv2.RETR_LIST检测的轮廓不建立等级关系
cv2.RETR_CCOMP建立两个等级的轮廓,上一层为外边界,内层为内孔的边界。如果内孔内还有连通物体,则这个物体的边界也在顶层
cv2.RETR_TREE建立一个等级树结构的轮廓。
cv2.CHAIN_APPROX_NOME存储所有的轮廓点,相邻的两个点的像素位置差不超过1;cv2.CHAIN_APPROX_SIMPLE压缩水平方向、垂直方向、对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需要4个点来保存轮廓信息;cv2.CHAIN_APPROX_TC89_L1,cv2.CV_CHAIN_APPROX_TC89_KCOS
cv2.drawContours(image, contours, contourIdx, color, thickness=None, lineType=None, hierarchy=None, maxLevel=None, offset=None)
三、外接矩形
rect = cv2.minAreaRect(contours)
points = cv2.boxPoints(rect)
points = np.int0(points)
image = cv2.drawContours(original, [points], 0, (0, 0, 255), 2)
img = cv2.imread('图片位置')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
binary, contours, hierarchy = cv2.findContours(thresh, cv2RETR_TREE,cv2.CHAIN_APPROX_NONE)
cut = contours[0]
cv2.contourArea(cnt) #面积
cv2.arcLength(cnt,True) #周长,Ture表示闭合
epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True) #轮廓近似
x,y,w,h = cv2.bonudingRect(cnt)
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) #外接矩形
area = cv2.contourArea(cnt)
x,y,w,h = cv2.bonudingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area #轮廓面积与边界矩形比