Skip to content

Instantly share code, notes, and snippets.

@mkchoi212
Created November 30, 2018 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkchoi212/94357280a817cd76527958fe2bd57ce0 to your computer and use it in GitHub Desktop.
Save mkchoi212/94357280a817cd76527958fe2bd57ce0 to your computer and use it in GitHub Desktop.
import numpy as np
HORIZONTAL = 1
VERTICAL = 0
def first_nonzero(arr, axis, invalid_val=-1):
mask = arr!=0
return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)
def last_nonzero(arr, axis, invalid_val=-1):
mask = arr!=0
val = arr.shape[axis] - np.flip(mask, axis=axis).argmax(axis=axis) - 1
return np.where(mask.any(axis=axis), val, invalid_val)
arr = np.array(
[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 0, 0]
])
first_hor = first_nonzero(arr, axis=HORIZONTAL, invalid_val=np.nan)
first_vert = first_nonzero(arr, axis=VERTICAL, invalid_val=np.nan)
top = np.nanmin(first_vert)
left = np.nanmin(first_hor)
last_hor = last_nonzero(arr, axis=HORIZONTAL, invalid_val=np.nan)
last_vert = last_nonzero(arr, axis=VERTICAL, invalid_val=np.nan)
bottom = np.nanmax(last_vert)
right = np.nanmax(last_hor)
print("top, left, bottom, right")
print(top, left, bottom, right)
x = (right + left) / 2
y = (bottom + top) / 2
print(x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment