参考文档: https://docs.opencv.org/3.4/dd/d49/tutorial_py_contour_features.html
函数原型
image, contours, hierarchy = cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])
参数:
返回值:
# 实例
img = cv2.imread('1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
_, contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
函数原型
cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])
参数:
# 实例
cv2.drawContours(img,contours,-1,(0,0,255),3)
cv2.imshow("img", img)
cv2.waitKey(0)
函数原型:
cv2.moments(array[, binaryImage])
实例:
import numpy as np
import cv2
img = cv2.imread('star.jpg',0)
ret, thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
M = cv2.moments(cnt)
# 计算x,y轴的矩
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
函数原型:
cv2.contourArea(contour[, oriented])
实例:
area = cv2.contourArea(cnt)
函数原型:
cv2.arcLength(curve, closed)
实例:
perimeter = cv2.arcLength(cnt, True)
函数原型:
cv2.isContourConvex(contour)
实例:
k = cv2.isContourConvex(cnt)
函数原型:
cv2.approxPolyDP(curve, epsilon, closed[, approxCurve])
实例:
epsilon = 0.1*cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
函数原型:
cv2.convexHull(points[, hull[, clockwise[, returnPoints]]])
实例:
hull = cv2.convexHull(cnt)
函数原型:
# 普通矩形
cv2.boundingRect(points) # 1
# 可旋转矩形,即最小的外包矩形
cv2.minAreaRect(points) # 2
# 矩形表达形式的装换
cv2.boxPoints(box) # 3
实例:
# 普通矩形
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
# 可旋转矩形,即最小的外包矩形
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
# 最小外接圆
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
cv2.circle(img,center,radius,(0,255,0),2)
# 最小外接椭圆
ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img,ellipse,(0,255,0),2)
# 拟合直线
rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)