Python-OpenCVノート6--輪郭(Contours)
5523 ワード
Python-OpenCVノート6–アウトライン(Contours)
参照ドキュメント:https://docs.opencv.org/3.4/dd/d49/tutorial_py_contour_features.html
1、輪郭の検索findContours
関数プロトタイプimage, contours, hierarchy = cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])
パラメータ:
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)
2、輪郭を描くfindContours
関数プロトタイプ
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)
3、輪郭の特徴Contour Features
3.1、モーメント:cv 2.moments()
関数のプロトタイプ:
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'])
3.2、面積:cv 2.contourArea()
関数のプロトタイプ:
cv2.contourArea(contour[, oriented])
例:
area = cv2.contourArea(cnt)
3.3、周長:cv 2.arcLength()
関数のプロトタイプ:
cv2.arcLength(curve, closed)
例:
perimeter = cv2.arcLength(cnt, True)
3.4、凸性検査:cv 2.isContourConvex()
関数のプロトタイプ:
cv2.isContourConvex(contour)
例:
k = cv2.isContourConvex(cnt)
4、輪郭近似Contour Approximation
4.1、多角形近似:cv 2.approxPolyDP()
関数のプロトタイプ:
cv2.approxPolyDP(curve, epsilon, closed[, approxCurve])
例:
epsilon = 0.1*cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
4.2、凸包近似:cv 2.convexHull()
関数のプロトタイプ:
cv2.convexHull(points[, hull[, clockwise[, returnPoints]]])
例:
hull = cv2.convexHull(cnt)
4.3、矩形近似:Bounding Rectangle
関数のプロトタイプ:
#
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)
4.4、その他の近似
#
(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)