-
Notifications
You must be signed in to change notification settings - Fork 0
/
scan.py
75 lines (56 loc) · 1.75 KB
/
scan.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys
import time
from typing import List
import cv2
import torch
from loguru import logger
from web_config import YOLOX_PATH, YOLOX_MODEL
from yolox.data.data_augment import ValTransform
from yolox.exp import get_exp
from yolox.utils import get_model_info, postprocess
# YOLOX项目路径
yolox_path = YOLOX_PATH
sys.path.append(yolox_path)
def init(ckpt_path):
global model, exp
# 模型的配置参数信息
exp = get_exp(yolox_path + '/exps/example/custom/nano.py', None)
model = exp.get_model()
logger.info("Model Summary: {}".format(
get_model_info(model, exp.test_size)))
# 评估模式
model.eval()
# 加载模型
logger.info("loading yolox_nano model")
ckpt = torch.load(ckpt_path, map_location="cpu")
# load the model state dict
model.load_state_dict(ckpt["model"])
logger.info("loaded yolox_nano model done.")
def inference(img) -> List[float]:
""" 执行推理 """
preprocess = ValTransform()
img, _ = preprocess(img, None, exp.test_size)
img = torch.from_numpy(img).unsqueeze(0)
img = img.float()
with torch.no_grad():
t0 = time.time()
outputs = model(img)
outputs = postprocess(
outputs, exp.num_classes, exp.test_conf,
exp.nmsthre, class_agnostic=True
)
logger.info("Infer time: {:.4f}s".format(time.time() - t0))
result = []
if outputs is None or outputs[0] is None:
return [0.0]
for output in outputs[0]:
scores = output[4] * output[5]
result.append(scores)
return sorted(result, reverse=True)
def detect(path: str) -> List[float]:
# 图片
img = cv2.imread(path)
return inference(img)
init(YOLOX_MODEL)