import cv2
import numpy as np
def detect_ball(frame):
# Convert the frame to HSV (Hue, Saturation, Value) color space
hsv = [Link](frame, cv2.COLOR_BGR2HSV)
# Define the range of the color of the tennis ball in HSV
lower_color = [Link]([29, 86, 6]) # Lower bound of the color
upper_color = [Link]([64, 255, 255]) # Upper bound of the color
# Create a mask for the tennis ball color
mask = [Link](hsv, lower_color, upper_color)
# Find contours in the mask
contours, _ = [Link](mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if contours:
# Find the largest contour (assuming it's the tennis ball)
c = max(contours, key=[Link])
x, y, w, h = [Link](c)
return x, y, w, h
return None
# Initialize the video capture
cap = [Link](0) # 0 is the default camera
while True:
# Capture frame-by-frame
ret, frame = [Link]()
if not ret:
break
# Detect the ball
ball_position = detect_ball(frame)
if ball_position:
x, y, w, h = ball_position
# Draw a bounding box around the ball
[Link](frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Output the real-time position coordinates of the tennis ball
print(f"Tennis ball position: x={x}, y={y}, width={w}, height={h}")
# Display the resulting frame
[Link]('Tennis Ball Tracker', frame)
# Break the loop on 'q' key press
if [Link](1) & 0xFF == ord('q'):
break
# Release the capture and close windows
[Link]()
[Link]()