图像分类
from openvino.inference_engine import IECore
import numpy as np
import cv2 as cv
ie = IECore() #推理引擎
for device in ie.available_devices: #可用设备
print(device)
with open('imagenet_classes.txt') as f:
labels = [line.strip() for line in f.readlines()]
model_xml = "resnet18.xml"
model_bin = "resnet18.bin"
net = ie.read_network(model=model_xml, weights= model_bin) #读取模型
input_blob = next(iter(net.input_info)) #输入
out_blob = next(iter(net.outputs)) #输出
print("input layout: ",net.input_info[input_blob].layout) #模型输入格式NCHW
print("input precision: ",net.input_info[input_blob].precision) #模型精度F32
print("input shape: ",net.input_info[input_blob].tensor_desc.dims) #模型输入shape[1,3,224,224]
print("output layout: ",net.outputs[out_blob].layout) #模型输出格式NC
print("output precision: ",net.outputs[out_blob].precision) #模型精度F32
print("output shape: ",net.outputs[out_blob].shape) #模型输出shape[1,1000]
n, c, h, w = net.input_info[input_blob].input_data.shape #模型输入shape
print(n, c, h, w)
src = cv.imread("001.jpg") #HWC
image = cv.resize(src, (w, h)) #改变大小到输入大小
image = np.float32(image) / 255.0 #归一化
image[:, :, ] -= (np.float32(0.485), np.float32(0.456), np.float32(0.406))
image[:, :, ] /= (np.float32(0.229), np.float32(0.224), np.float32(0.225))
image = image.transpose(2, 0, 1) #HWC->CHW
exec_net = ie.load_network(network=net, device_name="CPU") #加载模型
res = exec_net.infer(inputs={input_blob:[image]}) #推理
res = res[out_blob] #推理结果 (1,1000)
print(res.shape)
label_index = np.argmax(res, 1)[0] #获取最大概率
print(label_index, labels[label_index])
cv.putText(src, labels[label_index], (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2, 8)
cv.imshow("image classification", src)
cv.waitKey(0)
天道酬勤 循序渐进 技压群雄
浙公网安备 33010602011771号