在imag中标记边

2024-06-28 10:54:09 发布

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

我编写了一个函数来标记像素级标记图像中对象的边缘:

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)处应该有另一个标记。我必须接受这种错误吗?还是有办法解决的?你知道吗


Tags: 对象in标记imagefornpmarkermark
1条回答
网友
1楼 · 发布于 2024-06-28 10:54:09

np.not_equal代替np.greater。这将导致所有区域的边缘都被标记,包括背景区域。你知道吗

接下来,移除背景区域上的边。你知道吗

在下面的代码中,我使用的是“遮罩图像”,而不是边缘像素列表。我觉得这更容易处理,而且效率也很高。你知道吗

import numpy as np

def mark_edges(image, marker):

  axes = len(image.shape)
  mask = np.zeros(image.shape, dtype=bool)

  for i in range(axes):
    shiftright = np.not_equal(image, np.roll(image, 1, axis=i))
    shiftleft = np.not_equal(image, np.roll(image, -1, axis=i))
    mask |= shiftright != shiftleft

  mask[image==0] = 0
  image[mask] = marker

  return image

问题的图像b输出:

>>> 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.  99.  99.   4.  99.   0.]
 [  0.  99.  99.  99.  99.  99.  99.   0.]
 [  0.   0.   0.   0.   0.   0.   0.   0.]]

相关问题 更多 >