Spaces:
Sleeping
Sleeping
Delete app.py
Browse filesremove old app.py
app.py
DELETED
@@ -1,69 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
"""appre.ipynb
|
3 |
-
|
4 |
-
Automatically generated by Colaboratory.
|
5 |
-
|
6 |
-
Original file is located at
|
7 |
-
https://colab.research.google.com/drive/1lDMgKpnES31ZrHV62ifeYr6k7KPvaPLt
|
8 |
-
"""
|
9 |
-
import torch
|
10 |
-
import gradio as gr
|
11 |
-
from transformers import Owlv2Processor, Owlv2ForObjectDetection
|
12 |
-
import spaces
|
13 |
-
|
14 |
-
# Use GPU if available
|
15 |
-
if torch.cuda.is_available():
|
16 |
-
device = torch.device("cuda")
|
17 |
-
else:
|
18 |
-
device = torch.device("cpu")
|
19 |
-
|
20 |
-
model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble").to(device)
|
21 |
-
processor = Owlv2Processor.from_pretrained("google/owlv2-base-patch16-ensemble")
|
22 |
-
|
23 |
-
@spaces.GPU
|
24 |
-
#输入图像,搜索文本,检测分数
|
25 |
-
def query_image(img, text_queries, score_threshold):
|
26 |
-
text_queries = text_queries
|
27 |
-
#分割搜索文本
|
28 |
-
text_queries = text_queries.split(",")
|
29 |
-
#转换为正方行torch矩阵
|
30 |
-
#(长宽边最大的那个设置为size)
|
31 |
-
size = max(img.shape[:2])
|
32 |
-
target_sizes = torch.Tensor([[size, size]])
|
33 |
-
#创建输入(搜索文本和图像转换为torch张量发送到GPU)
|
34 |
-
inputs = processor(text=text_queries, images=img, return_tensors="pt").to(device)
|
35 |
-
#禁用梯度计算,运行推理
|
36 |
-
with torch.no_grad():
|
37 |
-
outputs = model(**inputs)
|
38 |
-
#输出分数和边界框信息
|
39 |
-
outputs.logits = outputs.logits.cpu()
|
40 |
-
outputs.pred_boxes = outputs.pred_boxes.cpu()
|
41 |
-
#导出输出结果
|
42 |
-
results = processor.post_process_object_detection(outputs=outputs, target_sizes=target_sizes)
|
43 |
-
#分类存储输出结果的边界框,分数,标签
|
44 |
-
boxes, scores, labels = results[0]["boxes"], results[0]["scores"], results[0]["labels"]
|
45 |
-
#
|
46 |
-
#创建空列表
|
47 |
-
result_labels = []
|
48 |
-
#遍历分类存储的输出结果
|
49 |
-
for box, score, label in zip(boxes, scores, labels):
|
50 |
-
#转换为整数
|
51 |
-
box = [int(i) for i in box.tolist()]
|
52 |
-
#过滤阈值以下的目标
|
53 |
-
if score < score_threshold:
|
54 |
-
continue
|
55 |
-
result_labels.append((box, text_queries[label.item()]))
|
56 |
-
result
|
57 |
-
num_result_labels = len(result_labels)
|
58 |
-
return img, result_labels
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
demo = gr.Interface(
|
63 |
-
query_image,
|
64 |
-
inputs=[gr.Image(), "text", gr.Slider(0, 1, value=0.2)],
|
65 |
-
outputs=["annotatedimage"],
|
66 |
-
title="Zero-Shot Object Detection with OWLv2",
|
67 |
-
)
|
68 |
-
demo.launch()
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|