o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Code an AI with pytorch that detects an object in an image
- User
Code an AI with pytorch that detects an object in an image
- Assistant
Code an AI with pytorch that detects an object in an image
Sure! Below is a step-by-step guide to coding an object detection AI using PyTorch and the pre-trained Faster R-CNN model with a ResNet-50 backbone. This model is capable of detecting objects in an image and is readily available in the torchvision library.
Note: This code requires PyTorch and Torchvision to be installed. If you haven't installed them yet, you can do so using pip install torch torchvision.
import torch
from torchvision import models, transforms
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
# Load a pre-trained model for object detection
model = models.detection.fasterrcnn_resnet50_fpn(weights="DEFAULT")
model.eval() # Set the model to evaluation mode
# Transformation to convert the image to tensor and normalize
transform = transforms.Compose([
transforms.ToTensor(), # Convert PIL Image to Tensor
])
# Load the image
image_path = 'path_to_your_image.jpg' # Replace with your image path
image = Image.open(image_path).convert("RGB")
# Apply the transformation
image_tensor = transform(image)
# Add a batch dimension
image_tensor = image_tensor.unsqueeze(0) # Shape: [1, C, H, W]
# Get predictions
with torch.no_grad():
outputs = model(image_tensor)
boxes, labels, and scores.# Get the first output
output = outputs[0]
# Threshold to filter out low-confidence detections
threshold = 0.8
# Get boxes, labels, and scores above the threshold
boxes = output['boxes'][output['scores'] > threshold]
labels = output['labels'][output['scores'] > threshold]
scores = output['scores'][output['scores'] > threshold]
# COCO dataset class names
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A',
'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli',
'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A',
'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# Convert tensor image back to PIL Image
image_np = np.array(image)
# Create a figure and axis to plot on
fig, ax = plt.subplots(1, figsize=(12,9))
# Display the image
ax.imshow(image_np)
# Add bounding boxes to the image
for idx, box in enumerate(boxes):
xmin, ymin, xmax, ymax = box
width = xmax - xmin
height = ymax - ymin
# Create a Rectangle patch
rect = patches.Rectangle((xmin, ymin), width, height, linewidth=2,
edgecolor='r', facecolor='none')
# Add the patch to the Axes
ax.add_patch(rect)
# Add label
label = COCO_INSTANCE_CATEGORY_NAMES[labels[idx]]
score = scores[idx]
ax.text(xmin, ymin - 10, f'{label}: {score:.2f}', color='red',
fontsize=12, fontweight='bold')
plt.axis('off') # Hide axes
plt.show()
Putting it all together:
import torch
from torchvision import models, transforms
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
# Load the pre-trained model
model = models.detection.fasterrcnn_resnet50_fpn(weights="DEFAULT")
model.eval()
# Define the transformation
transform = transforms.Compose([
transforms.ToTensor(),
])
# Load the image
image_path = 'path_to_your_image.jpg' # Replace with your image path
image = Image.open(image_path).convert("RGB")
# Apply the transformation
image_tensor = transform(image)
image_tensor = image_tensor.unsqueeze(0) # Add batch dimension
# Perform object detection
with torch.no_grad():
outputs = model(image_tensor)
# Process the outputs
output = outputs[0]
threshold = 0.8
boxes = output['boxes'][output['scores'] > threshold]
labels = output['labels'][output['scores'] > threshold]
scores = output['scores'][output['scores'] > threshold]
# Class labels mapping
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A',
'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli',
'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A',
'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# Visualize the results
image_np = np.array(image)
fig, ax = plt.subplots(1, figsize=(12,9))
ax.imshow(image_np)
for idx, box in enumerate(boxes):
xmin, ymin, xmax, ymax = box
width = xmax - xmin
height = ymax - ymin
# Create a Rectangle patch
rect = patches.Rectangle((xmin, ymin), width, height, linewidth=2,
edgecolor='r', facecolor='none')
# Add the patch to the Axes
ax.add_patch(rect)
# Add label
label = COCO_INSTANCE_CATEGORY_NAMES[labels[idx]]
score = scores[idx]
ax.text(xmin, ymin - 10, f'{label}: {score:.2f}', color='red',
fontsize=12, fontweight='bold')
plt.axis('off')
plt.show()
fasterrcnn_resnet50_fpn with pre-trained weights. This model is trained on the COCO dataset, which can detect 91 object types.threshold variable based on your requirements.'path_to_your_image.jpg' with the path to the image you want to test.Make sure you have installed the following packages:
pip install torch torchvision matplotlib
Feel free to ask if you need assistance with training on a custom dataset or deploying the model!
Not yet included in a published release.