我编写了一个函数来标记像素级标记图像中对象的边缘:
import numpy as np
def mark_edges(image, marker):
axes = len(image.shape)
edges = []
for i in range(axes):
shiftright = np.greater(image, np.roll(image, 1, axis=i))
shiftleft = np.greater(image, np.roll(image, -1, axis=i))
idx = np.where(shiftright != shiftleft)
edges.append(idx)
for idx in edges:
image[idx] = marker
return image
对于孤立对象,这很好,因为每个标签都大于背景:
a = np.zeros(40).reshape(5,8)
a[1:4, 1:7] = 2
print(mark_edges(a, 99))
[[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 99. 99. 99. 99. 99. 99. 0.]
[ 0. 99. 2. 2. 2. 2. 99. 0.]
[ 0. 99. 99. 99. 99. 99. 99. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]]
但如果两个标记不同的对象相邻,结果会略有不同:
b = np.zeros(40).reshape(5,8)
b[1:4, 1:4] = 2
b[1:4, 4:7] = 4
print(mark_edges(b, 99))
[[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 99. 99. 99. 99. 99. 99. 0.]
[ 0. 99. 2. 2. 99. 4. 99. 0.]
[ 0. 99. 99. 99. 99. 99. 99. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]]
理想情况下,在位置(2,3)处应该有另一个标记。我必须接受这种错误吗?还是有办法解决的?你知道吗
用
np.not_equal
代替np.greater
。这将导致所有区域的边缘都被标记,包括背景区域。你知道吗接下来,移除背景区域上的边。你知道吗
在下面的代码中,我使用的是“遮罩图像”,而不是边缘像素列表。我觉得这更容易处理,而且效率也很高。你知道吗
问题的图像
b
输出:相关问题 更多 >
编程相关推荐