本文介绍了如何将一个numpy的二维数组裁剪为非零值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一个2d布尔numpy数组,如下所示:
Let's say i have a 2d boolean numpy array like this:
import numpy as np
a = np.array([
[0,0,0,0,0,0],
[0,1,0,1,0,0],
[0,1,1,0,0,0],
[0,0,0,0,0,0],
], dtype=bool)
我通常如何将其裁剪到包含所有True值的最小框(矩形,内核)?
How can i in general crop it to the smallest box (rectangle, kernel) that includes all True values?
因此在上面的示例中:
b = np.array([
[1,0,1],
[1,1,0],
], dtype=bool)
推荐答案
经过一番摆弄之后,我本人实际上找到了一个解决方案:
After some more fiddling with this, i actually found a solution myself:
coords = np.argwhere(a)
x_min, y_min = coords.min(axis=0)
x_max, y_max = coords.max(axis=0)
b = cropped = a[x_min:x_max+1, y_min:y_max+1]
以上内容适用于开箱即用的布尔数组.如果您还有其他条件,例如阈值t
,并且想要裁剪为大于t的值,只需修改第一行:
The above works for boolean arrays out of the box. In case you have other conditions like a threshold t
and want to crop to values larger than t, simply modify the first line:
coords = np.argwhere(a > t)
这篇关于如何将一个numpy的二维数组裁剪为非零值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!