我使用以下代码为您提供的图像获取凸包:
import cv2
import numpy as np
img = cv2.imread('2.png')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 127, 255, 0)
contours,hierarchy = cv2.findContours(thresh,2,1)
print len(contours)
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(img,start,end,[0,255,0],2)
cv2.circle(img,far,5,[0,0,255],-1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
由于轮廓是基于图像中的白色区域,因此我通过更改代码中的第五行,得到了两种轮廓类型。
情况1:
我可以获得这个: ![enter image description here](https://istack.dev59.com/LDPxo.webp)
情况2:
现在当我改变代码段中的第五行时,在反转二进制图像ret, thresh = cv2.threshold(img_gray, 127, 255, 1)
后,我得到了这个:
这是因为在情况1中,轮廓是基于这张图片找到的:![enter image description here](https://istack.dev59.com/iVqmO.webp)
现在在情况2中,轮廓是基于这张图片找到的:![enter image description here](https://istack.dev59.com/GCb6j.webp)
正如您所看到的,轮廓是基于二进制图像中的白色区域找到的。
希望这能帮助您。
我使用此链接获取代码和参考资料。