轮廓和凸包

import cv2
imagepath = "./hand.jpg"
img = cv2.imread(imagepath)
print(img.shape[:2])
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,235,255,cv2.THRESH_BINARY)
# 注意,findContous接受的是二值图
# 函数返回三个参数,第一个image,第二个是contours轮廓信息,第三个是层析结构
image,contours,hierarchy = cv2.findContours(thresh,2,1)

print("contours_type: ",type(contours))
print("contours_size: ",len(contours))
print("contours_data:\n",contours)

img_clone_1 = image.copy()
img_clone_2 = image.copy()
# 绘制轮廓图
cv2.drawContours(img_clone_1,contours,-1,(0,0,255),2)
cv2.imshow("drawContours_contours",img_clone_1)

# 对每个轮廓找凸包
hulls = []
index = 1
for cnt in contours:

    # 输出当前轮廓序号
    print("contour {}:\n".format(index),cnt)
    # 寻找凸包使用cv2.convexHull(contour)
    hull = cv2.convexHull(cnt)
    print("hull {}:\n".format(index),hull)
    # 获取凸包大小
    hulls.append(hull)
    hull_length = len(hull)
    if hull_length>5:
        for i in range(hull_length):
            cv2.line(img,tuple(hull[i][0]),tuple(hull[(i+1)%hull_length][0]),(0,0,255),2)
    index += 1
draw_hulls = cv2.drawContours(img_clone_2,hulls, -1, (0, 0, 255), 2)
cv2.imshow("draw_hulls",draw_hulls)
cv2.imshow('finger',img)
cv2.waitKey()

轮廓和凸包