remove_small_objects 消除噪音失败

Failed to remove noise by remove_small_objects

我有一张黑白图像。我尝试通过 remove_small_objects.

消除噪音
import cv2 as cv
import numpy as np
from skimage import morphology

img = np.array([[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
                [255, 255,   0, 255,   0,   0,   0,   0, 255, 255, 255],
                [255, 255, 255, 255,   0,   0,   0,   0, 255,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0, 255,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255, 255,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0]])

cleaned = morphology.remove_small_objects(img, min_size=10, connectivity=1)
print(cleaned)

while True:
    cv.imshow('Demo', cleaned.astype(np.uint8))
    if cv.waitKey(1) & 0xFF == 27:
        break

cv.destroyAllWindows()

然而,它并没有像我预期的那样工作。中间的白色像素点255还在。

我是不是做错了什么?谢谢

来自 docs(强调我的):

skimage.morphology.remove_small_objects(ar, min_size=64, connectivity=1, in_place=False)

Remove objects smaller than the specified size.

Expects ar to be an array with labeled objects, and removes objects smaller than min_size. If ar is bool, the image is first labeled. This leads to potentially different behavior for bool and 0-and-1 arrays.

import numpy as np
from skimage import io, morphology
import matplotlib.pyplot as plt

img = np.array([[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
                [255, 255,   0, 255,   0,   0,   0,   0, 255, 255, 255],
                [255, 255, 255, 255,   0,   0,   0,   0, 255,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0, 255,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255, 255,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
                [255, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0]])

arr = img > 0
cleaned = morphology.remove_small_objects(arr, min_size=2)
cleaned = morphology.remove_small_holes(cleaned, min_size=2)

fig, axs = plt.subplots(1, 2)
axs[0].imshow(img, cmap='gray')
axs[0].set_title('img')
axs[1].imshow(cleaned, cmap='gray')
axs[1].set_title('cleaned')
plt.show(fig)