Certainly! Below is a Python script that performs object detection using YOLO and then generates segmentation masks for the detected bounding boxes using the Segment Anything Model 2 (SAM2) from Facebook Research.
Prerequisites
-
Python Environment: Ensure you have Python 3.7 or higher installed.
-
Install Required Libraries:
- Ultralytics YOLOv8: We'll use YOLOv8 for object detection.
- SAM2: Clone the SAM2 repository and install its dependencies.
- Other Libraries: Such as
numpy, opencv-python, etc.
-
Download Pre-trained Models:
- YOLOv8 Weights: You can use pre-trained weights available from Ultralytics.
- SAM2 Weights: Follow the SAM2 GitHub repository to download the necessary weights.
Setup Instructions
-
Clone the SAM2 Repository:
git clone https://github.com/facebookresearch/segment-anything-2.git
cd segment-anything-2
pip install -r requirements.txt
python setup.py install
-
Install Ultralytics YOLOv8:
pip install ultralytics
-
Install Other Dependencies:
pip install opencv-python numpy torch torchvision
-
Ensure CUDA is Available (Optional):
If you have a GPU and CUDA installed, ensure that PyTorch is using it for faster computation.
Python Script
import torch
import cv2
import numpy as np
from ultralytics import YOLO
from sam import SamPredictor # Replace with the actual import path based on SAM2
from sam_model_registry import get_sam_model # Replace with the actual import path based on SAM2
import matplotlib.pyplot as plt
# Initialize YOLO model (You can choose a different model or path as needed)
yolo_model = YOLO('yolov8s.pt') # Make sure to download the YOLOv8 weights
# Initialize SAM2 model
# Replace 'path_to_sam2_model.pth' with the actual path to your SAM2 model weights
sam_model = get_sam_model('path_to_sam2_model.pth')
sam_predictor = SamPredictor(sam_model)
sam_predictor.to(device='cuda' if torch.cuda.is_available() else 'cpu')
def yolo_detect(image):
"""
Perform object detection using YOLO.
Args:
image (numpy.ndarray): Input image.
Returns:
List of bounding boxes. Each box is [x1, y1, x2, y2, confidence, class].
"""
results = yolo_model(image)
detections = results[0].boxes.cpu().numpy() # Assuming YOLOv8 returns boxes in results[0].boxes
# Each detection: [x1, y1, x2, y2, confidence, class]
return detections
def convert_yolo_to_sam_box(box, image_shape):
"""
Convert YOLO bounding box to SAM2 format.
Args:
box (list or array): [x1, y1, x2, y2, ...]
image_shape (tuple): Shape of the image (height, width).
Returns:
SAM2 formatted box: [x, y, width, height]
"""
x1, y1, x2, y2 = box[:4]
x = x1
y = y1
width = x2 - x1
height = y2 - y1
return [x, y, width, height]
def generate_masks(image, boxes):
"""
Generate segmentation masks for the given bounding boxes using SAM2.
Args:
image (numpy.ndarray): Input image.
boxes (list): List of bounding boxes in SAM2 format [x, y, width, height].
Returns:
List of masks corresponding to each bounding box.
"""
sam_predictor.set_image(image)
masks = []
for box in boxes:
# SAM2 expects boxes in the format [x, y, width, height]
masks_pred, scores_pred, logits_pred = sam_predictor.predict(
boxes=np.array([box]),
multimask_output=1 # Number of masks per box
)
masks.append(masks_pred[0]) # Assuming one mask per box
return masks
def visualize_results(image, detections, masks):
"""
Visualize bounding boxes and masks on the image.
Args:
image (numpy.ndarray): Original image.
detections (list): Bounding boxes from YOLO.
masks (list): Masks from SAM2.
"""
for det, mask in zip(detections, masks):
x1, y1, x2, y2, conf, cls = det
# Draw bounding box
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
# Overlay mask
color = np.random.randint(0, 255, (3,), dtype=int).tolist()
mask_color = np.zeros_like(image)
mask_color[mask > 0.5] = color
image = cv2.addWeighted(image, 1.0, mask_color, 0.5, 0)
# Convert BGR to RGB for display
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(12, 8))
plt.imshow(image_rgb)
plt.axis('off')
plt.show()
def main(image_path):
# Read image
image = cv2.imread(image_path)
if image is None:
print(f"Failed to read image from {image_path}")
return
# Perform YOLO detection
detections = yolo_detect(image)
if len(detections) == 0:
print("No objects detected.")
return
# Convert bounding boxes to SAM2 format
sam_boxes = [convert_yolo_to_sam_box(det, image.shape) for det in detections]
# Generate masks using SAM2
masks = generate_masks(image, sam_boxes)
# Visualize results
visualize_results(image, detections, masks)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="YOLO + SAM2 Segmentation")
parser.add_argument('--image', type=str, required=True, help='Path to input image')
args = parser.parse_args()
main(args.image)
Explanation of the Script
-
Imports:
- YOLO: Using Ultralytics' YOLOv8 for object detection.
- SAM2: Assuming
SamPredictor and get_sam_model are available from the SAM2 package. You might need to adjust the import paths based on the SAM2 repository structure.
- Other Libraries: For image processing and visualization.
-
Model Initialization:
- YOLO: Loads the YOLOv8 small model (
yolov8s.pt). You can choose other versions (yolov8m.pt, yolov8l.pt, etc.) based on your requirements.
- SAM2: Loads the SAM2 model weights and initializes the predictor. Ensure you replace
'path_to_sam2_model.pth' with the actual path to your SAM2 weights file.
-
Detection Function (yolo_detect):
- Takes an input image and returns a list of detections.
- Each detection includes bounding box coordinates, confidence score, and class ID.
-
Box Conversion (convert_yolo_to_sam_box):
- Converts YOLO's
[x1, y1, x2, y2] format to SAM2's [x, y, width, height] format.
-
Mask Generation (generate_masks):
- Sets the image for the SAM2 predictor.
- Iterates over each bounding box and generates a mask.
- Assumes that SAM2's
predict method returns masks, scores, and logits. Adjust based on the actual SAM2 API.
-
Visualization (visualize_results):
- Draws bounding boxes on the image.
- Overlays the generated masks with random colors for visualization.
- Displays the final image using
matplotlib.
-
Main Function (main):
- Reads the input image.
- Performs YOLO object detection.
- Converts bounding boxes to SAM2 format.
- Generates segmentation masks using SAM2.
- Visualizes the results.
-
Argument Parsing:
- Allows the script to take an image path as a command-line argument.
Running the Script
-
Save the Script: Save the above script to a file, e.g., yolo_sam2.py.
-
Run the Script:
python yolo_sam2.py --image path_to_your_image.jpg
Replace path_to_your_image.jpg with the actual path to the image you want to process.
Notes
-
SAM2 Integration: The exact integration with SAM2 might vary based on the repository's API. Ensure you refer to the SAM2 GitHub repository for accurate usage instructions and adjust the import statements and method calls accordingly.
-
Performance: Depending on your hardware (CPU vs. GPU), processing might be slow. If you have a CUDA-compatible GPU, ensure that both YOLO and SAM2 are utilizing it for faster computation.
-
Error Handling: The script includes basic error handling for image reading and detection. You might want to add more robust error handling based on your needs.
-
Customization: Feel free to customize the visualization, such as adding class labels, adjusting mask transparency, or saving the output images.
Conclusion
This script combines the strengths of YOLO for fast and accurate object detection with SAM2's powerful segmentation capabilities. By leveraging bounding boxes from YOLO as prompts for SAM2, you can obtain precise segmentation masks for detected objects in images.
If you encounter any issues or need further customization, please refer to the respective documentation of Ultralytics YOLO and SAM2.