在OpenCV Python中绘制凸包

5

我正在尝试用Python从轮廓中绘制凸包(convexHull),但是当我打印图像时,它没有改变。

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

有人知道吗?还是找不到解决方法。 - Trevor Judice
你能上传你正在处理的图片吗? - Jeru Luke
@JeruLuke 这是许多图像,每个图像都被二值化处理。我正在创建一个OCR平台,因此每个ROI都代表一个不同的字符。 - Trevor Judice
@JeruLuke 我刚刚添加了一个示例图像。这通常是它的外观;但是,字符周围的空白区域扩展了一些。 - Trevor Judice
1个回答

12

我使用以下代码为您提供的图像获取凸包:

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

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

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

现在在情况2中,轮廓是基于这张图片找到的:enter image description here

正如您所看到的,轮廓是基于二进制图像中的白色区域找到的。

希望这能帮助您。

我使用此链接获取代码和参考资料。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接