python - How to crop zero edges of a numpy array? -


i have ugly, un-pythonic beast:

def crop(dat, clp=true):     '''crops zero-edges of array , (optionally) clips [0,1].      example:     >>> crop( np.array(     ...       [[0,0,0,0,0,0],     ...        [0,0,0,0,0,0],     ...        [0,1,0,2,9,0],     ...        [0,0,0,0,0,0],     ...        [0,7,4,1,0,0],     ...        [0,0,0,0,0,0]]     ...     ))     array([[1, 0, 1, 1],            [0, 0, 0, 0],            [1, 1, 1, 0]])     '''     if clp: np.clip( dat, 0, 1, out=dat )     while np.all( dat[0,:]==0 ):         dat = dat[1:,:]     while np.all( dat[:,0]==0 ):         dat = dat[:,1:]     while np.all( dat[-1,:]==0 ):         dat = dat[:-1,:]     while np.all( dat[:,-1]==0 ):         dat = dat[:,:-1]     return dat     # below gets rid of zero-lines/columns in middle     #+so not usable.     #dat = dat[~np.all(dat==0, axis=1)]           #dat = dat[:, ~np.all(dat == 0, axis=0)] 

how tame it, , make beautiful?

try incorporating this:

# argwhere give coordinates of every non-zero point true_points = np.argwhere(dat) # take smallest points , use them top left of crop top_left = true_points.min(axis=0) # take largest points , use them bottom right of crop bottom_right = true_points.max(axis=0) out = dat[top_left[0]:bottom_right[0]+1,  # plus 1 because slice isn't           top_left[1]:bottom_right[1]+1]  # inclusive 

this expanded without reasonable difficulty general n-d case.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -