NumPy中的ndarray是否有"边界框"功能(具有非零值的切片)?

hel*_*ker 18 python arrays numpy trim bounding

我正在处理通过numpy.array()创建的数组,我需要在模拟图像的画布上绘制点.由于在包含有意义数据的数组中心部分周围有很多零值,我想"修剪"数组,删除仅包含零的行和仅包含零的行.

所以,我想知道一些本地numpy函数甚至是一个代码片段来"修剪"或找到一个"边界框"来仅切片数组中包含数据的部分.

(因为这是一个概念性的问题,我没有提出任何代码,对不起,如果我应该,我很新鲜在SO上发帖.)

谢谢阅读

Pau*_*aul 22

这应该这样做:

from numpy import array, argwhere

A = array([[0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 0, 0, 0, 0],
           [0, 0, 1, 1, 0, 0, 0],
           [0, 0, 0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0]])

B = argwhere(A)
(ystart, xstart), (ystop, xstop) = B.min(0), B.max(0) + 1 
Atrim = A[ystart:ystop, xstart:xstop]
Run Code Online (Sandbox Code Playgroud)


Luk*_*uke 8

下面的代码,从这个答案在我的测试中运行得最快:

def bbox2(img):
    rows = np.any(img, axis=1)
    cols = np.any(img, axis=0)
    ymin, ymax = np.where(rows)[0][[0, -1]]
    xmin, xmax = np.where(cols)[0][[0, -1]]
    return img[ymin:ymax+1, xmin:xmax+1]
Run Code Online (Sandbox Code Playgroud)

接受的答案使用argwhere有效,但运行速度较慢.我的猜测是,这是因为argwhere分配了一个巨大的输出索引数组.我测试了一个大的2D阵列(1024 x 1024图像,大约有50x100非零区域).