Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created April 5, 2010 13:24
Show Gist options
  • Save pyrtsa/356328 to your computer and use it in GitHub Desktop.
Save pyrtsa/356328 to your computer and use it in GitHub Desktop.
def offset(image, d)
def offset(image, d):
"""
Create a subview of image where the indices are offset by (a tuple) d.
Assume you needed to select all the items in a 3-D numpy.ndarray arr
which have neighbors at a distance d = (i, j, k). You can easily view
those items calling:
offset(arr, (-i, -j, -k)).
The neighbors are then, respectively:
offset(arr, d)
(Using the helper class vec, http://gist.github.com/356316, might help
even further, simplifying the negative offset to just -d.)
Example:
>>> from numpy import arange, reshape
>>> x = arange(15).reshape(5,3)
>>> x
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> offset(x, (1,2))
array([[ 7, 8, 9],
[12, 13, 14]])
>>> offset(x, (-1,2))
array([[2, 3, 4],
[7, 8, 9]])
>>> offset(x, (-1,2)) - offset(x, (1,2))
array([[-5, -5, -5],
[-5, -5, -5]])
"""
return image[[slice(0,i) if (i < 0) else slice(i,None) for i in d]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment