I need to provide a Python script for video detection, allowing for real-time viewing through a webcam or a video file. I should focus on handling command-line arguments, like using python detect_video.py --source 0 or a specific video path. Since the user didn't request a detailed explanation, I'll keep it straightforward with the necessary code and brief usage notes. I'll mention dependencies and follow up with the core coding elements required for this task.Providing Python script for video detection
I need to share a Python script that uses OpenCV and the YOLO model for real-time video detection. The script includes handling command-line arguments for choosing the source, like a webcam or video file. It seems important to clarify how to access class names correctly from the YOLO model, as in the Ultralytics YOLO v8 implementation, they can be retrieved directly from model.names. I'll ensure the code is concise and functional, focusing on essential parts for effective usage.Clarifying YOLO implementation for detection
I'm focusing on the details for implementing the YOLO detection using the Ultralytics library. Each r.names provides the class names, so I can access them using r.names[int(cls)]. It's unclear whether to emphasize YOLOv5 since the Ultralytics library also supports it. My plan is to include functionality for using either a video file or a webcam through command-line arguments while considering resizing. I want to make sure everything works smoothly with the script. I'll also highlight that it requires installing specific libraries.Streamlining the YOLO detection code
I’m refining the implementation for YOLO detection. Instead of using stream=True, I can simply call results = model(frame)[0] to get one frame at a time since the model is called repeatedly. While older versions required model.predict(source=frame, conf=0.5), the current Ultralytics version allows just model(frame), which is actually preferred.
Now, to extract box details, I can convert the coordinates with x1, y1, x2, y2 = map(int, box.xyxy[0]) and similarly gather confidence and class information. Finally, I’ll prepare to draw these results.Finalizing the YOLO detection script
I’m wrapping up the Python script for YOLO object detection that allows users to run detection either from a webcam or a video file. I made sure to extract the necessary box coordinates and confidence values correctly, using methods like .int().tolist(). The script will display bounding boxes and labels along with FPS. I've set up command-line arguments for easy customization. I also mentioned installation requirements and usage steps, ensuring everything is concise and clear for users. Now, I’m preparing to output the final script!Preparing the final answer
I want to make sure I include details on customizing the script while keeping the explanation straightforward. It's crucial to have correct indentation and format for readability, so I'll double-check that. My goal is to present a clean final version of the Python script with just the necessary information, avoiding any extra fluff. This way, the user can easily understand and implement the code without confusion. Let's get this into a polished format! Below is a simple, self-contained Python script that performs real‑time object detection on a video stream (webcam, video file, or IP camera) using YOLO (Ultralytics YOLOv8).
If you want this adapted to an older YOLO version (e.g. YOLOv3 via OpenCV DNN) or integrated into a specific application framework, say what environment you’re targeting and I can adjust the script.
import argparse
import time
import cv2
from ultralytics import YOLO
def run(source, model_path="yolov8n.pt", conf_thres=0.5):
# Load YOLO model (yolov8n.pt is small & fast; replace with your own model if needed)
model = YOLO(model_path)
# Open video source
cap = cv2.VideoCapture(source)
if not cap.isOpened():
print(f"Error: could not open video source {source}")
return
prev_time = 0.0
while True:
ret, frame = cap.read()
if not ret:
print("End of stream or cannot read frame.")
break
# Run YOLO inference on the frame
results = model(frame, conf=conf_thres)[0] # first (and only) result
# Draw detections
for box in results.boxes:
# Bounding box
x1, y1, x2, y2 = box.xyxy[0].int().tolist()
# Confidence
conf = float(box.conf[0])
# Class ID and name
cls_id = int(box.cls[0])
cls_name = results.names[cls_id]
# Draw rectangle
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Label text (class + confidence)
label = f"{cls_name} {conf:.2f}"
(tw, th), _ = cv2.getTextSize(
label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1
)
# Background for label
cv2.rectangle(
frame,
(x1, y1 - th - 4),
(x1 + tw, y1),
(0, 255, 0),
-1,
)
# Put text on top of the box
cv2.putText(
frame,
label,
(x1, y1 - 2),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0, 0),
1,
cv2.LINE_AA,
)
# FPS calculation
curr_time = time.time()
fps = 1.0 / (curr_time - prev_time) if prev_time else 0.0
prev_time = curr_time
cv2.putText(
frame,
f"FPS: {fps:.1f}",
(10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 255, 255),
2,
cv2.LINE_AA,
)
# Show the frame
cv2.imshow("YOLO Object Detection", frame)
# Press 'q' to quit
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Real-time object detection on video streams using YOLO."
)
parser.add_argument(
"--source",
type=str,
default="0",
help="Video source: '0' for default webcam, path to video file, or stream URL (RTSP/HTTP).",
)
parser.add_argument(
"--model",
type=str,
default="yolov8n.pt",
help="YOLO model name or path (e.g., yolov8n.pt, yolov8s.pt, or your custom .pt).",
)
parser.add_argument(
"--conf",
type=float,
default=0.5,
help="Confidence threshold between 0 and 1.",
)
args = parser.parse_args()
# Convert numeric string to int for webcams (e.g., "0" -> 0)
src = int(args.source) if args.source.isdigit() else args.source
run(src, args.model, args.conf)