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模型文件?
进阶学习:《深度学习图像识别技术》

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值