Spaces:
Running
Running
Create utils.py
Browse files- utils/utils.py +43 -0
utils/utils.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# utils.py
|
2 |
+
import torch
|
3 |
+
import supervision as sv
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
def detect_objects_in_image(image_input_path, texts, device):
|
7 |
+
# 加载图像
|
8 |
+
image_input = Image.open(image_input_path)
|
9 |
+
|
10 |
+
# 初始化检测列表
|
11 |
+
detections_list = []
|
12 |
+
|
13 |
+
# 对每个文本进行检测
|
14 |
+
for text in texts:
|
15 |
+
_, result = run_florence_inference(
|
16 |
+
model=FLORENCE_MODEL.to(device),
|
17 |
+
processor=FLORENCE_PROCESSOR,
|
18 |
+
device=device,
|
19 |
+
image=image_input,
|
20 |
+
task=FLORENCE_OPEN_VOCABULARY_DETECTION_TASK,
|
21 |
+
text=text
|
22 |
+
)
|
23 |
+
|
24 |
+
# 从结果中构建监督检测对象
|
25 |
+
detections = sv.Detections.from_lmm(
|
26 |
+
lmm=sv.LMM.FLORENCE_2,
|
27 |
+
result=result,
|
28 |
+
resolution_wh=image_input.size
|
29 |
+
)
|
30 |
+
|
31 |
+
# 运行 SAM 推理
|
32 |
+
detections = run_sam_inference(SAM_IMAGE_MODEL.to(device), image_input, detections)
|
33 |
+
|
34 |
+
# 将检测结果添加到列表中
|
35 |
+
detections_list.append(detections)
|
36 |
+
|
37 |
+
# 合并所有检测结果
|
38 |
+
detections = sv.Detections.merge(detections_list)
|
39 |
+
|
40 |
+
# 再次运行 SAM 推理
|
41 |
+
detections = run_sam_inference(SAM_IMAGE_MODEL.to(device), image_input, detections)
|
42 |
+
|
43 |
+
return detections
|