✨博客主页:米开朗琪罗~
✨博主爱好:羽毛球
✨年轻人要:Living for the moment(活在当下)!
推荐专栏:【图像处理】【千锤百炼Python】【深度学习】【排序算法】
凸包是一个几何图形学中的概念,用不严谨的话来说,凸包就是将最外层的点连接起来构成的凸多边形,凸包包含点集中的所有点。
函数:hull = cv2.convexHull(contours)
参数介绍:
import cv2
import numpy as np
original = cv2.imread(r'C:\Users\Lenovo\Desktop\contour.jpg')
# 查找物体轮廓
def findcontour(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 图像灰度化
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 图像二值化
image, contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 查找物体轮廓
return image, contours, hierarchy
image, contours, hierarchy = findcontour(original)
nums = len(contours)
for i in range(nums):
hull = cv2.convexHull(contours[i])
cv2.polylines(original, [hull], True, (255, 0, 0), 2)
cv2.imwrite(r'C:\Users\Lenovo\Desktop\result.jpg', original)
cv2.imshow("result", original)
cv2.waitKey()
轮廓与凸包的任何偏差都称为凸缺陷。
函数:defects = cv2.convexityDefects(contours,hull)
参数介绍:
这里我们绘制五角星的凸缺陷
import cv2
import numpy as np
original = cv2.imread(r'C:\Users\Lenovo\Desktop\contour.jpg')
# 查找物体轮廓
def findcontour(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 图像灰度化
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 图像二值化
image, contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 查找物体轮廓
return image, contours, hierarchy
image, contours, hierarchy = findcontour(original)
cnt = contours[0]
hull = cv2.convexHull(cnt,returnPoints=False)
defects = cv2.convexityDefects(cnt, hull)
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv2.line(original, start, end, [0, 0, 255], 2)
cv2.circle(original, far, 5, [255, 0, 0], -1)
cv2.imwrite(r'C:\Users\Lenovo\Desktop\result.jpg', original)
cv2.imshow('result', original)
cv2.waitKey(0)