Skip to content

Instantly share code, notes, and snippets.

@arhanjain
Created May 30, 2022 23:36
Show Gist options
  • Save arhanjain/676a3ee40242bb7657e249928eb71086 to your computer and use it in GitHub Desktop.
Save arhanjain/676a3ee40242bb7657e249928eb71086 to your computer and use it in GitHub Desktop.
def get_playfield_corners(frame):
"""Identifies coordinates of the playfield corners from the frame.
Parameters
----------
frame : numpy.ndarray
The frame read in by the VideoCapture
Returns
-------
corners_coordinates : list
List of coordinates of the identified playfield corners
"""
corner_coordinates = []
blurred_frame = cv2.GaussianBlur(frame, config.GAUSSIAN_BLUR_KERNEL_SIZE, 0)
# Change to HSV colorspace for color thresholding
hsv = cv2.cvtColor(blurred_frame, cv2.COLOR_BGR2HSV)
# Split frame into two parts to analyze different colors and reduce noise
[top, bottom] = np.split(hsv, 2, axis=0)
# Color threshold masks (top of playfield has yellow corner markers and bottom of playfield has blue corner
# markers)
yellow_mask = cv2.inRange(top, np.array(config.CORNER_LOWER_YELLOW), np.array(config.CORNER_UPPER_YELLOW))
blue_mask = cv2.inRange(bottom, np.array(config.CORNER_LOWER_BLUE), np.array(config.CORNER_UPPER_BLUE))
# Combining masks to retrieve full frame mask
mask = np.vstack((yellow_mask, blue_mask))
# Extract targeted colors from original frame in grayscale
extracted_colors = cv2.bitwise_and(blurred_frame, blurred_frame, mask=mask)
extracted_colors_gray = cv2.cvtColor(extracted_colors, cv2.COLOR_BGR2GRAY)
# Find contours in the image
contours, _ = cv2.findContours(extracted_colors_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
area = cv2.contourArea(c)
perim = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, config.CONTOUR_APPROXIMATION_COEFFICIENT * perim, True)
if config.CORNER_CONTOUR_AREA_MIN < area < config.CORNER_CONTOUR_AREA_MAX and len(approx) == 4:
m = cv2.moments(c)
x = int(m["m10"] / m["m00"])
y = int(m["m01"] / m["m00"])
corner_coordinates.append([x, y])
return corner_coordinates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment