绘制轮廓
cv2.drawContours可以实现轮廓绘制.

格式:

cv2.drawContours(image, contours, contourIdx, color, thickness=None, lineType=None, hierarchy=None, maxLevel=None, offset=None):
1
参数:

image: 需要绘制轮廓的图片
contours: 轮廓
color: 颜色
thickness: 轮廓粗细

# 读取图片
import cv2

img = cv2.imread("tx.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)

# 绘制轮廓
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2)

# 图片展示
cv2.imshow("res", res)
cv2.waitKey(0)
cv2.destroyAllWindows()


图像处理11  图像轮廓_灰度图

 

 

绘制单个轮廓:

import cv2
# 读取图片
img = cv2.imread("tx.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)

# 绘制轮廓 (单一)
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, 0, (0, 0, 255), 2)

# 图片展示
cv2.imshow("res", res)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像处理11  图像轮廓_获取图片_02

 

 

边界矩形

cv2.boundingRect可以帮助我们得到边界矩形的位置和长宽

 

import cv2
# 读取图片
img = cv2.imread("tx.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]

 轮廓面积与边界矩形比: 0.9960818994520811

图像处理11  图像轮廓_获取图片_03

 

 

 

外接圆

cv2.minEnclosingCircle可以帮助我们得到外接圆的位置和半径.

 

 

import cv2
# 读取图片
img = cv2.imread("girl.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), radius = cv2.minEnclosingCircle(cnt)

# 获取图片
img = cv2.circle(img, (int(x), int(y)), int(radius), (255, 100, 0), 2)

# 图片展示
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()