Created
January 9, 2019 05:13
-
-
Save garybradski/2a4e438f444eeb1be95942b7c5ea0842 to your computer and use it in GitHub Desktop.
Convolve to find axis aligned corners. Also, find nearest pixel
This file contains hidden or 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
def convert_bin_img_to_corners(img): | |
''' | |
Mark corners with bias being pixels origin as (x,y): (0.5, 0.5) | |
:param img: Binary image of field | |
:return: Image of corners marked with 255, all else is 0 | |
''' | |
kernel = np.ones( | |
(2, 2), np.float32) # Make convolution kernel 2x2 of 0.25s | |
ret, img_thresh = cv2.threshold( | |
img, 1, 1, cv2.THRESH_BINARY) # Make img into [0,1] | |
dst = cv2.filter2D( | |
img_thresh, -1, kernel, | |
anchor=(0, 0)) # convolving marks corners with a 1 or a 3 | |
idx = (dst == 2) + (dst == 4) # Get rid of 2s and 4s in the dst image | |
dst[idx] = 0 | |
idx2 = (dst > 0) # set dst to [0,255] | |
dst[idx2] = 255 | |
nonzero = cv2.findNonZero(dst) | |
return dst | |
def find_nearest_white(img, xy_point): | |
''' | |
Given an image (usually [0,1] or [0,255]) find the nearest non-zero pixel to xy_point | |
:param img: Image, usually binarized to [0,1] or [0,255] | |
:param xy_point: Tuple of (x,y) | |
:return: Index (x,y) tuple of nearest non-zero point. | |
''' | |
nonzero = cv2.findNonZero(img) | |
distances = np.sqrt((nonzero[:, :, 0] - xy_point[0]) ** 2 + (nonzero[:, :, 1] - xy_point[1]) ** 2) | |
nearest_index = np.argmin(distances) | |
return nonzero[nearest_index][0] + 0.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment