YOLO (You Only Look Once) is one of the most popular object detection approaches. In this article, we will use YOLOv8 with OpenCV to perform real-time object detection through a webcam.
Prerequisites
Make sure you have:
- Python 3.8+
- The
ultralyticslibrary for YOLOv8 - The
opencv-pythonlibrary for webcam access
Install the dependencies with pip:
pip install ultralytics opencv-pythonExample Code
The following Python example performs object detection from a webcam stream:
from ultralytics import YOLO
import cv2
# Load the lightweight and fast YOLOv8 Nano model
model = YOLO("yolov8n.pt")
# Open the webcam (0 = default camera)
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# Run detection
results = model(frame)
for result in results:
# Read bounding boxes, class IDs, and confidence scores
boxes = result.boxes
class_ids = boxes.cls
confidences = boxes.conf
# Visualize the result
annotated_frame = result.plot()
cv2.imshow("YOLOv8 Inference", annotated_frame)
# Press 'q' to exit
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()How It Works
-
Load the model
YOLO("yolov8n.pt")loads the YOLOv8 Nano model, which is a lightweight option suitable for real-time experiments. -
Open the webcam
cv2.VideoCapture(0)accesses the default camera. If your system has multiple cameras, replace0with the appropriate camera index. -
Run detection
results = model(frame)performs inference on each captured frame and returns detection results that include bounding boxes, confidence scores, and class IDs. -
Display the result
result.plot()creates an annotated frame, which is displayed withcv2.imshow.
Conclusion
With a small amount of code, you can build a real-time object detection pipeline using YOLOv8 and OpenCV. The same approach can be adapted to live cameras, recorded video, or collections of images.
Possible next steps include:
- Saving detection results to files
- Running detection on recorded video
- Building automated monitoring or analysis systems