Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Real-Time Object Detection with YOLOv8 and OpenCV

1 min read .
Real-Time Object Detection with YOLOv8 and OpenCV

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 ultralytics library for YOLOv8
  • The opencv-python library for webcam access

Install the dependencies with pip:

pip install ultralytics opencv-python

Example 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

  1. Load the model YOLO("yolov8n.pt") loads the YOLOv8 Nano model, which is a lightweight option suitable for real-time experiments.

  2. Open the webcam cv2.VideoCapture(0) accesses the default camera. If your system has multiple cameras, replace 0 with the appropriate camera index.

  3. Run detection results = model(frame) performs inference on each captured frame and returns detection results that include bounding boxes, confidence scores, and class IDs.

  4. Display the result result.plot() creates an annotated frame, which is displayed with cv2.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

Related Posts

chevron-up