I am working on using video from a football (soccer) match and try to map the frames to a top view of the pitch using homography. I have started to get find all the white lines from the frames using both Hough lines as well as using the line segment detector, where the line segment detector seems to work slightly better. See my code and examples below:
import cv2
import numpy as np
cv2.imread("frame-27.jpg")
hsv = cv2.cvtColor(frame, cv2.COLOR_RGB2HSV)
mask_green = cv2.inRange(hsv, (36, 25, 25), (86, 255, 255)) # green mask to select only the field
frame_masked = cv2.bitwise_and(frame, frame, mask=mask_green)
gray = cv2.cvtColor(frame_masked, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
canny = cv2.Canny(gray, 50, 150, apertureSize=3)
# Hough line detection
lines = cv2.HoughLinesP(canny, 1, np.pi / 180, 50, None, 50, 20)
# Line segment detection
lines_lsd = lsd.detect(canny)[0]
This uses this input frame

and returns this image for the Hough lines

and this image for the line segment detection.

My question is twofold: (1) any ideas on how I can further refine the line detection (i.e. decrease false positives such as lines around players and outside of the field) and (2) a good way to use the detection lines to create a homography so I can map the frame to a higher overview of the field (like this). Any help is greatly appreciated!


