[SciPy-User] autocrop 2d array
Christian K.
ckkart at hoc.net
Fri May 13 12:36:00 EDT 2011
Am 12.05.11 18:38, schrieb Chris Weisiger:
> On Thu, May 12, 2011 at 8:56 AM, Christian K. <ckkart at hoc.net
> <mailto:ckkart at hoc.net>> wrote:
>
> Hi Zach,
>
> Zachary Pincus <zachary.pincus <at> yale.edu <http://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]]
>
Thanks all, that works very well.
Christian
More information about the SciPy-User
mailing list