[SciPy-user] stupid array tricks

Young, Karl karl.young@ucsf....
Mon Feb 9 11:03:45 CST 2009

Thanks Stefan ! The index meister comes through again. I was sort of thinking along those lines but couldn't quite take the final step of understanding how to get the row coordinates for arbitrary filter locations. BTW, I should send you the latest version of my modification of glcom; the "profiling" that showed this part of my code to be the current bottleneck was the result of the generalized glcom (arbitrary number of co-registered images and arbitrary templates) being so fast at generating the co-occurrence matrices (for others on the list, Stefan wrote a very nice ctypes module, glcom, that generates co-occurrence matrices from an image for doing texture analysis). 

Karl Young
Center for Imaging of Neurodegenerative Disease, UCSF
VA Medical Center, MRS Unit (114M)
Phone:  (415) 221-4810 x3114
FAX:    (415) 668-2864
Email:  karl young at ucsf edu

-----Original Message-----
From: scipy-user-bounces@scipy.org on behalf of Stéfan van der Walt
Sent: Sat 2/7/2009 9:36 AM
To: SciPy Users List
Subject: Re: [SciPy-user] stupid array tricks
2009/2/7 Karl Young <karl.young@ucsf.edu>:
> I have three objects, 1) an array containing an "image" (could be any
> dimension), 2) a mask for the image (of the same dimensions as the
> image), and 3) a "template" which is just a list of offset coordinates
> from any point in the image.

You can create a strided view of the image, so that the values around
each position where the filter can be applied becomes a row.
Thereafter, using the indexing tricks shown at


index the view to produce the templated values at each position.

Say your template has length n, then you'd have:

template of shape (1, n)
rows = np.arange(m)[:, None] with shape (m, 1)

When using template and rows in a fancy indexing operating, you should
get an output of shape (m, n).

Here is a simplified example:

# Strided view of your image
In [25]: data
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

In [26]: rows

In [27]: rows.shape
Out[27]: (4, 1)

In [28]: template
Out[28]: array([[0, 2]])

In [29]: template.shape
Out[29]: (1, 2)

In [30]: data[rows, template]
array([[ 0,  2],
       [ 3,  5],
       [ 6,  8],
       [ 9, 11]])

Hope that helps!

SciPy-user mailing list

More information about the SciPy-user mailing list