版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_39611196/article/details/85002086
通过cv2中函数convexHull能很容易的得到一系列点的凸包,比如由点组成的轮廓,通过convexHull函数,我们就能得到轮廓的凸包。
下面是对地图进行凸包检测示例代码:
import cv2
import numpy as np
import sys
# 读取图片
img = cv2.imread('./sample.jpg', 1)
# 将图片转换到灰度空间
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 图像平滑
blur = cv2.blur(gray, (3, 3))
# 图像的二值阈值化
ret, thresh = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)
# 轮廓检测
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# 为凸包点创建数组
hull =[]
# 计算每个轮廓点
for i in range(len(contours)):
hull.append(cv2.convexHull(contours[i], False))
# 创建一个空白的黑色图片
drawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)
# 绘制轮廓和凸包点
for i in range(len(contours)):
color_contours = (0, 255, 0) # 轮廓颜色
color = (255, 255, 255) # 凸包的颜色
# 绘制轮廓
cv2.drawContours(drawing, contours, i, color_contours, 2, 8, hierarchy)
# 绘制凸包
cv2.drawContours(drawing, hull, i, color, 2, 8)
cv2.imwrite('result.jpg', drawing)
cv2.imshow("Output", drawing)
cv2.waitKey(0)
cv2.destroyAllWindows()
测试图片:
测试结果: