Skip to main content
 首页 » 编程设计

python之快速找到大图像中连通分量的最小和最大坐标

2024年10月01日6zhengyun_ustc

我有一张尺寸为 50000x50000 的图片。它有大约 25000 连接不同的连接组件。我正在使用 ndimage.label 来标记它们中的每一个,然后找到非零点并最终获得最小 x、最大 x、最小 y 和最大 y 值。但是,我必须找到这些坐标是针对每个 25000 连接组件的。这很昂贵,因为我必须在 50000x50000 图像上运行 np.nonzero 25000 次。这是执行我刚才提到的代码的片段。

im, _ = ndimage.label(im) 
num_instances = np.max(np.max(im)) 
for instance_id in range(1,num_instances+1): 
    im_inst = im == instance_id  
    points = np.nonzero(im_inst) # running this is expensive as im is 50000x50000 
 
    cropped_min_x_1 = np.min(points[0]) 
    cropped_min_y_1 = np.min(points[1])  
    cropped_max_x_1 = np.max(points[0])+1  
    cropped_max_y_1 = np.max(points[1])+1 

有谁知道我可以做些什么来显着加快这个过程?

请您参考如下方法:

如果标记像素的比例不是太大:

nz = np.flatnonzero(im) 
order = np.argsort(im.ravel()[nz]) 
nz = nz[order] 
blocks = np.searchsorted(im.ravel()[nz], np.arange(2, num_instances+1)) 
# or (which is faster will depend on numbers) 
blocks = 1 + np.where(np.diff(im.ravel()[nz]))[0] 
coords = np.array(np.unravel_index(nz, (50000, 50000))) 
groups = np.split(coords, blocks, axis=-1) 

组将是 2xn_i 坐标的列表,其中 n_i 是组件 i 的大小。