编写 OpenVINO 应用程序(Python 版)
设置环境变量
添加一个名为 PYTHONPATH
的环境变量,并为该变量添加两个路径:
C:\Program Files (x86)\IntelSWTools\openvino_2019.3.334\python\python3 和 C:\Program Files (x86)\IntelSWTools\openvino_2019.3.334\python\python3.6
其中第一个路径是包含 OpenCV Python 模块的路径,第二个路径是包含 OpenVINO Python 模块的路径。设置好了该环境变量,我们才能正常导入相关的库。
例1:编写程序(使用 OpenCV 库)
通过 OpenCV dnn 模块来调用 OpenVINO,实现 AI 推理计算。
#导入opencv-openvino模块
import cv2 as cv
import time
#配置推断计算设备,IR文件路径,图片路径
DEVICE = cv.dnn.DNN_TARGET_CPU
model_xml = 'D:/tf_train/workspaces/cats_dogs/IR_model/cats_dogs_detector.xml'
model_bin = 'D:/tf_train/workspaces/cats_dogs/IR_model/cats_dogs_detector.bin'
image_file = 'D:/tf_train/workspaces/cats_dogs/images/test/3.jpg'
#读取IR模型文件
net = cv.dnn.readNet(model_xml, model_bin)
#指定AI推断执行硬件
net.setPreferableTarget(DEVICE)
#读取图片
img = cv.imread(image_file)
#将图片传入模型的输入张量
blob = cv.dnn.blobFromImage(img,ddepth=cv.CV_8U)
net.setInput(blob)
#执行推断计算
start = time.time()
out = net.forward()
end = time.time()
print("Infer Time:{}ms".format((end-start)*1000))
#处理推断计算结果
for detection in out.reshape(-1, 7):
confidence = float(detection[2])
xmin = int(detection[3] * img.shape[1])
ymin = int(detection[4] * img.shape[0])
xmax = int(detection[5] * img.shape[1])
ymax = int(detection[6] * img.shape[0])
if confidence>0.7:
cv.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0))
conf = "{:.4f}".format(confidence)
font = cv.FONT_HERSHEY_COMPLEX_SMALL
cv.putText(img, conf, (xmin, ymin - 5), font, 1, (0, 0, 255))
#显示处理结果
cv.imshow("Detection results",img)
cv.waitKey(0)
cv.destroyAllWindows()
print("Inference is completed...")
例2:编写程序(直接使用 OpenVINO)
直接用 OpenVINO Python API 编写的程序,比用 OpenCV DNN 模块编写的程序运行速度快。
#导入IE/OpenCV/numpy/time模块
from openvino.inference_engine import IECore, IENetwork
import cv2
import numpy as np
from time import time
#配置推断计算设备,IR文件路径,图片路径
DEVICE = 'CPU'
model_xml = 'D:/tf_train/workspaces/cats_dogs/IR_model/cats_dogs_detector.xml'
model_bin = 'D:/tf_train/workspaces/cats_dogs/IR_model/cats_dogs_detector.bin'
image_file = 'D:/tf_train/workspaces/cats_dogs/images/test/3.jpg'
cpu_extension_lib = "C:/Program Files (x86)/IntelSWTools/openvino_2019.2.275/inference_engine/bin/intel64/Release/cpu_extension.dll"
labels_map = ["fake","cat","dog"]
#初始化插件,输出插件版本号
ie = IECore()
ver = ie.get_versions(DEVICE)[DEVICE]
print("{descr}: {maj}.{min}.{num}".format(descr=ver.description, maj=ver.major, min=ver.minor, num=ver.build_number))
#加载CPU插件扩展库
if cpu_extension_lib and 'CPU' in DEVICE:
ie.add_extension(cpu_extension_lib, "CPU")
#读取IR模型文件
net = IENetwork(model=model_xml, weights=model_bin)
#准备输入输出张量
print("Preparing input blobs")
input_blob = next(iter(net.inputs))
out_blob = next(iter(net.outputs))
net.batch_size = 1
#载入模型到AI推断计算设备
print("Loading IR to the plugin...")
exec_net = ie.load_network(network=net, num_requests=1, device_name=DEVICE)
#读入图片
n, c, h, w = net.inputs[input_blob].shape
frame = cv2.imread(image_file)
initial_h, initial_w, channels = frame.shape
#按照AI模型要求放缩图片
image = cv2.resize(frame, (w, h))
#按照AI模型要求将图像数据结构从HWC转为CHW
image = image.transpose((2, 0, 1))
print("Batch size is {}".format(n))
#执行推断计算
print("Starting inference in synchronous mode")
start = time()
res = exec_net.infer(inputs={input_blob: image})
end = time()
print("Infer Time:{}ms".format((end-start)*1000))
# 处理输出
print("Processing output blob")
res = res[out_blob]
for obj in res[0][0]:
# 当信心指数大于0.7时,显示检测结果
if obj[2] > 0.7:
xmin = int(obj[3] * initial_w)
ymin = int(obj[4] * initial_h)
xmax = int(obj[5] * initial_w)
ymax = int(obj[6] * initial_h)
class_id = int(obj[1])
# 显示信心指数,物体标签和边界框
color = (0,255,0) if class_id>1 else(255,0,0)
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color, 2)
det_label = labels_map[class_id] if labels_map else str(class_id)
cv2.putText(frame, det_label + ' ' + str(round(obj[2] * 100, 1)) + ' %', (xmin, ymin - 7),
cv2.FONT_HERSHEY_COMPLEX, 0.6, color, 1)
print("Inference is completed")
#显示处理结果
cv2.imshow("Detection results",frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
两种开发方式对比
通过 OpenCV DNN 模块来调用 OpenVINO 实现 AI 推理计算的好处是代码非常简单,写起来很容易。其缺点是 OpenCV 是社区维护的开源软件,对英特尔的 AI 计算硬件支持得没有 OpenVINO 工具套件那么好,所以时间代价比较高。
如果直接用 OpenVINO Python API 来编写程序,那么得到的程序的运行速度会比 OpenCV DNN 模块编写的程序快很多。