I'm trying to find an efficient, non-intensive way to detect tennis court lines. Essentially, a tennis broadcast has static camerawork and the model does not need to be robust like it would for other sports (basket-ball, hockey, etc.). Leveraging the long, static shot, I've been able to use Hough lines to get halfway there. What I'm thinking through now is a way to stitch together a polygon based on a sketch of it. From these red and green lines, I'd like to sketch the most likely polygon, in this case it should just fill out the exterior of the court. Does OpenCV have such a function?
# import the necessary packages
import math
import numpy as np
import cv2
# load the image
img = cv2.imread("assets/game-frames/clay-m-2012-71-870.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 100, apertureSize = 3)
lines = cv2.HoughLinesP(edges, 2, np.pi/180, 100, minLineLength=20, maxLineGap=10)
# Draw lines on the image
for line in lines:
x1, y1, x2, y2 = line[0]
length = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
if x1 == x2 or x1 < 10 or y1 < 100:
continue
elif abs((y2 - y1)/(x2 - x1)) > 1.5 and abs((y2 - y1)/(x2 - x1)) < 3 and length > 200:
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1)
elif abs((y2 - y1)/(x2 - x1)) < 0.02 and ((x1 > 44 and x1 < 685) and (x2 < 685 and x2 > 44)) and ((y1 > 110 and y1 < 120) or (y1 > 400 and y1 < 420)):
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 1)
else:
continue
cv2.imshow("Detected Lines (in red) - Standard Hough Line Transform", img)
cv2.waitKey(0)