-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpredict.py
More file actions
64 lines (52 loc) · 1.9 KB
/
Copy pathpredict.py
File metadata and controls
64 lines (52 loc) · 1.9 KB
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
from networks.detector import HeadDetector
from skimage import transform
from data.preprocess import Normalize
from config import cfg
import torch
import numpy as np
import time
import cv2
import argparse
def preprocess(img, min_size=600, max_size=1000):
c, h, w = img.shape
scale = min(min_size / min(h, w), max_size / max(h, w))
img = img / 255
img = transform.resize(img, (c, h * scale, w * scale), mode='reflect')
normalize = Normalize(mode='caffe')
sample = normalize({'img': img})
return sample['img'], scale
def read_img(path):
img = cv2.imread(path)
img_raw = img.copy()
img = img.transpose((2, 0, 1)) # (H,W,C) -> (C,H,W)
img, scale = preprocess(img)
return img, img_raw, scale
def detect(img_path):
# Load and pre-process img
img, img_raw, scale = read_img(img_path)
img = np.expand_dims(img, axis=0)
img = torch.from_numpy(img)
img = img.cuda().float()
# Load model
head_detector = HeadDetector(ratios=cfg.ANCHOR_RATIOS, scales=cfg.ANCHOR_SCALES)
model_dict = torch.load(cfg.BEST_MODEL_PATH)['model']
head_detector.load_state_dict(model_dict)
head_detector = head_detector.cuda()
# Inference
begin = time.time()
preds, scores = head_detector(img, scale, score_thresh=0.01)
end = time.time()
print("[INFO] Model inference time: {:.3f} s".format(end - begin))
print("[PREDS SCORES]\n", scores)
# Plot bbox into img
for bbox in preds:
ymin, xmin, ymax, xmax = bbox
xmin, ymin = int(xmin / scale), int(ymin / scale)
xmax, ymax = int(xmax / scale), int(ymax / scale)
cv2.rectangle(img_raw, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2)
cv2.imwrite('result.png', img_raw)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--img_path", help="path of the input image")
args = parser.parse_args()
detect(args.img_path)