Skip to content

Instantly share code, notes, and snippets.

@nickodell
Created October 30, 2022 01:36
Show Gist options
  • Save nickodell/d45a50de665cbb38c80a3b0acadbd3d1 to your computer and use it in GitHub Desktop.
Save nickodell/d45a50de665cbb38c80a3b0acadbd3d1 to your computer and use it in GitHub Desktop.
filter tennis court
import numpy as np
import cv2
import scipy.ndimage
import matplotlib.pyplot as plt
img = cv2.imread('HjJto.jpg')
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
blue = np.array((81, 93, 147)).reshape(1, 1, 3)
rmse = np.sqrt(((img_rgb - blue)**2).mean(axis=2))
rmse = scipy.ndimage.gaussian_filter(rmse, sigma=5)
rmse = scipy.ndimage.minimum_filter(rmse, size=15)
rmse = rmse.astype('uint16')
_, rmse_thresh = cv2.threshold(rmse,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
rmse_thresh = (rmse_thresh == 0).astype('uint8')
contours, hierarchy = cv2.findContours(rmse_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Sort contours by area
contours = sorted(contours, key=cv2.contourArea, reverse=True)
# contours[0] is the largest contour
# Take the convex hull of the largest contour
hull = cv2.convexHull(contours[0])
# Simplify the polygon
perim = cv2.arcLength(contours[0], True)
epsilon = 0.02*perim
hull = cv2.approxPolyDP(hull, epsilon, True)
hull = np.concatenate((hull, hull[0, :, :].reshape(1, 1, 2)))
hull
x = hull[:, 0, 0]
y = hull[:, 0, 1]
plt.plot(x, y, color='red')
plt.imshow(img_rgb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment