Wherein the contour image (perimeter, area, and an external contour is approximately rectangular and circumscribed circle) of OpenCV

On a blog talking about how to find and draw the outline of a picture; now come to talk about the common features of these profiles and how to use opencv inside the corresponding function.

1. cv2.contourArea(cnt, oriented = False)  # 计算轮廓的面积

参数说明:cnt为输入的单个轮廓值;oriented:默认值false,面向区域标识符,
如果为true,该函数返回一个带符号的面积,其正负取决于轮廓的方向(顺时针还是逆时针)。
根据这个特性可以根据面积的符号来确定轮廓的位置。如果是默认值false,则面积以绝对值的形式返回.

2. cv2.arcLength(cnt, closed)   #  计算轮廓的周长

参数说明:cnt为输入的单个轮廓值,closed表示用来指定对象的形状是
闭合的(True),还是打开的一条曲线(False)3. cv2.aprroxPolyDP(cnt, epsilon, True)  # 用于获得轮廓的近似值,使用cv2.drawCountors进行画图操作

 参数说明:cnt为输入的轮廓值, epsilon为阈值T,
 通常使用轮廓的周长作为阈值,True表示的是轮廓是闭合的

4. x, y, w, h = cv2.boudingrect(cnt) # 获得外接矩形

参数说明:x,y, w, h 分别表示外接矩形的x轴和y轴的坐标,
以及矩形的宽和高, cnt表示输入的轮廓值

5.cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)  # 根据坐标在图像上画出矩形

参数说明: img表示传入的图片, (x, y)表示左上角的位置, 
(x+w, y+h)表示加上右下角的位置,(0, 255, 0)表示颜色,2表示线条的粗细

6. (x, y), radius = cv2.minEnclosingCircle(cnt) # 获得外接圆的位置信息

参数说明: (x, y)表示外接圆的圆心,radius表示外接圆的半径,cnt表示输入的轮廓

7. cv2.Cricle(img, center, radius, (0, 255, 0), 2)  # 根据坐标在图上画出圆

参数说明:img表示需要画的图片,center表示圆的中心点,
radius表示圆的半径, (0, 255, 0)表示颜色, 2表示线条的粗细

A contour approximation:

Suppose there is a curve A, B, C is present at a point on the curve, the farthest distance from the line segment AB, referred to as d1, if d1 <T (own set threshold), as an alternative to the segment AB of the curve AB, NO by connecting AC and BC, D point on line segment AC is calculated from the farthest AB, denoted as d2, if d2 <T, then the AC line curve AC Alternatively, whether to continue the connection is divided.
Here Insert Picture Description

img = cv2.imread('contours2.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]

draw_img = img.copy()
res = cv2.drawContours(draw_img, [cnt], -1, (0, 0, 255), 2)
cv_show(res,'res')

Here Insert Picture Description

epsilon = 0.05*cv2.arcLength(cnt,True) 
approx = cv2.approxPolyDP(cnt,epsilon,True)

draw_img = img.copy()
res = cv2.drawContours(draw_img, [approx], -1, (0, 0, 255), 2)
cv_show(res,'res')

Here Insert Picture Description

Second, the bounding rectangle and the circumscribed circle

img = cv2.imread('contours.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]

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

Here Insert Picture Description
Here Insert Picture Description

Published 27 original articles · won praise 20 · views 1547

Guess you like

Origin blog.csdn.net/qq_39507748/article/details/104550500