Babyloncoder commited on
Commit
396610c
·
verified ·
1 Parent(s): 4676395

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ from transformers import Owlv2Processor, Owlv2ForObjectDetection
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ import numpy as np
6
+ import random
7
+
8
+ if torch.cuda.is_available():
9
+ device = torch.device("cuda")
10
+ else:
11
+ device = torch.device("cpu")
12
+
13
+ model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble").to(device)
14
+ processor = Owlv2Processor.from_pretrained("google/owlv2-base-patch16-ensemble")
15
+
16
+ st.title("Zero-Shot Object Detection with OWLv2")
17
+
18
+ uploaded_image = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
19
+ text_queries = st.text_input("Enter text queries (comma-separated):")
20
+ score_threshold = st.slider("Score Threshold", min_value=0.0, max_value=1.0, value=0.1, step=0.01)
21
+
22
+
23
+ def query_image(img, text_queries, score_threshold):
24
+ try:
25
+ img = Image.open(img).convert("RGB")
26
+ img_np = np.array(img)
27
+ text_queries = text_queries.split(",")
28
+
29
+ size = max(img_np.shape[:2])
30
+ target_sizes = torch.Tensor([[size, size]])
31
+ inputs = processor(text=text_queries, images=img_np, return_tensors="pt").to(device)
32
+
33
+ with torch.no_grad():
34
+ outputs = model(**inputs)
35
+
36
+ outputs.logits = outputs.logits.cpu()
37
+ outputs.pred_boxes = outputs.pred_boxes.cpu()
38
+ results = processor.post_process_object_detection(outputs=outputs, target_sizes=target_sizes)
39
+ boxes, scores, labels = results[0]["boxes"], results[0]["scores"], results[0]["labels"]
40
+
41
+ result_labels = []
42
+ for box, score, label in zip(boxes, scores, labels):
43
+ box = [int(i) for i in box.tolist()]
44
+ if score < score_threshold:
45
+ continue
46
+ result_labels.append((box, text_queries[label.item()]))
47
+
48
+ return img, result_labels
49
+
50
+ except Exception as e:
51
+ st.error(f"Error performing object detection: {e}")
52
+
53
+
54
+ if uploaded_image is not None:
55
+ annotated_image, detected_objects = query_image(uploaded_image, text_queries, score_threshold)
56
+ if annotated_image:
57
+ draw = ImageDraw.Draw(annotated_image)
58
+ font = ImageFont.load_default()
59
+ for box, label in detected_objects:
60
+ color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
61
+ draw.rectangle(box, outline=color, width=3)
62
+ draw.text((box[0], box[1]), label, fill="black", font=font)
63
+ st.image(annotated_image, caption="Annotated Image", use_column_width=True)
64
+