I'm starting by establishing the core objective: building a Python script for object detection via YOLO on video streams. Next, I'm identifying the foundational elements – Python as the language, and YOLO as the chosen methodology. The focus is now on the practical implementation using these.
Structuring the Script
I've sketched the structure. First, I'll install the required libraries – ultralytics and opencv-python. Then, I'll write the imports, followed by loading the YOLO model. The video stream setup will come next, and then the main loop for frame processing and display. I'll need to define how to handle exit.
Refining and Enhancing
Now, I'm focusing on the script's usability. I'm considering ease of use versus customization. Using the built-in plot() function is simple, but how do I offer options like filtering for specific classes, and controlling the confidence threshold? I'm adding these refinements, along with robust error handling and clear commenting.
Detailing the Implementation
I'm now generating the initial code block, starting with library imports and model loading, selecting the nano model for performance. Then I'm working through the video capture setup, choosing the webcam as the default source. I'm focusing on the main loop structure, ensuring proper frame reading and error handling.
Optimizing for Presentation
I'm now prioritizing clarity. The script's core is functional. I'm focusing on the introduction, guiding the user towards installation steps, model selection, and practical use. I plan to provide concise code breakdowns and actionable advice on customization. I'm making sure to address GPU acceleration in the final remarks.
This script uses YOLOv8 (by Ultralytics) and OpenCV. YOLOv8 is currently the standard for object detection because it is fast, accurate, and capable of running in real-time on many devices.
Prerequisites
You will need to install the ultralytics library and opencv. Open your terminal or command prompt and run:
bash
pip install ultralytics opencv-python
The Python Script
Create a file named detect.py and paste the following code:
python
import cv2
from ultralytics import YOLO
def main():
# 1. Load the YOLO model
# 'yolov8n.pt' is the generic "Nano" model.
# It downloads automatically on first run and is fastest for real-time.
# Options: yolov8n.pt, yolov8s.pt, yolov8m.pt, yolov8l.pt, yolov8x.pt
print("Loading model...")
model = YOLO('yolov8n.pt')
# 2. Setup Video Capture
# Use 0 for the default webcam.
# Replace 0 with a filename (e.g., "video.mp4") to detect on a video file.
cap = cv2.VideoCapture(0)
# Set the resolution (optional, but good for performance)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
if not cap.isOpened():
print("Error: Could not open video stream.")
return
print("Starting detection. Press 'q' to exit.")
while True:
# 3. Read a frame from the video
success, frame = cap.read()
if not success:
print("End of video flow or error reading frame.")
break
# 4. Run YOLOv8 Loop
# conf=0.5 means it only detects objects with >50% confidence
results = model(frame, stream=True, conf=0.5)
# 5. Visualize the results
# The 'results' object yields a generator. We process items as they come.
for r in results:
# plot() draws the bounding boxes and labels on the frame
annotated_frame = r.plot()
# Display the annotated frame
cv2.imshow("YOLOv8 Detection", annotated_frame)
# 6. Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 7. Cleanup
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
How it works
Model Loading:YOLO('yolov8n.pt') loads the Neural Network. Valid models range from n (nano, fastest) to x (extra large, most accurate but slow).
Video Capture:cv2.VideoCapture(0) connects to your webcam.
Inference:model(frame) passes the image through the neural network. We use stream=True which is more memory efficient for videos.
Plotting:r.plot() is a built-in Ultralytics function that handles the hard work of calculating the coordinates, drawing the boxes, writing the text labels, and assigning colors.
Advanced Customization
1. Filter Specific Classes
If you only want to detect people or cars, pass the classes argument. The COCO dataset (which standard YOLO is trained on) uses index 0 for people and 2 for cars.
2. Using a GPU (NVIDIA)
If you have an NVIDIA GPU and have installed PyTorch with CUDA support, YOLO will automatically attempt to use the GPU. If your FPS is low, you are likely running on CPU.
3. Accessing Coordinates Data
If you need the logic (e.g., "trigger alarm if person is on left side"), do not use r.plot(). Instead, iterate through boxes:
python
for r in results:
boxes = r.boxes
for box in boxes:
# Bounding Box
x1, y1, x2, y2 = box.xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
# Class Name
cls = int(box.cls[0])
currentClass = model.names[cls]
print(f"Detected {currentClass} at {x1},{y1}")
# Draw manually using cv2
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 255), 3)