opencv python 轮廓特征/凸包/外接矩形/外接圆/拟合矩形/拟合直线/拟合圆

Contour Features

1 图像的矩

`cv2.moments()`

``````import cv2
import numpy as np

ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print( M )

``````cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])``````

2轮廓面积

`cv2.contourArea(contour[, oriented])`

3轮廓周长

`cv2.arcLength(curve, closed)`

4轮廓近似

`cv2.approxPolyDP(curve, epsilon, closed[, approxCurve])`

``````import cv2
import numpy as np

cv2.imshow('src',img)
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[1]

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
cv2.polylines(img, [approx], True, (0, 0, 255), 2)

cv2.imshow('show',img)
cv2.waitKey()``````

5凸包

`convexHull(points[, hull[, clockwise[, returnPoints]]])`:检查曲线的凸性缺陷并进行修正.

• points:传入的轮廓
• hull：输出
• clockwise：方向标志，如果为True，则顺时针方向输出凸包.
• returnPoints：默认情况下为True，然后它返回hull points的坐标； 如果为False，则返回与hull points对应的轮廓点的索引

``````import cv2
import numpy as np

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[1]

hull = cv2.convexHull(cnt)``````

returnPoints = True，得到以下值:

``````array([[[192, 135]],
[[  9, 135]],
[[  9,  12]],
[[192,  12]]], dtype=int32)``````

``````array([[129],
[ 67],
[  0],
[142]], dtype=int32)
``````

``````cnt[129]

Out[3]: array([[192, 135]], dtype=int32)``````

6 检查凸性

`cv2.isContourConvex(contour)`:检查曲线是否凸起

7 外接矩形

7.1 直边外接矩形

`cv.boundingRect()`

``````import cv2
import numpy as np

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]

x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

cv2.imshow('show',img)
cv2.waitKey()``````

7.2 最小外接矩形

`cv.minAreaRect`返回一个Box2D结构，其中包含以下detals - （center（x，y），（width，height），rotation of rotation）
`cv.boxPoints`画上述矩形.

``````rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)``````

8 最小封闭圈

``````(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))

9 拟合椭圆

``````ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img,ellipse,(0,255,0),2)``````

10 拟合直线

``````rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv2.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)``````

76 声望
37 粉丝
0 条评论