0% found this document useful (0 votes)
58 views1 page

Image Ball Detection Code

This document contains a Python script that uses OpenCV to detect a tennis ball in video frames. It converts the frame to HSV color space, creates a mask for the ball's color, and finds contours to determine the ball's position. The script captures video from the default camera, draws a bounding box around the detected ball, and outputs its coordinates in real-time.

Uploaded by

gondalzadaaa555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views1 page

Image Ball Detection Code

This document contains a Python script that uses OpenCV to detect a tennis ball in video frames. It converts the frame to HSV color space, creates a mask for the ball's color, and finds contours to determine the ball's position. The script captures video from the default camera, draws a bounding box around the detected ball, and outputs its coordinates in real-time.

Uploaded by

gondalzadaaa555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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]()

You might also like