Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
Created January 31, 2020 22:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaylockbk/a70537b41050d1d761ab6c5ab6e4bd43 to your computer and use it in GitHub Desktop.
Save blaylockbk/a70537b41050d1d761ab6c5ab6e4bd43 to your computer and use it in GitHub Desktop.
python function to extract the values around the border of an array
def border(array, corner=0, direction='cw'):
"""
Extract the values arround the border of a 2d array.
Default settings start from top left corner and move clockwise.
Corners are only used once.
Parameters
----------
array : array_like
A 2d array
corner : {0, 1, 2, 3}
Specify the corner to start at.
0 - start at top left corner (default)
1 - start at top right corner
2 - start at bottom right corner
3 - start at bottom left corner
direction : {'cw', 'ccw'}
Specify the direction to walk around the array
cw - clockwise (default)
ccw - counter-clockwise
Returns
-------
border : ndarray
Values around the border of `array`.
Examples
--------
>>> x, y = np.meshgrid(range(1,6), range(5))
>>> array=x*y
>>> array[0,0]=999
array([[999, 0, 0, 0, 0],
[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20]])
>>> border(array)
array([999, 0, 0, 0, 0, 5, 10, 15, 20, 16, 12, 8, 4,
3, 2, 1, 999])
>> border(array, corner=2)
array([ 20, 16, 12, 8, 4, 3, 2, 1, 999, 0, 0, 0, 0,
5, 10, 15, 20])
>>> border(array, direction='ccw')
array([999, 1, 2, 3, 4, 8, 12, 16, 20, 15, 10, 5, 0,
0, 0, 0, 999])
>>> border(array, corner=2, direction='ccw')
array([ 20, 15, 10, 5, 0, 0, 0, 0, 999, 1, 2, 3, 4,
8, 12, 16, 20])
"""
if corner > 0:
# Rotate the array so we start on a different corner
array = np.rot90(array, k=corner)
if direction is 'ccw':
# Transpose the array so we march around counter-clockwise
array = array.T
border = []
border += list(array[0, :-1]) # Top row (left to right), not the last element.
border +=list(array[:-1, -1]) # Right column (top to bottom), not the last element.
border +=list(array[-1, :0:-1]) # Bottom row (right to left), not the last element.
border +=list(array[::-1, 0]) # Left column (bottom to top), all elements element.
# NOTE: in that last statement, we include the last element to close the path.
return np.array(border)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment