如何去除二值图像中的噪声?

Vin*_*iow 5 python opencv image-processing python-3.x

这是我的代码,我试图从二进制图像中删除掩模(噪声)。我得到的是噪音周围留下的白线。我知道噪声周围有一条轮廓,在结果中形成了最终的白线。有什么帮助吗?

原始图像

原始图像

掩模和结果

掩模和结果

代码

import numpy as np
import cv2
from skimage import util

img = cv2.imread('11_otsu.png')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#cv2.drawContours(img, contours, -1, (0,255,0), 2)

# create an empty mask
mask = np.zeros(img.shape[:2], dtype=np.uint8)

# loop through the contours
for i, cnt in enumerate(contours):
    # if the contour has no other contours inside of it
    if hierarchy[0][i][2] == -1:
        # if the size of the contour is greater than a threshold
        if cv2.contourArea(cnt) <70:
            cv2.drawContours(mask, [cnt], 0, (255), -1)
            # display result

cv2.imshow("Mask", mask)

cv2.imshow("Img", img)
image = cv2.bitwise_not(img, img, mask=mask)
cv2.imshow("Mask", mask)
cv2.imshow("After", image)

cv2.waitKey()
cv2.destroyAllWindows()

Run Code Online (Sandbox Code Playgroud)

Kni*_*ked 3

您的代码完全没问题,只需进行这些调整即可工作:

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # Use cv2.CCOMP for two level hierarchy
if hierarchy[0][i][3] != -1: # basically look for holes
    # if the size of the contour is less than a threshold (noise)
    if cv2.contourArea(cnt) < 70:
        # Fill the holes in the original image
        cv2.drawContours(img, [cnt], 0, (255), -1)
Run Code Online (Sandbox Code Playgroud)