-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfere_ovino21.4.py~
240 lines (192 loc) · 10.1 KB
/
infere_ovino21.4.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""
@23/02/01 this is originally hello_classification.py
"""
import sys, os
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import argparse
import logging as log
#import cv2, time
import numpy as np
from matplotlib import pyplot as plt
from openvino.inference_engine import IECore, StatusCode
def parse_args() -> argparse.Namespace:
"""Parse and return command line arguments"""
parser = argparse.ArgumentParser(add_help=False)
args = parser.add_argument_group('Options')
# fmt: off
args.add_argument('-h', '--help', action='help',
help='Show this help message and exit.')
args.add_argument('-m', '--model', type=str,
help='Required. Path to an .xml or .onnx file with a trained model.')
args.add_argument('-i', '--input', type=str, nargs='+',
help='Required. Path to an image file(s).')
args.add_argument('-l', '--extension', type=str, default=None,
help='Optional. Required by the CPU Plugin for executing the custom operation on a CPU. '
'Absolute path to a shared library with the kernels implementations.')
args.add_argument('-c', '--config', type=str, default=None,
help='Optional. Required by GPU or VPU Plugins for the custom operation kernel. '
'Absolute path to operation description file (.xml).')
args.add_argument('-d', '--device', default='CPU', type=str,
help='Optional. Specify the target device to infer on; CPU, GPU, MYRIAD, HDDL or HETERO: '
'is acceptable. The sample will look for a suitable plugin for device specified. '
'Default value is CPU.')
args.add_argument('--labels', default=None, type=str, help='Optional. Path to a labels mapping file.')
args.add_argument('-nt', '--number_top', default=10, type=int, help='Optional. Number of top results.')
# fmt: on
return parser.parse_args()
def main():
log.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.INFO, stream=sys.stdout)
args = parse_args()
# ---------------------------Step 1. Initialize inference engine core--------------------------------------------------
log.info('Creating Inference Engine')
ie = IECore()
if args.extension and args.device == 'CPU':
log.info(f'Loading the {args.device} extension: {args.extension}')
ie.add_extension(args.extension, args.device)
if args.config and args.device in ('GPU', 'MYRIAD', 'HDDL'):
log.info(f'Loading the {args.device} configuration: {args.config}')
ie.set_config({'CONFIG_FILE': args.config}, args.device)
# ---------------------------Step 2. Read a model in OpenVINO Intermediate Representation or ONNX format---------------
log.info(f'Reading the network: {args.model}')
# (.xml and .bin files) or (.onnx file)
if 1: # add for my test
# int8 model via onnx runtime
# quantize/dequantize linear layers
args.model = "model.test-int8-Alex.onnx-rt-int8.cut.onnx"
# int8 model via nncf package ovino21.4
# fake-quantized layer
#args.model = "model.test-int8-Alex.ovino-nncrf-int8.ovino21.4_mo.cut" + ".xml"
# image
#fig = "emphasizedImage.tif"
fig = "Accordion-842.jpg"
np_save_name = "save_np_ovino21.4_" + fig + "_" + args.model
net = ie.read_network(model="sample-model/"+args.model)
if len(net.input_info) != 1:
log.error('Sample supports only single input topologies')
return -1
if len(net.outputs) != 1:
log.error('Sample supports only single output topologies')
return -1
# ---------------------------Step 3. Configure input & output----------------------------------------------------------
log.info('Configuring input and output blobs')
# Get names of input and output blobs
input_blob = next(iter(net.input_info))
out_blob = next(iter(net.outputs))
# Set input and output precision manually
#net.input_info[input_blob].precision = 'U8'
net.input_info[input_blob].precision = 'FP32'
net.outputs[out_blob].precision = 'FP32'
iterate = 1 # just 1 input file
# Get a number of input images
num_of_input = iterate #len(args.input)
# Get a number of classes recognized by a model
num_of_classes = max(net.outputs[out_blob].shape)
# ---------------------------Step 4. Loading model to the device-------------------------------------------------------
log.info('Loading the model to the plugin')
exec_net = ie.load_network(network=net, device_name=args.device, num_requests=num_of_input)
print(exec_net)
# ---------------------------Step 5. Create infer request--------------------------------------------------------------
# load_network() method of the IECore class with a specified number of requests (default 1) returns an ExecutableNetwork
# instance which stores infer requests. So you already created Infer requests in the previous step.
# ---------------------------Step 6. Prepare input---------------------------------------------------------------------
input_data = []
_, _, h, w = net.input_info[input_blob].input_data.shape
if 0: # here is original code
for i in range(num_of_input):
#image = cv2.imread(args.input[i])
image = cv2.imread(fig)
if image.shape[:-1] != (h, w):
log.warning(f'Image {args.input[i]} is resized from {image.shape[:-1]} to {(h, w)}')
image = cv2.resize(image, (w, h))
# Change data layout from HWC to CHW
image = image.transpose((2, 0, 1))
# Add N dimension to transform to NCHW
image = np.expand_dims(image, axis=0)
input_data.append(image)
else: # add for just my test
# add for normalization of figure
from PIL import Image, ImageFilter
import torchvision
normalize_GoogleOpenImage = torchvision.transforms.Normalize(
mean=[0.4900, 0.4252, 0.3741],
std=[0.2741, 0.2673, 0.2739]
)
transform_resize_totensor_donorm = torchvision.transforms.Compose([
torchvision.transforms.Resize(2048,interpolation=torchvision.transforms.InterpolationMode.BILINEAR),
torchvision.transforms.ToTensor(),
normalize_GoogleOpenImage,
])
#img = Image.open("sample-image/"+fig)
img = Image.open("sample-image/"+fig).convert('RGB')
img = transform_resize_totensor_donorm( img )
#print(type(img), img.shape)
#<class 'torch.Tensor'> torch.Size([3, 2048, 2048])
#print(img)
#img = img.transpose(2, 0, 1)
img = np.expand_dims(img, 0) # add batch dimension
print(type(img), img.shape)
print("\ninput image = \n", img[0:1,0:1,0:1,0:9], "\n\n")
input_data.append(img)
# ---------------------------Step 7. Do inference----------------------------------------------------------------------
for i in range(iterate):
#log.info('Starting inference in asynchronous mode')
#exec_net.requests[i].async_infer({input_blob: input_data[0]})
#log.info('Starting inference in synchronous mode')
exec_net.infer(inputs={input_blob: input_data[0]})
# ---------------------------Step 8. Process output--------------------------------------------------------------------
# Generate a label list
if args.labels:
with open(args.labels, 'r') as f:
labels = [line.split(',')[0].strip() for line in f]
# Create a list to control a order of output
output_queue = list(range(num_of_input))
while True:
for i in output_queue:
# Immediately returns a inference status without blocking or interrupting
infer_status = exec_net.requests[i].wait(0)
if infer_status == StatusCode.RESULT_NOT_READY:
continue
log.info(f'Infer request {i} returned {infer_status}')
if infer_status != StatusCode.OK:
return -2
# Read infer request results from buffer
res = exec_net.requests[i].output_blobs[out_blob].buffer
#print("Read infer request results from buffer = ", res.shape)
# Read infer request results from buffer = (1, 256, 255, 255)
if 1: # add for my output
print(res.shape)
print("\noutput features = \n", res[0:1,0:1,0:1,0:9], "\n\n")
fig = plt.figure("")
plt.imshow(res[0][0]) # b,c,h,w
#plt.show()
np.save(np_save_name, res[0])
plt.show()
# Change a shape of a numpy.ndarray with results to get another one with one dimension
probs = res.reshape(num_of_classes)
# Get an array of args.number_top class IDs in descending order of probability
top_n_idexes = np.argsort(probs)[-args.number_top :][::-1]
header = 'classid probability'
header = header + ' label' if args.labels else header
log.info(f'Image path: {args.input[i]}')
log.info(f'Top {args.number_top} results: ')
log.info(header)
log.info('-' * len(header))
for class_id in top_n_idexes:
probability_indent = ' ' * (len('classid') - len(str(class_id)) + 1)
label_indent = ' ' * (len('probability') - 8) if args.labels else ''
label = labels[class_id] if args.labels else ''
log.info(f'{class_id}{probability_indent}{probs[class_id]:.7f}{label_indent}{label}')
log.info('')
output_queue.remove(i)
if len(output_queue) == 0:
break
# ----------------------------------------------------------------------------------------------------------------------
log.info('This sample is an API example, for any performance measurements please use the dedicated benchmark_app tool\n')
return 0
if __name__ == '__main__':
sys.exit(main())