"""
Real-time Object Detection in Video Streams using YOLOv8
========================================================
This script uses Ultralytics YOLOv8 for detecting objects in a video stream.
It supports:
- Webcam (source=0)
- Video file (source='path/to/video.mp4')
Installation:
pip install ultralytics opencv-python
Usage:
python yolo_video_detection.py --source 0 # Webcam
python yolo_video_detection.py --source video.mp4 # Video file
"""
import cv2
import argparse
from ultralytics import YOLO
def main(source=0, model_path='yolov8n.pt', conf=0.25, save=False):
# Load the YOLOv8 model (downloads automatically if not present)
model = YOLO(model_path)
# Open video capture (0 for webcam, or path to video file)
cap = cv2.VideoCapture(source)
if not cap.isOpened():
print(f"Error: Could not open video source '{source}'")
return
# Optional: Setup video writer for saving output
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = None
if save:
out_path = 'output.mp4'
out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
print(f"Saving output to {out_path}")
print("Press 'q' to quit.")
while True:
ret, frame = cap.read()
if not ret:
print("End of video or capture failed.")
break
# Run YOLO inference on the frame
results = model(frame, conf=conf, verbose=False)
# Draw bounding boxes, labels, and confidences on the frame
annotated_frame = results[0].plot()
# Display the frame
cv2.imshow('YOLOv8 Object Detection', annotated_frame)
# Optional: Save the annotated frame
if save and out:
out.write(annotated_frame)
# Break on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Cleanup
cap.release()
if out:
out.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="YOLOv8 Video Object Detection")
parser.add_argument('--source', type=str, default=0, help='Video source (0 for webcam, path for file)')
parser.add_argument('--model', type=str, default='yolov8n.pt', help='YOLO model path (e.g., yolov8n.pt, yolov8s.pt)')
parser.add_argument('--conf', type=float, default=0.25, help='Confidence threshold (0.0-1.0)')
parser.add_argument('--save', action='store_true', help='Save output video as output.mp4')
args = parser.parse_args()
main(args.source, args.model, args.conf, args.save)
Real-time detection: Processes frames at high speed (model-dependent).
Customizable: Adjust confidence threshold, model size (nano yolov8n.pt is fastest, yolov8x.pt is most accurate).
COCO classes: Detects 80 common objects (person, car, dog, etc.).
Save output: Use --save to record annotated video.
Efficient: Uses YOLOv8's optimized inference.
This script is production-ready and handles errors gracefully. For custom models or classes, check Ultralytics docs. Let me know if you need tweaks! 🕵️♂️