openvino之图像分类
基于resnet18的图像分类,1000个类别。
openvino工作机制:
下面是代码:
1 import cv2 as cv 2 import numpy as np 3 from openvino.inference_engine import IECore 4 5 6 ''' 7 1、读取模型、声明推理器 8 ''' 9 ie = IECore() 10 for device in ie.available_devices: 11 print(device) 12 model_xml = "resnet18.xml" 13 model_bin = "resnet18.bin" 14 # read the net 15 net = ie.read_network(model=model_xml, weights=model_bin) 16 # 获取网络的输入、输出 17 input_blob = next(iter(net.inputs)) 18 out_blob = next(iter(net.outputs)) 19 n, c, h, w = net.inputs[input_blob].shape 20 print(n, c, h, w) # 1 3 224 224 xml文件前面就有 21 # 声明推理器 22 exec_net = ie.load_network(network=net, device_name="CPU") 23 ''' 24 2、读取类别文件 25 ''' 26 with open('imagenet_classes.txt') as f: 27 labels = [line.strip() for line in f.readlines()] 28 ''' 29 3、读取图像和预处理 30 ''' 31 src = cv.imread("d:/3.png") 32 # resize 33 image = cv.resize(src, (w, h)) 34 # 归一化 35 image = np.float32(image) / 255.0 36 # 减去均值 37 image[:, :, ] -= (np.float32(0.485), np.float32(0.456), np.float32(0.406)) 38 image[:, :, ] /= (np.float32(0.229), np.float32(0.224), np.float32(0.225)) 39 # -> c, h, w 40 image = image.transpose(2, 0, 1) 41 ''' 42 4、推理 & 解析结果 43 ''' 44 res = exec_net.infer(inputs={input_blob:[image]}) #[]:使得c, h, w -> 1, c, h, w;其实就是batch_size = 1 45 # 获取网络输出 46 res = res[out_blob] # 1000个分类的置信度 47 label_index = np.argmax(res, 1) # 最大置信度索引 48 print(labels[label_index[0]]) 49 ''' 50 可视化 51 ''' 52 cv.putText(src, labels[label_index[0]], (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 2, 8) 53 cv.imshow("image classification", src) 54 cv.waitKey(0)
CV&DL