首页 > 解决方案 > 有没有办法用白色填充图像的内部?

问题描述

例如,在 MATLAB 图像处理工具箱中,我们有imfill函数。我怎样才能在 Python 中做到这一点?

所以我试图分割各种形状并去除内部的黑色。我知道如果我得到了边界,分割仍然很容易,但我也想检测出完美的形状。简而言之,我想删除图像中的黑色覆盖区域,如图所示。

我尝试过使用按位运算、形态变换和填充。我是洪水填充的新手,不知道它是如何工作的。

image=cv2.imread('rec2.jpg')
kernel = np.ones((5,5),np.uint8)
w=int(image.shape[1]*0.3)
h=int(image.shape[0]*0.5)
resized = cv2.resize(image,(w, h), interpolation = cv2.INTER_CUBIC)
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY_INV)[1]
thresh2 = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
print(len(cnts[1])) #To verify number of counts
cv2.imshow("Result",np.hstack((thresh,thresh2)))

在此处输入图像描述

这是到目前为止的分割图像。但我希望那些内部黑色区域也用白色填充,以便可以将其识别为实心形状。

标签: pythonopencvimage-processingimage-segmentationimage-thresholding

解决方案


您可以通过定义绘制填充轮廓thickness=cv2.FILLED

cv2.drawContours(thresh, cnts, -1, (255, 255, 255), thickness=cv2.FILLED)

推荐阅读