我已经编写了此python代码来获取标签的邻居(一组共享某些共同属性的像素)。标签的邻居定义为位于边界另一侧的其他标签(相邻标签共享边界)。因此,我编写的代码可以运行,但是速度非常慢:
# segments: It is a 2-dimensional numpy array (an image really)
# where segments[x, y] = label_index. So each entry defines the
# label associated with a pixel.
# i: The label whose neighbours we want.
def get_boundaries(segments, i):
neighbors = []
for y in range(1, segments.shape[1]):
for x in range(1, segments.shape[0]):
# Check if current index has the label we want
if segments[x-1, y] == i:
# Check if neighbour in the x direction has
# a different label
if segments[x-1, y] != segments[x, y]:
neighbors.append(segments[x,y])
# Check if neighbour in the y direction has
# a different label
if segments[x, y-1] == i:
if segments[x, y-1] != segments[x, y]:
neighbors.append(segments[x, y])
return np.unique(np.asarray(neighbors))
如您所料,我可能在这里完全滥用了python。我想知道是否有一种方法可以优化此代码,使其更具pythonic风格。
干得好:
def get_boundaries2(segments, i):
x, y = np.where(segments == i) # where i is
right = x + 1
rightMask = right < segments.shape[0] # keep in bounds
down = y + 1
downMask = down < segments.shape[1]
rightNeighbors = segments[right[rightMask], y[rightMask]]
downNeighbors = segments[x[downMask], down[downMask]]
neighbors = np.union1d(rightNeighbors, downNeighbors)
return neighbors
如您所见,根本没有Python循环。我还尝试最小化副本(第一次尝试segments
使用NAN边框进行副本的复制,但是后来我设计了“保持边界”检查)。
注意,我并没有i
从“邻居”中过滤掉自己。您可以根据需要在结尾处轻松添加。一些时间:
输入2000x3000:原始耗时13秒,我的耗时370毫秒(加速35倍)。
输入1000x300:原始耗时643毫秒,我的耗时17.5毫秒(36倍加速)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句