Python实现AI推理程序:不到二十行代码

  在Python下实现AI推理程序非常简单,除去模块引用和常量定义,真正实现AI推理计算的程序不到二十行!真正用于AI推理计算的函数只有五个!

  • 第一步,用cv.dnn.readNet()读入OpenVINO格式的IR模型文件
  • 第二步,用net.setPreferableTarget(DEVICE)指定AI推理计算执行硬件
  • 第三步,用cv.dnn.blobFromImage()和net.setInput()将图像数据传给AI模型
  • 第四步,用net.forward()实现AI推理计算
  • 第五步,分析推理计算结果
用Python 基于OpenCV和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...")

如何训练自己的AI模型,如何获得OpenVINO IR模型文件?
进阶学习:《深度学习图像识别技术》

发布了8 篇原创文章 · 获赞 0 · 访问量 138

猜你喜欢

转载自blog.csdn.net/qq_41802192/article/details/105305414