Using YOLOv8 for Real-Time Object Detection with OpenCV

2 min read .

We will discuss how to use YOLOv8 (You Only Look Once) for real-time object detection using a webcam and OpenCV. YOLO is one of the most popular and effective object detection algorithms, and its latest version, YOLOv8, offers improved and faster performance.

Prerequisites

Before you begin, ensure that you have installed:

  • Python
  • ultralytics (for YOLOv8)
  • opencv-python (for OpenCV)

You can install them using pip if you haven’t already:

pip install ultralytics opencv-python

Object Detection Code

Below is an example of Python code that uses YOLOv8 to detect objects from video captured by a webcam:

from ultralytics import YOLO
import cv2

# Load a model
model = YOLO("yolov8n.pt") 

# Access webcam
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # Run inference on the frame
    results = model(frame)

    # Loop through each detection in the frame
    for result in results:
        boxes = result.boxes
        # Print bounding boxes
        # print(boxes)

        # Get other attributes like class IDs, confidences, etc.
        class_ids = boxes.cls  
        confidences = boxes.conf
        # Print or process other attributes as needed
        # print("Class IDs:", class_ids)
        # print("Confidences:", confidences)

        # Visualize the results on the frame
        annotated_frame = result.plot()

        # Display the annotated frame
        cv2.imshow("YOLOv8 Inference", annotated_frame)

    # Break the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# Release resources
cap.release()
cv2.destroyAllWindows()

Code Explanation

  1. Importing Modules:

    • YOLO from ultralytics is used to load the YOLOv8 model.
    • cv2 from opencv-python is used to handle webcam operations and image manipulation.
  2. Loading the Model:

    • model = YOLO("yolov8n.pt") loads the YOLOv8 model. You must ensure that the yolov8n.pt model file is in your working directory, or you can download it from the YOLO repository.
  3. Accessing the Webcam:

    • cap = cv2.VideoCapture(0) opens the webcam. The parameter 0 refers to the default camera. If you have multiple cameras, you can change this parameter to match the camera ID.
  4. Main Loop:

    • ret, frame = cap.read() reads a frame from the webcam.
    • results = model(frame) runs object detection on the captured frame.
  5. Processing Detection Results:

    • boxes = result.boxes retrieves bounding boxes from the detection results.
    • class_ids and confidences store the class IDs and confidence levels of the detected objects.
  6. Visualization and Display:

    • annotated_frame = result.plot() draws the detection results on the frame.
    • cv2.imshow("YOLOv8 Inference", annotated_frame) displays the annotated frame.
  7. Termination and Cleanup:

    • The loop ends when the ‘q’ key is pressed.
    • cap.release() and cv2.destroyAllWindows() are used to release the camera and close the display window.

Conclusion

With this code, you can easily use YOLOv8 for real-time object detection from a webcam. YOLOv8 offers fast and accurate detection, and integration with OpenCV allows for direct visualization and manipulation of the results. You can further develop this code for more complex applications according to your needs.

Tags:
AI

See Also

chevron-up