我有一个黑白图像。我尝试通过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仍然存在。
我做错了吗?谢谢
答案 0 :(得分:2)
来自docs(重点是我):
skimage.morphology.remove_small_objects(ar, min_size=64, connectivity=1, in_place=False)
删除小于指定大小的对象。
期望ar是带有标签对象的数组,并删除小于min_size的对象。 如果ar是bool,则首先标记图像。这会导致bool和0-and-1数组的行为不同。
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)