“Special thanks to Murtaza Hassan for not only creating the cvzone library, a user-friendly computer vision library built on top of OpenCV, but also for providing insightful tutorials that make learning computer vision easier. I followed one of his tutorials to implement the concepts discussed in this blog. His work has greatly contributed to making computer vision more accessible for developers and researchers. To learn more about Murtaza Hassan and his projects, you can visit his YouTube channel or check out the cvzone GitHub repository.”
This blog post is a written version of one of his tutorials, where I followed his implementation step by step.
What is Polynomial regression?
Polynomial regression is a type of regression analysis where the relationship between the independent variable (input) and the dependent variable (output) is modeled as an nth-degree polynomial function. In other words, it is a way to fit a curve to the data points by using a polynomial equation.
In a simple linear regression, the relationship between the independent and dependent variables is modeled as a straight line. However, sometimes the relationship between the variables is more complex and cannot be represented by a straight line. Polynomial regression is used in such cases where the relationship is not linear.
The degree of the polynomial determines the complexity of the curve that is fitted to the data. For example, a second-degree polynomial (quadratic) can fit a parabolic curve to the data, while a third-degree polynomial (cubic) can fit a more complex curve.
Polynomial regression can be used in many areas of data analysis, including finance, physics, engineering, and social sciences, to name a few. It is an effective technique for modeling non-linear relationships and making predictions based on the data.
Introduction: In this tutorial, we will walk through a Python script that predicts the trajectory of a colored ball and determines if it will make a “basket” or not. We will use OpenCV, a powerful open-source computer vision library, and cvzone, a simple computer vision library built on top of OpenCV. This script imports a video and processes it frame by frame, identifying the colored ball’s position and predicting its trajectory using polynomial regression.
Requirements: To follow this tutorial, you will need to have Python installed and the following libraries:
- OpenCV (
opencv-python
): Install withpip install opencv-python
- cvzone: Install with
pip install cvzone
Let’s break down the code into smaller sections and explain each part in detail.
Step 1: Import necessary libraries First, we need to import the required libraries:
import math
import cv2
import cvzone
from cvzone.ColorModule import ColorFinder
import numpy as np
Step 2: Set up the video source We will use OpenCV’s VideoCapture class to read frames from a video file:
video_src = cv2.VideoCapture('Videos/vid (1).mp4')
Step 3: Instantiate the ColorFinder object To detect the colored ball in the video, we will use the ColorFinder class from cvzone:
color_finder = ColorFinder(False)
hsv_params = {'hmin': 8, 'smin': 96, 'vmin': 115, 'hmax': 14, 'smax': 255, 'vmax': 255}
Step 4: Initialize variables We will create some variables to store the positions of the ball and the range of the x-axis:
x_positions, y_positions = [], []
x_range = [i for i in range(0, 1300)]
predicted = False
Step 5: Read and process frames We will loop through each frame in the video, perform ball detection, and store the ball’s x and y positions:
while True:
# Capture the frame
ret, frame = video_src.read()
frame = frame[0:900, :]
# Locate the colored ball
colored_frame, ball_mask = color_finder.update(frame, hsv_params)
frame_contours, ball_contours = cvzone.findContours(frame, ball_mask, minArea=500)
if ball_contours:
x_positions.append(ball_contours[0]['center'][0])
y_positions.append(ball_contours[0]['center'][1])
Step 6: Perform polynomial regression and draw trajectory We will use NumPy’s polyfit()
function to perform polynomial regression and draw the ball’s trajectory:
if x_positions:
# Perform polynomial regression (y = Ax^2 + Bx + C)
A, B, C = np.polyfit(x_positions, y_positions, 2)
for i, (x, y) in enumerate(zip(x_positions, y_positions)):
position = (x, y)
cv2.circle(frame_contours, position, 10, (0, 255, 0), cv2.FILLED)
if i == 0:
cv2.line(frame_contours, position, position, (0, 255, 0), 5)
else:
cv2.line(frame_contours, position, (x_positions[i - 1], y_positions[i - 1]), (0, 255, 0), 5)
for x in x_range:
y = int(A * x ** 2 + B * x + C)
cv2.circle(frame_contours, (x, y), 2, (255, 0, 255), cv2.FILLED)
Step 7: Make a prediction and display the result We will make a prediction based on the polynomial equation and display “Basket” or “No Basket” on the video frame:
if len(x_positions) < 10:
# Make a prediction
a, b, c = A, B, C - 590
x_solution = int((-b - math.sqrt(b ** 2 - (4 * a * c))) / (2 * a))
predicted = 330 < x_solution < 430
if predicted:
cvzone.putTextRect(frame_contours, "Basket", (50, 150), scale=5, thickness=5, colorR=(0, 200, 0), offset=20)
else:
cvzone.putTextRect(frame_contours, "No Basket", (50, 150), scale=5, thickness=5, colorR=(0, 0, 200), offset=20)
Step 8: Show the result Finally, we will resize the frame and display the result in a window:
# Show the result
frame_contours = cv2.resize(frame_contours, (0, 0), None, 0.7, 0.7)
cv2.imshow("ColoredFrame", frame_contours)
cv2.waitKey(100)
Conclusion: In this tutorial, we have walked through a Python script that predicts the trajectory of a colored ball and determines if it will make a “basket” or not. We used OpenCV and cvzone to process video frames, detect the ball’s position, and predict its trajectory using polynomial regression. This script can be easily adapted to analyze various scenarios, detect other objects, or predict different outcomes based on the trajectory of objects.