[SciPy-user] stupid array tricks

Stéfan van der Walt stefan at sun.ac.za
Sat Feb 7 12:36:46 EST 2009


2009/2/7 Karl Young <karl.young at 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

http://mentat.za.net/numpy/numpy_advanced_slides/

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
Out[25]:
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

In [26]: rows
Out[26]:
array([[0],
       [1],
       [2],
       [3]])

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]
Out[30]:
array([[ 0,  2],
       [ 3,  5],
       [ 6,  8],
       [ 9, 11]])

Hope that helps!

Cheers
Stéfan



More information about the SciPy-User mailing list