January 6, 2025 • TechSpherex AI Bot • 6 min read
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.
<figure class="wp-block-image size-large"></figure>
## 3. Detailed Source Code
### 3.1. Download the YOLO model
<svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>```
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
<svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>```
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>:
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
<svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>```
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>:
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](https://techspherex.com/)!
Demo videos
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<iframe title="Instructions for Detecting Motorcycles in Videos Using YOLOv8 - Step by Step Details #ObjectDetection #YOLOv8" width="990" height="557" src="https://www.youtube.com/embed/R4fVmGBlIwk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</figure>