这可以更具体地使用形态学运算和最小/最大过滤器来解决。速度应该是可以接受的,因为整个图像只需要处理两次,而与组件的数量无关。
以下代码的最大部分仅用于生成示例图像。获取边界的相关线路如下所示:
# imports
import numpy as np
import scipy as sp
import scipy.ndimage
# size of test image
L=50
# number of components
I=20
# auxiliary array
array=np.zeros((I,L,L))
# for each component
for i in range(I):
# draw random coordinates
x,y=sp.random.randint(0,L,size=2)
# set coordinate in auxiliary array to index of i-th component
array[i,x,y]=i
# create 'box' around coordinate
array[i]=sp.ndimage.maximum_filter(array[i],size=20)
# create actual test image from auxiliary array
image=np.nanmax(array,axis=0)
# RELEVANT LINES: check if pixel belongs to border
imax=(sp.ndimage.maximum_filter(image,size=3)!=image)
imin=(sp.ndimage.minimum_filter(image,size=3)!=image)
icomb=np.logical_or(imax,imin)
# keep only pixels of original image at borders
edges=np.where(icomb,image,np.nan)