如何去除图像中对象的边缘噪声

How to remove edge noises from an object in an image

我创建了一个衣服蒙版来从图像中提取衣服对象,但是蒙版中包含一些白噪声,如下图所示(外面的黑色区域是背景)。

我想去掉mask的"white"边缘噪声,我试过用朴素的方法检查像素值是否>=240,结果有所改善但仍然不完美,如下图:

我想完全消除白噪声,但不知道该怎么做。我正在使用 python opencv,如果有人能帮助我,我将不胜感激。

谢谢!

我建议使用一个简单的管道来消除边缘噪音:

import numpy as np
import cv2

gray = cv2.imread("t1yfp.jpg", cv2.IMREAD_GRAYSCALE)

#  eliminate white blobs
kernel = np.ones((5, 5), np.float32)/25
processedImage = cv2.filter2D(gray, -1, kernel)
gray[processedImage > 100] = 0

#  eliminate pixels with very large value
gray[gray > 230] = 0

#  eliminate last remeaning outlier white pixels
gray = cv2.medianBlur(gray, 5)



#  display result
cv2.imshow("res", gray)
cv2.waitKey(0)

最后一步后,图像蒙版内的白色像素也将被消除。您也许可以使用平均滤波器来恢复它们。这是结果:

通过扩大阈值图像,我能够从图像中取出稍大的部分并去除所有白色,但从一些无辜区域去除了 1px 的边缘。

结果如下:

这是代码,基于 this answer:

import cv2
import numpy as np

# Create binary threshold
img = cv2.imread('shirt.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, gray = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY)

# Dilate the image to join small pieces to the larger white sections
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
gray = cv2.dilate(gray, kernel)

# Create the mask by filling in all the contours of the dilated edges
mask = np.zeros(gray.shape, np.uint8)
_, contours, _ = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if 10 < cv2.contourArea(cnt) < 5000:
        #  cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
        cv2.drawContours(mask, [cnt], 0, 255, -1)

# Erode the edges back to their orig. size
# Leaving this out creates a more greedy bite of the edges, removing the single strands
#  mask = cv2.erode(mask, kernel)

cv2.imwrite('im.png', img)
cv2.imwrite('ma.png', mask)

mask = cv2.cvtColor(255 - mask, cv2.COLOR_GRAY2BGR)
img = img & mask
cv2.imwrite('fi.png', img)

这个答案的好处是轮廓部分允许您在使用神奇数字 10 时保持较小尺寸的白色区域(我假设这可能不是您想要的唯一图像 运行 这段代码结束。)如果没有必要,那么代码可以简单得多,只需 1) 采用原始阈值,2) 扩大它 3) 在原始图像上屏蔽它。