Created
November 30, 2018 00:54
-
-
Save mkchoi212/94357280a817cd76527958fe2bd57ce0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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