1. Understand the Goal: The user wants a Python script to detect objects in video streams using YOLO (You Only Look Once).
Identify Key Components:
Language: Python.
Core Task: Object Detection.
Input Source: Video streams (could be a webcam, a video file, or an RTSP stream).
Model: YOLO (specifically, the latest and easiest-to-use versions are usually YOLOv8 or YOLOv5, with YOLOv8 via Ultralytics being the current standard for ease of use).
Choose the Right Library:
Option A: Darknet (Original C implementation). Too complex for a general request.
Option B: PyTorch with YOLOv5. Good, but requires a bit more boilerplate code (loading models, handling image processing manually).
Option C: Ultralytics (YOLOv8). This is the best choice for a modern, "Pythonic" script. It handles downloads, preprocessing, and inference with very few lines of code. It's robust and widely used.
Open the video source (0 for webcam or a file path).
Loop through frames.
Run inference on each frame.
Visualize results (draw bounding boxes).
Display the output.
Handle exit conditions (press 'q' to quit).
Drafting the Code (Mental or Scratchpad):
Imports:
python
import cv2
from ultralytics import YOLO
Loading Model:
python
model = YOLO('yolov8n.pt') # 'n' is nano, fastest for real-time
Video Capture:
python
cap = cv2.VideoCapture(0) # Or path
Loop:
python
while cap.isOpened():
ret, frame = cap.read()
if not ret: break
# Inference
results = model(frame)
# Visualization
annotated_frame = results[0].plot()
# Show
cv2.imshow("YOLO", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'): break
Cleanup:
python
cap.release()
cv2.destroyAllWindows()
Refining and Expanding:
The basic script is good, but I should make it user-friendly.
Add comments explaining what's happening.
Add a way to switch between Webcam and File easily (maybe a variable at the top or argparse). For a simple tutorial, a variable at the top is usually easier to read. Let's stick to Webcam as the default but mention how to change it.
Mention dependencies clearly.
Explain why I chose YOLOv8 (ease of use).
Addressing Potential Issues:
Performance:yolov8n.pt (Nano) is best for CPU/webcam real-time. I should explicitly mention this.
First Run: The library will auto-download the weights. I need to mention this so the user isn't surprised by the delay.
Final Code Structure:
Prerequisites: List pip install ultralytics opencv-python.
The Script: The complete, runnable code.
Explanation: Breakdown of the code sections.
Customization: How to use a video file, how to change model size.
Self-Correction/Review during drafting:
Wait, does ultralytics handle the loop internally? Yes, model.predict(source='0', show=True) does, but writing the cv2 loop explicitly gives the user more control (e.g., if they want to save frames or log specific detections later). I will provide the explicit cv2 loop approach as it's more "script-like" and educational.
Final Output Generation: (This matches the provided good response).
Use yolov8n.pt.
Use cv2.VideoCapture.
Use results[0].plot() because it's the easiest way to visualize.
Add the standard q to quit logic.
Adding YOLOv5 option? No, keep it simple. YOLOv8 is the current standard recommendation from Ultralytics. It's backward compatible in concept but better in implementation.
Formatting: Use code blocks, bold text for emphasis, and clear steps.
(Self-Correction during final output generation): Ensure I import cv2. Even though ultralytics uses it, we need it for VideoCapture and imshow.
Let's write the response.
This guide uses YOLOv8, the latest state-of-the-art version from Ultralytics. It is the easiest way to get started because the library handles model downloads, image processing, and bounding box rendering internally.
1. Prerequisites
You will need Python installed. Open your terminal or command prompt and install the following libraries:
bash
pip install opencv-python ultralytics
2. The Python Script
Create a file named detect.py and paste the following code.
This script handles three scenarios automatically:
Webcam: Uses 0 as the source.
Video File: Uses the path to the file (e.g., video.mp4).
import cv2
from ultralytics import YOLO
def main():
# ---------------------------------------------------------
# CONFIGURATION
# ---------------------------------------------------------
# 1. Load the YOLO model
# Options: 'yolov8n.pt' (fastest), 'yolov8s.pt', 'yolov8m.pt', 'yolov8l.pt', 'yolov8x.pt' (most accurate)
# The first run will automatically download the weights file.
model = YOLO('yolov8n.pt')
# 2. Define Video Source
# Use 0 for default webcam, or replace with "path/to/video.mp4"
video_source = 0
# ---------------------------------------------------------
# VIDEO PROCESSING LOOP
# ---------------------------------------------------------
# Open the video source
cap = cv2.VideoCapture(video_source)
if not cap.isOpened():
print("Error: Could not open video source.")
return
print("Press 'q' to quit.")
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
# If frame reading was not successful, break the loop (end of video)
if not success:
break
# -----------------------------------------------------
# RUN YOLO DETECTION
# -----------------------------------------------------
# The 'stream=True' argument creates a generator for memory efficiency.
# 'verbose=False' stops the console from printing detection details every frame.
results = model(frame, stream=True, verbose=False)
# Process results
for r in results:
# The 'plot()' method draws the bounding boxes and labels on the frame automatically
annotated_frame = r.plot()
# -----------------------------------------------------
# DISPLAY OUTPUT
# -----------------------------------------------------
cv2.imshow("YOLOv8 Detection", annotated_frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
3. How it Works
model = YOLO('yolov8n.pt'): This initializes the model. We use yolov8n (Nano) because it is the fastest and lightest, making it ideal for running on a standard laptop CPU or GPU. If you want higher accuracy and have a powerful GPU, change n to s, m, or x.
cv2.VideoCapture(0): This accesses your default computer webcam. If you have a video file (like traffic.mp4), change 0 to "traffic.mp4".
model(frame): This performs the actual object detection. It converts the image to a tensor, runs it through the neural network, and returns coordinates for 80 different object classes (COCO dataset: person, car, dog, etc.).
annotated_frame = r.plot(): This is a unique feature of the Ultralytics library. Instead of manually drawing rectangles and text using OpenCV functions (which is tedious), .plot() handles all the drawing for you with nice colors and labels.
4. Advanced: Filter Specific Objects (e.g., Only People)
If you don't want to detect everything (like cars and apples) and only want to detect people, you can modify the loop section:
python
while cap.isOpened():
success, frame = cap.read()
if not success:
break
# Run detection
results = model(frame, stream=True, verbose=False)
for r in results:
# Get the boxes and original frame
boxes = r.boxes
for box in boxes:
# 1. Check Class ID
# Class ID 0 is usually 'person' in the COCO dataset
cls_id = int(box.cls[0])
if cls_id == 0:
# 2. Manually Draw if you want custom filtering,
# or just use r.plot() if you are okay with the library drawing everything.
# Here is how you draw manually:
x1, y1, x2, y2 = map(int, box.xyxy[0])
confidence = round(float(box.conf[0]), 2)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f"Person {confidence}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
cv2.imshow("YOLOv8 Detection", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
5. Troubleshooting
Webcam Lag: If the video is very slow, ensure you are using yolov8n.pt. The larger models (like yolov8x.pt) are too heavy for real-time CPU processing.
Black Window: Ensure your webcam is not being used by another application (Zoom, Teams, etc.).
Import Error: If you get ModuleNotFoundError: No module named 'ultralytics', run the pip install command again.