图像处理总目录←点击这里
cv2.findContours(img,mode,method)
cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2)
为了更高的准确率,使用二值图像cv2.THRESH_BINARY
,其余l类型详细点击 → 链接
def cv_show(img,name):
cv2.imshow(name,img)
cv2.waitKey()
cv2.destroyAllWindows()
img = cv2.imread('./image/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)
#传入绘制图像,轮廓,轮廓索引,颜色模式,线条厚度
# 注意需要copy,要不原图会变。。。
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2)
cv_show(res,'res')
计算面积和周长
cnt = contours[0]
#面积 8500.5
cv2.contourArea(cnt)
#周长,True表示闭合的 437.9482651948929
cv2.arcLength(cnt,True)
其中contours[0]
代表下图中的三角形的外边框(contours中的第一个元素)
contours下标代表意义
1 代表三角形内边框
2 代表六边形外边框
3 代表六边形内边框
…
画出contours[0]
img = cv2.imread('./image/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]
res = cv2.drawContours(draw_img, [cnt], -1, (0, 0, 255), 2)
cv_show(res,'res')
cv2.approxPolyDP(cnt,epsilon,True)
0.1*cv2.arcLength(cnt,True)
)
原始轮廓
img = cv2.imread('./image/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')
epsilon = 0.1*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')
epsilon = 0.1*cv2.arcLength(cnt,True)
epsilon = 0.15*cv2.arcLength(cnt,True)
epsilon = 0.2*cv2.arcLength(cnt,True)
原理方法
x,y,w,h = cv2.boundingRect(cnt)
获得左上角位置(xy)和宽高(wh)
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
画出矩形框
代码
img = cv2.imread('./image/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[2]
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')
(x,y),radius = cv2.minEnclosingCircle(cnt)
获得圆心半斤
cv2.circle(img,center,radius,(0,255,0),2)
画圆
cnt = contours[0]
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img,center,radius,(0,255,0),2)
cv_show(img,'img')