Certainly! Below is a Python script that uses the YOLO (You Only Look Once) model for object detection. This script will load an image from your device, perform object detection using the YOLO model, and display the results.
First, ensure you have the necessary libraries installed. You can install them using pip:
import cv2
import numpy as np
import torch
from torchvision import transforms
from PIL import Image
# Load the YOLO model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # You can choose other YOLO versions like yolov5m, yolov5l, yolov5x
# Function to perform object detection
def detect_objects(image_path):
# Load the image
image = Image.open(image_path)
image_rgb = image.convert("RGB")
# Convert the image to a format suitable for the model
transform = transforms.Compose([
transforms.Resize(640),
transforms.CenterCrop(640),
transforms.ToTensor()
])
input_tensor = transform(image_rgb).unsqueeze(0) # Add batch dimension
# Perform object detection
results = model(input_tensor)
# Get the results
detections = results.xyxy[0] # Confidence threshold is set to 0.4 by default
# Draw bounding boxes on the image
image_np = np.array(image)
for *box, conf, cls in detections:
box = [int(b) for b in box]
label = f'{model.names[int(cls)]} {conf:.2f}'
cv2.rectangle(image_np, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
cv2.putText(image_np, label, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the image with bounding boxes
cv2.imshow('Object Detection', image_np)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Example usage
image_path = 'path_to_your_image.jpg' # Replace with your image path
detect_objects(image_path)
Explanation:
Loading the YOLO Model: The script loads the YOLOv5 small model using torch.hub.load.
Image Loading and Preprocessing: The image is loaded using PIL, converted to RGB, and then resized and transformed into a tensor suitable for the YOLO model.
Object Detection: The model is applied to the input tensor to get the detections.
Drawing Bounding Boxes: The script iterates over the detections, draws bounding boxes, and labels on the image.
Displaying the Image: The image with bounding boxes is displayed using OpenCV.
Usage:
Replace 'path_to_your_image.jpg' with the path to the image you want to process.
Run the script, and it will display the image with detected objects and their labels.
Ensure you have the necessary dependencies installed and the image path is correct for the script to work properly.