File size: 1,080 Bytes
a863f79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sys

import torch
from PIL import Image
from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor

repo = "/repository/models/grounding-dino-tiny"
processor = AutoProcessor.from_pretrained(repo)
model = AutoModelForZeroShotObjectDetection.from_pretrained(repo).to("cuda:0").eval()

image_path, *labels = sys.argv[1:]
image = Image.open(image_path).convert("RGB")
text = " . ".join(labels) + " ."
inputs = processor(images=image, text=text, return_tensors="pt").to("cuda:0")
with torch.no_grad():
    outputs = model(**inputs)
results = processor.post_process_grounded_object_detection(
    outputs, inputs["input_ids"], threshold=0.05, text_threshold=0.05,
    target_sizes=[image.size[::-1]])[0]
names = results.get("text_labels") or results["labels"]
rows = []
for box, score, name in zip(results["boxes"], results["scores"], names):
    x0, y0, x1, y1 = [float(v) for v in box]
    rows.append((float(score), str(name), round((x1 - x0) / image.size[0], 3), round((y1 - y0) / image.size[1], 3)))
rows.sort(reverse=True)
for r in rows[:12]:
    print(r)