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)
下面的代码,从这个答案在我的测试中运行得最快:
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非零区域).
| 归档时间: |
|
| 查看次数: |
6326 次 |
| 最近记录: |