Python OpenCV.fillPoly()不填充多边形。为什么?
使用OpenCV for Python,我正在尝试获取图像中噪声元素的掩码,以便稍后用作Python OpenCV.fillPoly()不填充多边形。为什么?,python,opencv,Python,Opencv,使用OpenCV for Python,我正在尝试获取图像中噪声元素的掩码,以便稍后用作cv.inpaint()函数的输入 在input_mtx_8u变量中,我得到了一个灰度图像(值为0到255的2D矩阵),带有噪声(非常低值的孤立多边形) 到目前为止,我所做的是: 获取渐变大于25的边: 获取工件的轮廓 填充确定的等高线 由于某些原因,我的“填充多边形”没有完全填充(见图)。 我会做错什么 正如@fmw42所指出的,填充轮廓的解决方案是使用drawcourts()而不是fillPoly() 我
cv.inpaint()
函数的输入
在input_mtx_8u
变量中,我得到了一个灰度图像(值为0到255的2D矩阵),带有噪声(非常低值的孤立多边形)
到目前为止,我所做的是:
正如@fmw42所指出的,填充轮廓的解决方案是使用
drawcourts()
而不是fillPoly()
我得到的最终工作代码是:
# input_mtx_8u = 2D matrix with uint8 values from 0 to 255
laplacian = cv2.Laplacian(input_mtx_8u, cv2.CV_8UC1)
lapl_bin, lapl_bin_val = cv2.threshold(laplacian, 25, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(lapl_bin_val, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
inpaint_mask = np.zeros(input_mtx_8u.shape, dtype=np.uint8)
for contour in contours:
cv2.drawContours(inpaint_mask, [contour], -1, (255, 0, 0), thickness=-1)
# inpaint_mask = can be used as the mask for cv2.inpaint()
请注意,出于某些原因:
cv2.drawContours(input_mtx_cont, contours, -1, (255, 0, 0), thickness=-1)
不起作用。必须循环并按等高线绘制等高线…要填充多边形,请使用-1表示线的厚度感谢您的建议,fmw42。但我不清楚应该在哪里将线的滴答度设置为-1。cv2.findContours()或cv2.fillPoly()似乎都没有此参数,只有cv2.drawContours()有此参数。所以cv2.fillPoly()将取决于cv2.drawContours()的输出?我的错误。我在想你。你的多边形闭合了吗?如果从边获取轮廓,则这些轮廓定义的是边,而不是多边形。尝试对图像设置阈值,然后获得阈值化白色对象的轮廓。最好是你展示你的输入图像和更多的代码,这样我们就可以复制和修改它。这是你的问题吗?@fmw42的答案帮助我找到了答案,Ahmet。我使用drawContours()修改我的矩阵并获得填充轮廓,这些轮廓后来被用作我正在寻找的遮罩。谢谢大家!
filled_mtx = input_mtx_8u.copy()
cv2.fillPoly(filled_mtx, contours, (255, 255, 0), 4)
# input_mtx_8u = 2D matrix with uint8 values from 0 to 255
laplacian = cv2.Laplacian(input_mtx_8u, cv2.CV_8UC1)
lapl_bin, lapl_bin_val = cv2.threshold(laplacian, 25, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(lapl_bin_val, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
inpaint_mask = np.zeros(input_mtx_8u.shape, dtype=np.uint8)
for contour in contours:
cv2.drawContours(inpaint_mask, [contour], -1, (255, 0, 0), thickness=-1)
# inpaint_mask = can be used as the mask for cv2.inpaint()
cv2.drawContours(input_mtx_cont, contours, -1, (255, 0, 0), thickness=-1)