用openCV2 Python绘制converxhull

2024-05-15 20:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着用python从一个轮廓中画出converxhull,但是当我打印图像时它没有变化。

roi=mask[y:y+h,x:x+w]
roi = cv2.fastNlMeansDenoisingColored(roi,None,15,15,7,21)
hull = cv2.convexHull(cnt)
cv2.drawContours(roi,[hull],0,(147,0,255),2)
cv2.imshow(str(i),roi)
blank_image[y:y+h,x:x+w] = roi

但是,如果我没有包含代码,显示的图像是完全相同的。我上网查了一下,但似乎找不到答案。 这是一个示例图像:Sample Image


Tags: 图像nonemaskcv2轮廓imshowstrcnt
1条回答
网友
1楼 · 发布于 2024-05-15 20:37:57

我使用了以下代码来获取您给出的图像的凸面外壳:

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()

由于轮廓是基于图像中的白色区域,所以我可以通过改变代码中的第5行获得两种轮廓类型。

案例1:

我得到了这个:enter image description here

案例2: 现在,当我改变代码段中的第五行时,我得到这个:enter image description here当我反转二进制图像时ret, thresh = cv2.threshold(img_gray, 127, 255, 1)

这是因为在情况1中,轮廓是基于此图像enter image description here找到的

现在,在情况2中,基于此图像enter image description here找到了轮廓

如您所见,轮廓是基于二值图像中的白色区域找到的。

希望这有帮助。

我用THIS LINK来获取代码和参考。

相关问题 更多 >