我试图通过删除所有完全隔离的单个单元格来减少二进制 python 数组中的噪声,即将“1”值单元格设置为 0,如果它们完全被其他“0”包围。我已经能够通过使用循环删除大小等于 1 的 blob 来获得可行的解决方案,但这对于大型数组来说似乎是一个非常低效的解决方案:
import numpy as np
import scipy.ndimage as ndimage
import matplotlib.pyplot as plt
# Generate sample data
square = np.zeros((32, 32))
square[10:-10, 10:-10] = 1
np.random.seed(12)
x, y = (32*np.random.random((2, 20))).astype(np.int)
square[x, y] = 1
# Plot original data with many isolated single cells
plt.imshow(square, cmap=plt.cm.gray, interpolation='nearest')
# Assign unique labels
id_regions, number_of_ids = ndimage.label(square, structure=np.ones((3,3)))
# Set blobs of size 1 to 0
for i in xrange(number_of_ids + 1):
if id_regions[id_regions==i].size == 1:
square[id_regions==i] = 0
# Plot desired output, with all isolated single cells removed
plt.imshow(square, cmap=plt.cm.gray, interpolation='nearest')
在这种情况下,侵 eclipse 和扩张我的数组将不起作用,因为它还会删除宽度为 1 的特征。我觉得解决方案位于 scipy.ndimage 包中的某处,但是到目前为止,我还没有能够破解它。任何帮助将不胜感激!
最佳答案
感谢 Jaime 和 Kazemakase 的回复。手动邻域检查方法确实删除了所有孤立的补丁,但也删除了一个角(即示例数组中正方形的右上角)附加到其他补丁的补丁。面积求和表在小样本阵列上运行得非常好并且速度非常快,但在较大的阵列上速度变慢。
我最终遵循了一种使用 ndimage 的方法,它似乎对非常大和稀疏的数组有效地工作(5000 x 5000 数组为 0.91 秒,求和面积表方法为 1.17 秒)。我首先为每个离散区域生成一个标记的唯一 ID 数组,计算每个 ID 的大小,屏蔽大小数组以仅关注大小 == 1 blob,然后索引原始数组并将大小 == 1 设置为 0 :
def filter_isolated_cells(array, struct):
""" Return array with completely isolated single cells removed
:param array: Array with completely isolated single cells
:param struct: Structure array for generating unique regions
:return: Array with minimum region size > 1
"""
filtered_array = np.copy(array)
id_regions, num_ids = ndimage.label(filtered_array, structure=struct)
id_sizes = np.array(ndimage.sum(array, id_regions, range(num_ids + 1)))
area_mask = (id_sizes == 1)
filtered_array[area_mask[id_regions]] = 0
return filtered_array
# Run function on sample array
filtered_array = filter_isolated_cells(square, struct=np.ones((3,3)))
# Plot output, with all isolated single cells removed
plt.imshow(filtered_array, cmap=plt.cm.gray, interpolation='nearest')
结果:
关于python - 从 Python 数组中删除完全隔离的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28274091/