前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OpenVINO2023异步回调流水线提升推理吞吐率

OpenVINO2023异步回调流水线提升推理吞吐率

作者头像
OpenCV学堂
发布2023-11-21 16:30:00
4361
发布2023-11-21 16:30:00
举报

同步模式推理流程

OpenVINO2023版本的SDK支持同步与异步推理模式相比之前OpenVINO2021版本更加的简洁,易用。同时支持创建多个Requst然后基于多个Requst实现流水线方式的推理从而提升CPU推理的吞吐率。同步模式下OpenVINO2023 SDK的推理方式如下:

推理的流程如下:

代码语言:javascript
复制
while(true) {
  // capture frame
  // populate CURRENT InferRequest
  // Infer CURRENT InferRequest
  //this call is synchronous
  // display CURRENT result
}

以YOLOv5s的模型为例,在OpenVINO C++上同步推理的代码实现如下:

代码语言:javascript
复制
// 创建IE插件, 查询支持硬件设备
ov::Core core;
std::string model_onnx = "D:/python/yolov5-7.0/yolov5s.onnx";
auto model = core.read_model(model_onnx);
ov::CompiledModel cmodel = core.compile_model(model, "CPU");


// create infer request
auto request = cmodel.create_infer_request();
cv::Mat frame;
while (true) {
  bool ret = cap.read(frame);
  if (frame.empty()) {
    break;
  }
  image_detect(frame, request);
  char c = cv::waitKey(1);
  if (c == 27) { // ESC
    break;
  }
}

其中image_detect方法包含模型的图像前处理、同步推理、后处理。其中同步推理:

代码语言:javascript
复制
// 前处理
// 开启同步
request.infer();
// 后处理

运行结果如下:

异步模式推理流程

当使用OpenVINO2023提供的Request对象的回调功能以后,我们可以把模型的后处理直接放到回调中去,这样异步推理方式就变成只有图像前处理+模型推两个步骤了,然后通过创建两个Request基于流水线方式,实现异步流水线模式推理方式,这个时候推理流程如下:

推理的流程如下:

代码语言:javascript
复制
while(true) {
  // capture frame
  // populate NEXT InferRequest
  // start NEXT InferRequest
  // this call is async and returns immediately
  // wait for the CURRENT InferRequest
  // display CURRENT result
  // swap CURRENT and NEXT InferRequests
}

首先需要创建两个Request,然后分别设置它们的Callback部分代码,主要是在Callback中完成后处理操作。这部分的代码如下:

代码语言:javascript
复制
// 创建IE插件, 查询支持硬件设备
ov::Core core;
std::string model_onnx = "D:/python/yolov5-7.0/yolov5s.onnx";
auto model = core.read_model(model_onnx);
ov::CompiledModel cmodel = core.compile_model(model, "AUTO");

// create infer request
auto request = cmodel.create_infer_request();
auto next_request = cmodel.create_infer_request();
std::exception_ptr exception_var;
request.set_callback([&](std::exception_ptr ex) {
    if (ex) {
        exception_var = ex;
        return;
    }
    det_boxes.clear();
    det_ids.clear();
    ov::Tensor output = request.get_output_tensor();
    const float* prob = (float*)output.data();
    const ov::Shape outputDims = output.get_shape();
    size_t numRows = outputDims[1];
    size_t numCols = outputDims[2];

    // 后处理, 1x25200x85
    std::vector<cv::Rect> boxes;
    std::vector<int> classIds;
    std::vector<float> confidences;
    cv::Mat det_output(numRows, numCols, CV_32F, (float*)prob);
    for (int i = 0; i < det_output.rows; i++) {
        float confidence = det_output.at<float>(i, 4);
        if (confidence < 0.45) {
            continue;
        }
        cv::Mat classes_scores = det_output.row(i).colRange(5, numCols);
        cv::Point classIdPoint;
        double score;
        minMaxLoc(classes_scores, 0, &score, 0, &classIdPoint);

        // 置信度 0~1之间
        if (score > 0.25)
        {
            float cx = det_output.at<float>(i, 0);
            float cy = det_output.at<float>(i, 1);
            float ow = det_output.at<float>(i, 2);
            float oh = det_output.at<float>(i, 3);
            int x = static_cast<int>((cx - 0.5 * ow) * x_factor);
            int y = static_cast<int>((cy - 0.5 * oh) * y_factor);
            int width = static_cast<int>(ow * x_factor);
            int height = static_cast<int>(oh * y_factor);
            cv::Rect box;
            box.x = x;
            box.y = y;
            box.width = width;
            box.height = height;

            boxes.push_back(box);
            classIds.push_back(classIdPoint.x);
            confidences.push_back(score);
        }
    }

    // NMS
    std::vector<int> indexes;
    cv::dnn::NMSBoxes(boxes, confidences, 0.25, 0.45, indexes);
    for (size_t i = 0; i < indexes.size(); i++) {
        int index = indexes[i];
        det_ids.emplace_back(classIds[index]);
        det_boxes.emplace_back(boxes[index]);
    }
});

依据上述的推理流程,最终调用执行的代码如下:

代码语言:javascript
复制
cv::Mat frame, next_frame;
// do first frame
cap.read(frame);
async_image_detect(frame, request);
std::chrono::milliseconds tout{ 50 };
int cnt = 0;
while (true) {
    bool ret = cap.read(next_frame);
    if (next_frame.empty()) {
        break;
    }

    int64 start = cv::getTickCount();
    // 继续异步
    if (cnt % 2 == 0) {
        async_image_detect(next_frame, next_request);
        request.wait_for(tout);
    }
    if (cnt % 2 == 1) {
        async_image_detect(next_frame, request);
        next_request.wait_for(tout);
    }
    for (size_t t = 0; t < det_boxes.size(); t++) {
        int idx = det_ids[t];
        cv::rectangle(frame, det_boxes[t], colors_table[idx % 6], 2, 8, 0);
        putText(frame, classNames[idx].c_str(), det_boxes[t].tl(), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(255, 0, 0), 1, 8);
    }

    // 计算FPS render it
    float t = (cv::getTickCount() - start) / static_cast<float>(cv::getTickFrequency());
    putText(frame, cv::format("FPS: %.2f", 1.0 / t), cv::Point(20, 40), cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(255, 0, 0), 2, 8);
    cv::imshow("OpenVINO2023 - YOLOv5 7.0 异步推理", frame);
    char c = cv::waitKey(1);
    if (c == 27) { // ESC
        break;
    }
    next_frame.copyTo(frame);
    cnt++;
}
cv::waitKey(0);
cv::destroyAllWindows();
return 0;

其中async_image_detect方法中实现了YOLOv5模型推理的图像前处理与启动异步推理模式

代码语言:javascript
复制
preprocess(frame)
// 开启异步
request.start_async();

最终运行效果如下:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-11-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 OpenCV学堂 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档