Object Detection with YOLO

Object Detection with YOLO

Object Detection with YOLO

A guide to using a pre-trained YOLO (You Only Look Once) model to detect and localize objects in images or video.

Libraries and Tools Used

This project uses a few key Python libraries for Computer Vision and deep learning:

  • torch: The deep learning framework for loading and running the YOLO model.
  • ultralytics: A library providing a simple API for the latest YOLO models.
  • cv2 (OpenCV): For reading and displaying images or video frames.

1. Load the Pre-trained YOLO Model

  • What the code does: It loads a pre-trained YOLOv8n model from the `ultralytics` library. This model is ready to be used for inference without any additional training.
  • Behind the scenes: The YOLO model consists of a convolutional neural network that processes an image and outputs predictions. The `n` in YOLOv8n stands for "nano," indicating it's a smaller, faster version suitable for real-time applications.
  • Abstraction: The `ultralytics` library simplifies the process of loading the model to a single line, abstracting away the complex architecture and weight loading.
# pip install ultralytics
from ultralytics import YOLO

# Load a pre-trained YOLOv8n model
model = YOLO('yolov8n.pt')

print("YOLO model loaded successfully.")

2. Perform Object Detection on an Image

  • What the code does: It runs the loaded YOLO model on a sample image URL. The `model.predict` method handles all the heavy lifting, including preprocessing, inference, and post-processing like Non-Maximum Suppression (NMS).
  • Behind the scenes: The image is resized and passed through the model. The model outputs bounding boxes, class labels, and confidence scores. NMS then filters out redundant or overlapping boxes.
  • Abstraction: The `model.predict` function provides a high-level API to get the results, which include the bounding box coordinates and class names, in a clean format.
# Run inference on a sample image from a URL
image_url = 'https://ultralytics.com/images/bus.jpg'
results = model.predict(source=image_url)

# Display the results
for r in results:
    im_array = r.plot()  # plot a BGR numpy array of predictions
    im = Image.fromarray(im_array[..., ::-1])  # RGB PIL image
    im.show()

3. Process and Visualize Results

  • What the code does: It iterates through the detection results to print the details of each detected object, including its class and confidence score. The `r.plot()` method is used to directly visualize the results.
  • Behind the scenes: The `results` object is an iterator that contains information about all the detections. We can access attributes like `boxes` and `names` to get the raw data.
  • Abstraction: The `r.plot()` method makes visualization extremely simple, as it takes care of drawing the bounding boxes and labels on the image for us.
# Parse the detection results
for result in results:
    boxes = result.boxes
    for box in boxes:
        class_id = int(box.cls[0])
        class_name = result.names[class_id]
        confidence = float(box.conf[0])
        box_coords = [int(i) for i in box.xyxy[0].tolist()]
        print(f"Detected: {class_name}, Confidence: {confidence:.2f}, BBox: {box_coords}")

Comments

Popular posts from this blog

Simple Augmented Reality (AR) App

Image Captioning

Pose Estimation