Mithu96 commited on
Commit
8a9739b
1 Parent(s): 25e742a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import OwlViTProcessor, OwlViTForObjectDetection
3
+ from PIL import Image, ImageDraw
4
+ import gradio as gr
5
+
6
+ # Load pre-trained Owl-ViT model and processor
7
+ model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")
8
+ processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
9
+
10
+ def detect_objects(image: Image.Image, texts: str):
11
+ # Prepare text queries
12
+ text_queries = [text.strip() for text in texts.split(',')]
13
+
14
+ # Prepare inputs for the model
15
+ inputs = processor(text=text_queries, images=image, return_tensors="pt")
16
+
17
+ # Perform inference with the model
18
+ with torch.no_grad():
19
+ outputs = model(**inputs)
20
+
21
+ # Post-process the outputs to extract detected boxes and labels
22
+ target_sizes = torch.tensor([image.size[::-1]])
23
+ results = processor.post_process(outputs=outputs, target_sizes=target_sizes)
24
+
25
+ # Extracting results
26
+ detected_boxes = []
27
+ for i, box in enumerate(results[0]["boxes"]):
28
+ score = results[0]["scores"][i].item()
29
+ label = results[0]["labels"][i].item()
30
+ if score > 0.1: # Confidence threshold
31
+ detected_boxes.append((box, text_queries[label], score))
32
+
33
+ return detected_boxes
34
+
35
+ def visualize(image, texts):
36
+ # Detect objects in the image
37
+ boxes = detect_objects(image, texts)
38
+
39
+ # Draw boxes on the image
40
+ image = image.copy()
41
+ draw = ImageDraw.Draw(image)
42
+ for box, label, score in boxes:
43
+ box = [round(coord) for coord in box.tolist()]
44
+ draw.rectangle(box, outline="red", width=3)
45
+ draw.text((box[0], box[1]), f"{label}: {score:.2f}", fill="red")
46
+
47
+ return image
48
+
49
+ # Gradio Interface
50
+ def gradio_interface(image, texts):
51
+ return visualize(image, texts)
52
+
53
+ interface = gr.Interface(
54
+ fn=gradio_interface,
55
+ inputs=[gr.Image(type="pil", label="Upload an Image"), gr.Textbox(label="Comma-separated Text Queries")],
56
+ outputs=gr.Image(type="pil", label="Object Detection Output"),
57
+ title="Owl-ViT Object Detection",
58
+ description="Upload an image and provide comma-separated text queries for object detection.",
59
+ allow_flagging="never"
60
+ )
61
+
62
+ if __name__ == "__main__":
63
+ interface.launch()