forked from axinc-ai/ailia-models
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc-3-framework.py
203 lines (156 loc) · 5.77 KB
/
c-3-framework.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import sys, os
import time
import numpy as np
import cv2
from matplotlib import pyplot as plt
import ailia
# import original modules
sys.path.append('../../util')
from utils import get_base_parser, update_parser # noqa: E402
from model_utils import check_and_download_models # noqa: E402
from detector_utils import load_image # noqa: E402C
from webcamera_utils import get_capture # noqa: E402
# ======================
# Parameters
# ======================
WEIGHT_ALEXNET_PATH = 'AlexNet.onnx'
WEIGHT_VGG_PATH = 'VGG.onnx'
WEIGHT_VGG_DECODER_PATH = 'VGG_DECODER.onnx'
WEIGHT_RESNET50_PATH = 'ResNet50.onnx'
WEIGHT_RESNET101_PATH = 'ResNet101.onnx'
WEIGHT_CSRNET_PATH = 'CSRNet.onnx'
WEIGHT_SANET_PATH = 'SANet.onnx'
MODEL_ALEXNET_PATH = 'AlexNet.onnx.prototxt'
MODEL_VGG_PATH = 'VGG.onnx.prototxt'
MODEL_VGG_DECODER_PATH = 'VGG_DECODER.onnx.prototxt'
MODEL_RESNET50_PATH = 'ResNet50.onnx.prototxt'
MODEL_RESNET101_PATH = 'ResNet101.onnx.prototxt'
MODEL_CSRNET_PATH = 'CSRNet.onnx.prototxt'
MODEL_SANET_PATH = 'SANet.onnx.prototxt'
REMOTE_PATH = \
'https://storage.googleapis.com/ailia-models/c-3-framework/'
IMAGE_PATH = 'demo.jpg'
SAVE_IMAGE_PATH = 'output.png'
# ======================
# Arguemnt Parser Config
# ======================
parser = get_base_parser(
'C-3-Framework model', IMAGE_PATH, SAVE_IMAGE_PATH
)
parser.add_argument(
'-m', '--model', type=str, default='resnet50',
choices=(
'alexnet', 'vgg', 'vgg_decoder', 'resnet50', 'resnet101', 'csrnet', 'sanet',
),
help='choice model'
)
args = update_parser(parser)
# ======================
# Secondaty Functions
# ======================
def preprocess(img):
img = img.astype(np.float32) / 255
# normalize
mean = np.array([0.452016860247, 0.447249650955, 0.431981861591])
std = np.array([0.23242045939, 0.224925786257, 0.221840232611])
mean = np.float64(mean.reshape(1, -1))
stdinv = 1 / np.float64(std.reshape(1, -1))
cv2.subtract(img, mean, img) # inplace
cv2.multiply(img, stdinv, img) # inplace
img = img.transpose(2, 0, 1)
img = np.expand_dims(img, axis=0)
return img
# ======================
# Main functions
# ======================
def predict(img, net):
img = preprocess(img)
net.set_input_shape(img.shape)
pred_map = net.predict({'imgs': img})[0]
pred_map = pred_map[0, 0, :, :]
return pred_map
def recognize_from_image(filename, net):
# prepare input data
img = load_image(filename)
print(f'input image shape: {img.shape}')
img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
# inference
print('Start inference...')
if args.benchmark:
print('BENCHMARK mode')
for i in range(5):
start = int(round(time.time() * 1000))
pred_map = predict(img, net)
end = int(round(time.time() * 1000))
print(f'\tailia processing time {end - start} ms')
else:
pred_map = predict(img, net)
pred = np.sum(pred_map) / 100.0
pred_map = pred_map / np.max(pred_map + 1e-20)
print("predict:", pred)
# plot result
pred_frame = plt.gca()
plt.imshow(pred_map, 'jet')
pred_frame.axes.get_yaxis().set_visible(False)
pred_frame.axes.get_xaxis().set_visible(False)
pred_frame.spines['top'].set_visible(False)
pred_frame.spines['bottom'].set_visible(False)
pred_frame.spines['left'].set_visible(False)
pred_frame.spines['right'].set_visible(False)
plt.savefig(args.savepath, bbox_inches='tight', pad_inches=0, dpi=150)
plt.close()
print('Script finished successfully.')
def recognize_from_video(video, net):
capture = get_capture(video)
from threading import Event
fin = Event()
def handle_close(evt):
fin.set()
def press(event):
if event.key == 'q':
fin.set()
fig = plt.figure()
fig.canvas.mpl_connect('close_event', handle_close)
fig.canvas.mpl_connect('key_press_event', press)
while not fin.is_set():
ret, frame = capture.read()
if not ret:
continue
pred_map = predict(frame, net)
pred = np.sum(pred_map) / 100.0
pred_map = pred_map / np.max(pred_map + 1e-20)
print("predict:", pred)
# show
pred_frame = plt.gca()
plt.imshow(pred_map, 'jet')
pred_frame.axes.get_yaxis().set_visible(False)
pred_frame.axes.get_xaxis().set_visible(False)
pred_frame.spines['top'].set_visible(False)
pred_frame.spines['bottom'].set_visible(False)
pred_frame.spines['left'].set_visible(False)
pred_frame.spines['right'].set_visible(False)
plt.pause(0.001) # pause a bit so that plots are updated
capture.release()
print('Script finished successfully.')
def main():
dic_model = {
'alexnet': (WEIGHT_ALEXNET_PATH, MODEL_ALEXNET_PATH),
'vgg': (WEIGHT_VGG_PATH, MODEL_VGG_PATH),
'vgg_decoder': (WEIGHT_VGG_DECODER_PATH, MODEL_VGG_DECODER_PATH),
'resnet50': (WEIGHT_RESNET50_PATH, MODEL_RESNET50_PATH),
'resnet101': (WEIGHT_RESNET101_PATH, MODEL_RESNET101_PATH),
'csrnet': (WEIGHT_CSRNET_PATH, MODEL_CSRNET_PATH),
'sanet': (WEIGHT_SANET_PATH, MODEL_SANET_PATH),
}
weight_path, model_path = dic_model[args.model]
# model files check and download
check_and_download_models(weight_path, model_path, REMOTE_PATH)
# initialize
env_id = ailia.get_gpu_environment_id()
net = ailia.Net(model_path, weight_path, env_id=env_id)
if args.video is not None:
recognize_from_video(args.video, net)
else:
recognize_from_image(args.input, net)
if __name__ == '__main__':
main()