[SciPy-User] autocrop 2d array

Chris Weisiger cweisiger at msg.ucsf.edu
Thu May 12 12:38:56 EDT 2011


On Thu, May 12, 2011 at 8:56 AM, Christian K. <ckkart at hoc.net> wrote:

> Hi Zach,
>
> Zachary Pincus <zachary.pincus <at> yale.edu> writes:
>
> >
> > If you can specify the problem a little more clearly (I'm not familiar
> with
> autocrop) maybe I could help. Are
> > you looking for the smallest sub-array containing all of the non-zero
> values
> in the array? (That is, to
> > trim off zero-valued borders?)
> >
>
> That is exactly what I want.
>

You ought to be able to rig something up with numpy.where, which returns the
coordinates in the array that match some condition. Something like this:

foo = np.zeros((5, 5))
foo[1:4,1:4] = np.arange(9).reshape(3, 3)
coords = np.array(np.where(foo != 0)).T
minCorner = np.min(coords, axis = 0)
maxCorner = np.max(coords, axis = 0) + 1
foo[minCorner[0]:maxCorner[0], minCorner[1]:maxCorner[1]]

There's almost certainly even faster ways to do this; this is just the first
solution that came to mind.

-Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20110512/1759123a/attachment.html>


More information about the SciPy-User mailing list