【学习】1.win环境安装openvino,并对yolov5进行部署

该文章用来记录学习过程,如有错误,还请大佬指正。

1.首先在anaconda下创建一个新环境

conda create -n openvino python=3.9

2.打开openvino官网

https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/download.html?ENVIRONMENT=DEV_TOOLS&OP_SYSTEM=WINDOWS&VERSION=v_2022_3_1&DISTRIBUTION=PIP&FRAMEWORK=ONNX%2CPYTORCH

 按照下图选择,打开刚才创建的环境,输入step-4安装

 3.下载yolov5并通过export.py程序生成onnx文件。

4.然后在openvino环境下执行命令

python mo_onnx.py   --input_model (onnx位置) --model_name(输出位置)

例如:

运行后会在输出位置生成三个文件:

 

6.运用下面代码,使用刚生成的open.xml文件,完成yolov5的推理过程。 

import cv2
import numpy as np
import time
import os
# from openvino.runtime import Core  # the version of openvino >= 2022.1 # openvino 2022.1.0 has requirement numpy<1.20,>=1.16.6
from openvino.inference_engine import IECore  # the version of openvino <= 2021.4.2

classes = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
           'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
           'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
           'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
           'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
           'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
           'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
           'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
           'hair drier', 'toothbrush']  # class names


class OpenVinoYoloV5Detector():

    def __init__(self, IN_conf):
        # ie = Core()  # Initialize Core version>=2022.1
        # self.Net = ie.compile_model(model=IN_conf.get("weight_file"),device_name=IN_conf.get("device"))

        ie = IECore()  # Initialize IECore  openvino <= 2021.4.2
        self.Net = ie.load_network(network=IN_conf.get("weight_file"), device_name=IN_conf.get("device"))

        self.INPUT_HEIGHT = 640
        self.INPUT_WIDTH = 640

    # YOLOv5目标检测
    def detect(self, image):

        blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (self.INPUT_WIDTH, self.INPUT_HEIGHT), swapRB=True, crop=False)

        # openvino >= 2022.1
        # results = net([blob])[next(iter(net.outputs))]
        # results = self.Net([blob])[self.Net.output(0)]

        # openvino <= 2021.4.2
        results = self.Net.infer(inputs={"images": blob})
        results = results["output"]

        self.process_results(image, results)

    # YOLOv5的后处理函数,解析模型的输出
    def process_results(self, image, results, thresh=0.25):

        h, w, _ = image.shape

        class_ids = []
        boxes = []
        scores = []

        results = results[0]
        rows = results.shape[0]

        y_factor = h / self.INPUT_HEIGHT
        x_factor = w / self.INPUT_WIDTH

        for r in range(rows):
            row = results[r]
            score = row[4]

            if score >= 0.4:

                classes_scores = row[5:]

                _, _, _, max_indexes = cv2.minMaxLoc(classes_scores)
                class_id = max_indexes[1]

                if classes_scores[class_id] > 0.25:
                    x, y, w, h = row[0].item(), row[1].item(), row[2].item(), row[3].item()

                    x1 = int((x - 0.5 * w) * x_factor)
                    y1 = int((y - 0.5 * h) * y_factor)
                    x2 = x1 + int(w * x_factor)
                    y2 = y1 + int(h * y_factor)
                    boxes.append((x1, y1, x2, y2))
                    class_ids.append(class_id)
                    scores.append(score)

        # default score_threshold=0.25, nms_threshold=0.45
        indices = cv2.dnn.NMSBoxes(bboxes=boxes, scores=scores, score_threshold=thresh, nms_threshold=0.45)

        for index in indices:
            x1, y1, x2, y2 = boxes[index][0], boxes[index][1], boxes[index][2], boxes[index][3]
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(frame, str(classes[class_ids[index]]), (x1, y1 + 20), cv2.FONT_HERSHEY_SIMPLEX, .5,
                        (255, 255, 255))


if __name__ == '__main__':
    a=time.time()
    IN_conf = {
        "weight_file": r"D:\code\yolov5-6.2\open\open.xml",
        "device": "CPU"  # "GPU"
    }
    path='D:/code/yolov5-6.2/data/img'
    detector = OpenVinoYoloV5Detector(IN_conf=IN_conf)
    for filename in os.listdir(path):
        frame = path + "/" + filename
        frame=cv2.imread(frame)
        detector.detect(frame)
    b=time.time()
    print(b-a)

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mmasterer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值