使用OpenCV for Python,我试图在图像中获得噪声元素的遮盖物,以便稍后用作cv.inpaint()
函数的输入。
我在input_mtx_8u
变量中获得了灰度图像(值为0到255的2D矩阵),并带有噪声(孤立的非常低值的多边形)。
到目前为止,我所做的是:
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)
filled_mtx = input_mtx_8u.copy()
cv2.fillPoly(filled_mtx, contours, (255, 255, 0), 4)
由于某种原因,我的“填充的多边形”没有完全填充(见图)。 我该怎么办?
答案 0 :(得分:0)
如@ fmw42所指出的那样,填充轮廓的解决方案是使用drawContours()
而不是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)
不起作用。必须循环并按轮廓绘制轮廓...