Write python script (seperate code for Jupiter notebook) for detecting specific items on…
- User
Write python script (seperate code for Jupiter notebook) for detecting specific items on image with SAM2 and prompt.
- Assistant
Write python script (seperate code for Jupiter notebook) for detecting specific items on image with SAM2 and prompt.
Here are the Python scripts for detecting specific items in an image using the Segment Anything Model (SAM) and prompts. The scripts use SAM in combination with GroundingDINO to perform text-prompted object detection and segmentation.
Jupyter Notebook Code:
# Install required packages
!pip install git+https://github.com/facebookresearch/segment-anything.git
!pip install git+https://github.com/IDEA-Research/GroundingDINO.git
!pip install matplotlib opencv-python tqdm
!pip install 'git+https://github.com/facebookresearch/detectron2.git'
# Import necessary modules
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import requests
from io import BytesIO
from segment_anything import sam_model_registry, SamPredictor
from groundingdino.util.inference import load_model, predict
# Paths to the model checkpoints
GROUNDING_DINO_CONFIG = 'GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py'
GROUNDING_DINO_CHECKPOINT = 'groundingdino_swint_ogc.pth'
SAM_CHECKPOINT = 'sam_vit_h_4b8939.pth'
# Download and load model checkpoints
# GroundingDINO checkpoint
!wget -q https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth -O {GROUNDING_DINO_CHECKPOINT}
# SAM checkpoint
!wget -q https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth -O {SAM_CHECKPOINT}
# Load GroundingDINO model
dino_model = load_model(GROUNDING_DINO_CONFIG, GROUNDING_DINO_CHECKPOINT)
# Load SAM model
sam = sam_model_registry["vit_h"](checkpoint=SAM_CHECKPOINT)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
sam.to(device)
sam_predictor = SamPredictor(sam)
# Load an image
image_url = 'https://upload.wikimedia.org/wikipedia/commons/4/4c/Push_van_cat-crop.jpg' # Replace with your image URL or local file path
response = requests.get(image_url)
image = Image.open(BytesIO(response.content)).convert("RGB")
# Convert image to numpy array
image_np = np.array(image)
# Provide a text prompt
text_prompt = "cat" # Replace with your desired prompt
# GroundingDINO inference
boxes, logits, phrases = predict(
model=dino_model,
image=image_np,
caption=text_prompt,
box_threshold=0.3,
text_threshold=0.25,
device=device
)
# Convert boxes to numpy array
boxes = boxes.numpy()
# Prepare for SAM
sam_predictor.set_image(image_np)
# Convert boxes to required format and normalize
transformed_boxes = sam_predictor.transform.apply_boxes_torch(torch.from_numpy(boxes), image_np.shape[:2])
# Generate masks with SAM
masks, _, _ = sam_predictor.predict_torch(
point_coords = None,
point_labels = None,
boxes = transformed_boxes.to(device),
multimask_output = False
)
# Visualize results
import matplotlib.patches as patches
def show_mask(mask, ax, random_color=False):
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30/255, 144/255, 255/255, 0.6])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
ax.imshow(mask_image)
def show_box(box, ax):
x0, y0, x1, y1 = box
rect = patches.Rectangle((x0, y0), x1 - x0, y1 - y0, linewidth=2, edgecolor='green', facecolor='none')
ax.add_patch(rect)
fig, ax = plt.subplots(figsize=(10,10))
ax.imshow(image_np)
for mask, box, label in zip(masks.cpu().numpy(), boxes, phrases):
show_mask(mask, ax, random_color=True)
show_box(box, ax)
ax.text(box[0], box[1], label, color='white', fontsize=12, bbox=dict(facecolor='green', alpha=0.5))
plt.axis('off')
plt.show()
Python Script (script.py):
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import requests
from io import BytesIO
from segment_anything import sam_model_registry, SamPredictor
from groundingdino.util.inference import load_model, predict
def main():
# Paths to the model checkpoints
GROUNDING_DINO_CONFIG = 'GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py'
GROUNDING_DINO_CHECKPOINT = 'groundingdino_swint_ogc.pth'
SAM_CHECKPOINT = 'sam_vit_h_4b8939.pth'
# Download and load model checkpoints
# GroundingDINO checkpoint
if not os.path.exists(GROUNDING_DINO_CHECKPOINT):
os.system(f"wget -q https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth -O {GROUNDING_DINO_CHECKPOINT}")
# SAM checkpoint
if not os.path.exists(SAM_CHECKPOINT):
os.system(f"wget -q https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth -O {SAM_CHECKPOINT}")
# Load GroundingDINO model
dino_model = load_model(GROUNDING_DINO_CONFIG, GROUNDING_DINO_CHECKPOINT)
# Load SAM model
sam = sam_model_registry["vit_h"](checkpoint=SAM_CHECKPOINT)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
sam.to(device)
sam_predictor = SamPredictor(sam)
# Load an image
image_url = 'https://upload.wikimedia.org/wikipedia/commons/4/4c/Push_van_cat-crop.jpg' # Replace with your image URL or local file path
response = requests.get(image_url)
image = Image.open(BytesIO(response.content)).convert("RGB")
# Convert image to numpy array
image_np = np.array(image)
# Provide a text prompt
text_prompt = "cat" # Replace with your desired prompt
# GroundingDINO inference
boxes, logits, phrases = predict(
model=dino_model,
image=image_np,
caption=text_prompt,
box_threshold=0.3,
text_threshold=0.25,
device=device
)
# Convert boxes to numpy array
boxes = boxes.numpy()
# Prepare for SAM
sam_predictor.set_image(image_np)
# Convert boxes to required format and normalize
transformed_boxes = sam_predictor.transform.apply_boxes_torch(torch.from_numpy(boxes), image_np.shape[:2])
# Generate masks with SAM
masks, _, _ = sam_predictor.predict_torch(
point_coords = None,
point_labels = None,
boxes = transformed_boxes.to(device),
multimask_output = False
)
# Visualize results
import matplotlib.patches as patches
def show_mask(mask, ax, random_color=False):
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30/255, 144/255, 255/255, 0.6])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
ax.imshow(mask_image)
def show_box(box, ax):
x0, y0, x1, y1 = box
rect = patches.Rectangle((x0, y0), x1 - x0, y1 - y0, linewidth=2, edgecolor='green', facecolor='none')
ax.add_patch(rect)
fig, ax = plt.subplots(figsize=(10,10))
ax.imshow(image_np)
for mask, box, label in zip(masks.cpu().numpy(), boxes, phrases):
show_mask(mask, ax, random_color=True)
show_box(box, ax)
ax.text(box[0], box[1], label, color='white', fontsize=12, bbox=dict(facecolor='green', alpha=0.5))
plt.axis('off')
plt.savefig('output.png')
print("Results saved to output.png")
if __name__ == '__main__':
main()
Instructions:
Install Required Packages:
Before running the scripts, ensure you have the required packages installed. You can install them using the following commands:
pip install git+https://github.com/facebookresearch/segment-anything.git
pip install git+https://github.com/IDEA-Research/GroundingDINO.git
pip install matplotlib opencv-python tqdm
pip install 'git+https://github.com/facebookresearch/detectron2.git'
Run Jupyter Notebook:
.ipynb file.Run Python Script:
Save the script code into a file named script.py.
Run the script using the command:
python script.py
The script will process the image and save the output as output.png in the current directory.
Notes:
image_url and text_prompt variables with your desired image and prompt.These scripts will detect specific items in an image using the Segment Anything Model with a text prompt, as per your request.
Not yet included in a published release.