Skip to content

January 6, 2025 • TechSpherex AI Bot • 4 min read

Detect Motorcycles in Videos Using YOLOv8: Detailed Instructions

Detect Motorcycles in Videos Using YOLOv8: Detailed Instructions

In this article, we will learn how to detect motorbikes in videos using the YOLOv8 model. YOLO (You Only Look Once) is one of the fastest object detection and recognition technologies today, suitable for application in many real-life situations such as traffic, surveillance, and self-driving cars.

Summary

  • Language: Python

  • Libraries: OpenCV, PyTorch, YOLOv8

  • Result: Recognize motorbikes in videos in real time and display results.

1. Preparation Requirements

Necessary tools:

  • Python is installed (version >= 3.8).

  • OpenCV library for video processing.

  • PyTorch library to load models.

  • “Ultralytics” library used for YOLOv8.

Install library:

Run the following command in terminal to install the required libraries:

pip install opencv-python torch ultralytics

2. Illustrative Results

Before looking at the source code, let’s see the simulation results of motorcycle recognition in the video.

3. Detailed Source Code

3.1. Download the YOLO model

from ultralytics import YOLO

def load_model(model_path):
    """
    Load the YOLO model from the specified path.
    """
    return YOLO(model_path)

3.2. Process Each Video Frame

import cv2

def process_frame(frame, model, confidence_threshold):
"""
Process a frame and detect motorbikes using the YOLO model.

    Args:
        frame (ndarray): Frame to process.
        model (YOLO): YOLO model for detection.
        confidence_threshold (float): Confidence threshold to filter results.

Returns:
tuple: Frame processed, number of detected motorbikes.
"""
results = model(frame)
motorbike_count = 0
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
font_color = (0, 255, 0)
thickness = 1

for result in results:
boxes = result.boxes # Bounding boxes
for box in boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0])
class_id = int(box.cls[0])
confidence = float(box.conf[0])

class_name = model.names[class_id]

if class_name.lower() == 'motorcycle' and confidence >= confidence_threshold:
motorbike_count += 1
label = f"{class_name} {confidence:.2f}"
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, label, (x1, y1 - 10), font, font_scale, font_color, thickness)

return frame, motorbike_count

3.3. Video Display With Detection

import cv2

def display_video(video_path, model, confidence_threshold):
    """
    Video display with real-time motorcycle detection and counting.

Args:
        video_path (str): Path to video file.
        model (YOLO): YOLO model for object detection.
        confidence_threshold (float): Confidence threshold to filter results.
    """
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print("Error: Cannot open video file.")
        return

font = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 2
    font_color = (0, 255, 0)
    thickness = 2

whileTrue:
        ret, frame = cap.read()
        if not returned:
            break. break

frame, motorbike_count = process_frame(frame, model, confidence_threshold)

cv2.putText(frame, f"Motorbikes: {motorbike_count}", (10, 50), font, font_scale, font_color, thickness)

output_width, output_height = 1080, 720
        frame = cv2.resize(frame, (output_width, output_height))
        cv2.imshow('YOLOv8 Detection', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):
            break. break

cap.release()
    cv2.destroyAllWindows()

3.4. Connect RTSP IP Camera

If you want to detect motorcycles in live video from an IP camera, change video_path with the camera’s RTSP URL:

rtsp_url = 'rtsp://username:password@<ip_address>:<port>/path'

def display_rtsp(rtsp_url, model, confidence_threshold):
"""
Displays live video from RTSP IP cameras and detects motorbikes.

Args:
rtsp_url (str): RTSP URL of IP camera.
model (YOLO): YOLO model for object detection.
confidence_threshold (float): Confidence threshold to filter results.
"""
cap = cv2.VideoCapture(rtsp_url)
if not cap.isOpened():
print("Error: Unable to connect to IP camera.")
return

font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 2
font_color = (0, 255, 0)
thickness = 2

whileTrue:
ret, frame = cap.read()
if not returned:
break. break

frame, motorbike_count = process_frame(frame, model, confidence_threshold)

cv2.putText(frame, f"Motorbikes: {motorbike_count}", (10, 50), font, font_scale, font_color, thickness)

output_width, output_height = 1080, 720
frame = cv2.resize(frame, (output_width, output_height))
cv2.imshow('YOLOv8 RTSP Detection', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):
break. break

cap.release()
cv2.destroyAllWindows()

3.5. Main Function Runs the Program

Use videos

if __name__ == "__main__":
    model_path = '{File}.pt' # Get from model yolo or train yourself
    video_path = '{File}.mp4' # video file
    confidence_threshold = 0.3

print("Loading YOLO model...")
    model = load_model(model_path)

print("Starting video detection...")
    display_video(video_path, model, confidence_threshold)

Use IP Cameras

if **name** == "**main**":
model_path = 'model/yolov8x.pt'
rtsp_url = 'rtsp://username:password@<ip_address>:<port>/path'
confidence_threshold = 0.3

print("Loading YOLO model...")
model = load_model(model_path)

print("Starting RTSP video detection...")
display_rtsp(rtsp_url, model, confidence_threshold)

4. Conclusion

With YOLOv8, you can quickly develop a program to detect motorcycles in video, serving many practical applications. To illustrate, share your experience with us at TechSphereX!

Demo videos

Telegram Zalo Facebook Messenger