How to crop a numpy 2d array to non-zero values?

后端 未结 3 1228
孤独总比滥情好
孤独总比滥情好 2020-12-11 18:48

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         


        
3条回答
  •  暖寄归人
    2020-12-11 19:19

    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]
    

    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)
    

提交回复
热议问题