Create a Football Players Detection using YOLO v8 model and Open CV in Colab
I want to share with you how easy to create an object detection Model with YOLO using data sets from RoboFlow, the main but of our Code is to create a model that can distinguish the players from video and generate an output video with the players tagged
first of all, we install the necessary Libraries:
%pip install ultralytics
!pip install torch torchvision -U
!pip3 install opencv-python
After the installation we download the data set from RoboFlow
!curl -L "https://universe.roboflow.com/ds/sO3gyQBJYk?key=u4DrcatDg6" > roboflow.zip; unzip roboflow.zip; rm roboflow.zip
this command will extract the dataset folder for our model training
Next, we execute this code :
from ultralytics import YOLO
import torch
import os
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# TRAINING
if __name__ == '__main__':
results = model.train(data="data.yaml", epochs=50, patience=5)
which will create a Yolov8 model and execute the training function with 3 parameters
领英推荐
After running the training function we will get a runs folder that contains all the trained models as a result :
The only Model we need is the "best.pt" so that we can use it in our code as follows:
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
# model = YOLO('yolov8n.pt') ### Pre-trained weights
model = YOLO('runs/detect/train5/weights/best.pt') ### weights from trained model
# Open the video file
video_path = r"est-jsk.mp4"
cap = cv2.VideoCapture(video_path)
# Default resolutions of the frame are obtained.
#The default resolutions are system dependent.
# We convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('ResultVideo.mp4',cv2.VideoWriter_fourcc('M','J','P','G'), 20, (frame_width,frame_height))
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True, show=False, tracker="botsort.yaml")
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Write the frame into the file 'ResultVideo.mp4'
out.write(annotated_frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
# Break the loop if the end of the video is reached
break
# Release the video capture object and close the display window
cap.release()
out.release()