是的。
ndimage.label
使用(首先反转图像,孔=黑色)标记您的图像。
- 找到孔对象切片
ndimage.find_objects
- 根据您的大小标准过滤对象切片列表
- 反转您的图像并
binary_fill_holes
在符合您标准的切片上执行。
应该这样做,而无需将图像切碎。例如:
输入图像:

输出图像(中等大小的孔消失了):

这是代码(设置不等式以删除中等大小的斑点):
import scipy
from scipy import ndimage
import numpy as np
im = scipy.misc.imread('cheese.png',flatten=1)
invert_im = np.where(im == 0, 1, 0)
label_im, num = ndimage.label(invert_im)
holes = ndimage.find_objects(label_im)
small_holes = [hole for hole in holes if 500 < im[hole].size < 1000]
for hole in small_holes:
a,b,c,d = (max(hole[0].start-1,0),
min(hole[0].stop+1,im.shape[0]-1),
max(hole[1].start-1,0),
min(hole[1].stop+1,im.shape[1]-1))
im[a:b,c:d] = scipy.ndimage.morphology.binary_fill_holes(im[a:b,c:d]).astype(int)*255
另请注意,我必须增加切片的大小,以便孔周围有边界。