删除二值图像中的单个像素

2024-09-28 03:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个二值图像,表示为numpy矩阵,其中一个像素是背景(0)或前景(1)。我正在寻找一种方法,删除前景中没有任何近邻的所有像素

假设图像矩阵为:

a = np.array([[0,0,1,1],[1,0,0,0]])

单像素删除后的结果图像应为

b = np.array([[0,0,1,1],[0,0,0,0]])

到目前为止,我的方法是为所有可能的方向组合开口:

opening1 = ndi.morphology.binary_opening(edge, structure=np.array([[0,1,0],[0,1,0],[0,0,0]]))
opening2 = ndi.morphology.binary_opening(edge, structure=np.array([[0,0,0],[0,1,1],[0,0,0]]))
opening3 = ndi.morphology.binary_opening(edge, structure=np.array([[1,0,0],[0,1,0],[0,0,0]]))
opening4 = ndi.morphology.binary_opening(edge, structure=np.array([[0,0,0],[0,1,0],[0,0,1]]))

opening = opening1 + opening2 + opening3 + opening4

另一种方法是标记连接的组件并通过索引将其删除,但是当涉及到计算复杂性时,这些解决方案感觉是次优的


Tags: 方法图像np矩阵像素structurearrayndi
2条回答

这个怎么样

其思想是在每个方向上创建一个像素的图像偏移,然后通过查看任何偏移的对应关系来确定是否存在邻居

import numpy as np

a = np.array([[0,0,1,1],[1,0,0,0]])

print(a)

shift_bottom = np.roll(a, -1, axis=0)
shift_top = np.roll(a, 1, axis=0)
shift_right= np.roll(a, 1, axis=1)
shift_left= np.roll(a, -1, axis=1)

b = (a * shift_bottom) | (a * shift_top) | (a * shift_right) | (a * shift_left)

print(b)

实际上,给连接的组件贴标签似乎是一条可行之路。至少skimageremove_small_objects函数here中是这样做的

相关问题 更多 >

    热门问题