快速查找大图像中连接组件的最小和最大坐标

时间:2017-02-28 01:58:15

标签: python image performance numpy matrix

我的图片大小为50000x50000。它有大约25000连接不同的连接组件。我使用ndimage.label标记每一个,然后我找到非零点,最后得到min x,max x,min y和max y值。但是,我必须找到每个25000连接组件的这些坐标。这很昂贵,因为我必须在np.nonzero图片50000x50000次上运行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

有谁知道我能做些什么来大大加快这个过程?

1 个答案:

答案 0 :(得分:2)

如果标记像素的分数不是太大:

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的大小。