国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

yolov8 opencv模型部署(C++版)

這篇具有很好參考價值的文章主要介紹了yolov8 opencv模型部署(C++版)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

  • TensorRT系列之 Windows10下yolov8 tensorrt模型加速部署

  • TensorRT系列之 Linux下 yolov8 tensorrt模型加速部署

  • TensorRT系列之 Linux下 yolov7 tensorrt模型加速部署

  • TensorRT系列之 Linux下 yolov6 tensorrt模型加速部署

  • TensorRT系列之 Linux下 yolov5 tensorrt模型加速部署

  • TensorRT系列之 Linux下 yolox tensorrt模型加速部署

  • TensorRT系列之 Linux下 u2net tensorrt模型加速部署

  • 更多(點我進去)…

yolov8 opencv模型部署(C++ 版)

使用opencv推理yolov8模型,僅依賴opencv,無需其他庫,以yolov8s為例子,注意:

  • 使用opencv4.8.1 !
  • 使用opencv4.8.1 !
  • 使用opencv4.8.1 !
    如果你使用別的版本,例如opencv4.5,可能會出現(xiàn)以下錯誤。
    yolov8 opencv模型部署(C++版),OpenCV,YOLO,yolov8,opencv,c++,深度學習,目標檢測,計算機視覺

20231206新增推理效果,代碼修改。
yolov8 opencv模型部署(C++版),OpenCV,YOLO,yolov8,opencv,c++,深度學習,目標檢測,計算機視覺
yolov8 opencv模型部署(C++版),OpenCV,YOLO,yolov8,opencv,c++,深度學習,目標檢測,計算機視覺

一、安裝yolov8

conda create -n yolov8 python=3.9 -y
conda activate yolov8
pip install ultralytics -i https://pypi.tuna.tsinghua.edu.cn/simple

二、導出onnx

導出onnx格式模型的時候,注意,如果你是自己訓練的模型,只需要把以下代碼中yolov8s.pt修改為自己的模型即可,如best.pt。如果是下面代碼中默認的模型,并且你沒有下載到本地,系統(tǒng)會自動下載,我這里在文章末尾提供了下載鏈接。

將以下代碼創(chuàng)建、拷貝到y(tǒng)olov8根目錄下。

具體代碼my_export.py:

from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt')  # load an official model
# Export the model
model.export(format='onnx', imgsz=[480, 640], opset=12) # 導出一定不要修改這里參數(shù)

執(zhí)行導出命令:

python my_export.py

輸出如下圖信息,表明onnx格式的模型被成功導出,保存在my_export.py同一級目錄。
yolov8 opencv模型部署(C++版),OpenCV,YOLO,yolov8,opencv,c++,深度學習,目標檢測,計算機視覺

三、基于opencv CPP推理onnx

使用opencv4.8.0,linux和windows都可以,下面以windows為例子。注:運行代碼需要onnx模型 + 一張圖,文末給了下載鏈接,classes.txt不需要。

以下是主函數(shù)文件main.cpp:

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include "inference.h"
using namespace std;
using namespace cv;

int main(int argc, char **argv)
{
    bool runOnGPU = false;

    // 1. 設(shè)置你的onnx模型
    // Note that in this example the classes are hard-coded and 'classes.txt' is a place holder.
    Inference inf("D:/CodePython/ultralytics/yolov8s.onnx", cv::Size(640, 480), "classes.txt", runOnGPU); // classes.txt 可以缺失

    // 2. 設(shè)置你的輸入圖片
    std::vector<std::string> imageNames;
    imageNames.push_back("bus.jpg");
    //imageNames.push_back("zidane.jpg");

    for (int i = 0; i < imageNames.size(); ++i)
    {
        cv::Mat frame = cv::imread(imageNames[i]);

        // Inference starts here...
        std::vector<Detection> output = inf.runInference(frame);

        int detections = output.size();
        std::cout << "Number of detections:" << detections << std::endl;

        // feiyull
        // 這里需要resize下,否則結(jié)果不對
        //cv::resize(frame, frame, cv::Size(480, 640));

        for (int i = 0; i < detections; ++i)
        {
            Detection detection = output[i];

            cv::Rect box = detection.box;
            cv::Scalar color = detection.color;

            // Detection box
            cv::rectangle(frame, box, color, 2);

            // Detection box text
            std::string classString = detection.className + ' ' + std::to_string(detection.confidence).substr(0, 4);
            cv::Size textSize = cv::getTextSize(classString, cv::FONT_HERSHEY_DUPLEX, 1, 2, 0);
            cv::Rect textBox(box.x, box.y - 40, textSize.width + 10, textSize.height + 20);

            cv::rectangle(frame, textBox, color, cv::FILLED);
            cv::putText(frame, classString, cv::Point(box.x + 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);
        }
        cv::imshow("Inference", frame);
        cv::waitKey(0);
        cv::destroyAllWindows();
    }
}

以下是運行效果圖:
yolov8 opencv模型部署(C++版),OpenCV,YOLO,yolov8,opencv,c++,深度學習,目標檢測,計算機視覺
其他依賴文件:inference.h、inference.cpp
inference.h:

#ifndef INFERENCE_H
#define INFERENCE_H

// Cpp native
#include <fstream>
#include <vector>
#include <string>
#include <random>

// OpenCV / DNN / Inference
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>

struct Detection
{
    int class_id{0};
    std::string className{};
    float confidence{0.0};
    cv::Scalar color{};
    cv::Rect box{};
};

class Inference
{
public:
    Inference(const std::string &onnxModelPath, const cv::Size &modelInputShape = {640, 640}, const std::string &classesTxtFile = "", const bool &runWithCuda = true);
    std::vector<Detection> runInference(const cv::Mat &input);

private:
    void loadClassesFromFile();
    void loadOnnxNetwork();
    cv::Mat formatToSquare(const cv::Mat &source);

    std::string modelPath{};
    std::string classesPath{};
    bool cudaEnabled{};

    std::vector<std::string> 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"};

    cv::Size2f modelShape{};

    float modelConfidenceThreshold {0.25};
    float modelScoreThreshold      {0.45};
    float modelNMSThreshold        {0.50};

    bool letterBoxForSquare = true;

    cv::dnn::Net net;
};

#endif // INFERENCE_H

inference.cpp

#include "inference.h"

Inference::Inference(const std::string &onnxModelPath, const cv::Size &modelInputShape, const std::string &classesTxtFile, const bool &runWithCuda)
{
    modelPath = onnxModelPath;
    modelShape = modelInputShape;
    classesPath = classesTxtFile;
    cudaEnabled = runWithCuda;

    loadOnnxNetwork();
    // loadClassesFromFile(); The classes are hard-coded for this example
}

std::vector<Detection> Inference::runInference(const cv::Mat &input)
{
    cv::Mat modelInput = input;
    if (letterBoxForSquare && modelShape.width == modelShape.height)
        modelInput = formatToSquare(modelInput);

    cv::Mat blob;
    cv::dnn::blobFromImage(modelInput, blob, 1.0/255.0, modelShape, cv::Scalar(), true, false);
    net.setInput(blob);

    std::vector<cv::Mat> outputs;
    net.forward(outputs, net.getUnconnectedOutLayersNames());

    int rows = outputs[0].size[1];
    int dimensions = outputs[0].size[2];

    bool yolov8 = false;
    // yolov5 has an output of shape (batchSize, 25200, 85) (Num classes + box[x,y,w,h] + confidence[c])
    // yolov8 has an output of shape (batchSize, 84,  8400) (Num classes + box[x,y,w,h])
    if (dimensions > rows) // Check if the shape[2] is more than shape[1] (yolov8)
    {
        yolov8 = true;
        rows = outputs[0].size[2];
        dimensions = outputs[0].size[1];

        outputs[0] = outputs[0].reshape(1, dimensions);
        cv::transpose(outputs[0], outputs[0]);
    }
    float *data = (float *)outputs[0].data;

    float x_factor = modelInput.cols / modelShape.width;
    float y_factor = modelInput.rows / modelShape.height;

    std::vector<int> class_ids;
    std::vector<float> confidences;
    std::vector<cv::Rect> boxes;

    for (int i = 0; i < rows; ++i)
    {
        if (yolov8)
        {
            float *classes_scores = data+4;

            cv::Mat scores(1, classes.size(), CV_32FC1, classes_scores);
            cv::Point class_id;
            double maxClassScore;

            minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);

            if (maxClassScore > modelScoreThreshold)
            {
                confidences.push_back(maxClassScore);
                class_ids.push_back(class_id.x);

                float x = data[0];
                float y = data[1];
                float w = data[2];
                float h = data[3];

                int left = int((x - 0.5 * w) * x_factor);
                int top = int((y - 0.5 * h) * y_factor);

                int width = int(w * x_factor);
                int height = int(h * y_factor);

                boxes.push_back(cv::Rect(left, top, width, height));
            }
        }
        else // yolov5
        {
            float confidence = data[4];

            if (confidence >= modelConfidenceThreshold)
            {
                float *classes_scores = data+5;

                cv::Mat scores(1, classes.size(), CV_32FC1, classes_scores);
                cv::Point class_id;
                double max_class_score;

                minMaxLoc(scores, 0, &max_class_score, 0, &class_id);

                if (max_class_score > modelScoreThreshold)
                {
                    confidences.push_back(confidence);
                    class_ids.push_back(class_id.x);

                    float x = data[0];
                    float y = data[1];
                    float w = data[2];
                    float h = data[3];

                    int left = int((x - 0.5 * w) * x_factor);
                    int top = int((y - 0.5 * h) * y_factor);

                    int width = int(w * x_factor);
                    int height = int(h * y_factor);

                    boxes.push_back(cv::Rect(left, top, width, height));
                }
            }
        }

        data += dimensions;
    }

    std::vector<int> nms_result;
    cv::dnn::NMSBoxes(boxes, confidences, modelScoreThreshold, modelNMSThreshold, nms_result);

    std::vector<Detection> detections{};
    for (unsigned long i = 0; i < nms_result.size(); ++i)
    {
        int idx = nms_result[i];

        Detection result;
        result.class_id = class_ids[idx];
        result.confidence = confidences[idx];

        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<int> dis(100, 255);
        result.color = cv::Scalar(dis(gen),
                                  dis(gen),
                                  dis(gen));

        result.className = classes[result.class_id];
        result.box = boxes[idx];

        detections.push_back(result);
    }

    return detections;
}

void Inference::loadClassesFromFile()
{
    std::ifstream inputFile(classesPath);
    if (inputFile.is_open())
    {
        std::string classLine;
        while (std::getline(inputFile, classLine))
            classes.push_back(classLine);
        inputFile.close();
    }
}

void Inference::loadOnnxNetwork()
{
    net = cv::dnn::readNetFromONNX(modelPath);
    if (cudaEnabled)
    {
        std::cout << "\nRunning on CUDA" << std::endl;
        net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
        net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
    }
    else
    {
        std::cout << "\nRunning on CPU" << std::endl;
        net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
        net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
    }
}

cv::Mat Inference::formatToSquare(const cv::Mat &source)
{
    int col = source.cols;
    int row = source.rows;
    int _max = MAX(col, row);
    cv::Mat result = cv::Mat::zeros(_max, _max, CV_8UC3);
    source.copyTo(result(cv::Rect(0, 0, col, row)));
    return result;
}

完整代碼+數(shù)據(jù)下載:
鏈接:https://pan.baidu.com/s/1XcgPSzxFhgxYEONum3dJFA?pwd=xcof
提取碼:xcof文章來源地址http://www.zghlxwxcb.cn/news/detail-712825.html

到了這里,關(guān)于yolov8 opencv模型部署(C++版)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • [C++]使用純opencv部署yolov8旋轉(zhuǎn)框目標檢測

    [C++]使用純opencv部署yolov8旋轉(zhuǎn)框目標檢測

    【官方框架地址】 https://github.com/ultralytics/ultralytics 【算法介紹】 YOLOv8是一種先進的對象檢測算法,它通過單個神經(jīng)網(wǎng)絡(luò)實現(xiàn)了快速的物體檢測。其中,旋轉(zhuǎn)框檢測是YOLOv8的一項重要特性,它可以有效地檢測出不同方向和角度的物體。 旋轉(zhuǎn)框檢測的原理是通過預測物體的邊界

    2024年04月26日
    瀏覽(28)
  • 模型實戰(zhàn)(11)之win10下Opencv+CUDA部署yolov5、yolov8算法

    模型實戰(zhàn)(11)之win10下Opencv+CUDA部署yolov5、yolov8算法

    測試環(huán)境:AMDRH7000+RTX3050+win10+vs2-10+opencv455+cuda11.7 關(guān)于opencv470+contrib+cuda的編譯,可以詳見:Win10下Opencv+CUDA聯(lián)合編譯詳細教程 本文代碼同時支持 yolov5 、 yolov8 兩個模型,詳細過程將在文中給出, 完整代碼倉庫最后給出 其中,yolov8在opencv-DNN + CUDA下的效果如下: 新建VS項目,名

    2024年02月16日
    瀏覽(23)
  • 【模型部署】使用opencv C++ 加速YOLO V5

    【模型部署】使用opencv C++ 加速YOLO V5

    在ultralytics/YOLO V5中官方給出了利用opencv c++ cuda 進行YOLO V5加速的實例代碼,但是代碼中并沒有給出相關(guān)注釋,今天花了些時間,把示例源碼仔細看了看,并把每一部分都進行了詳細注釋。內(nèi)容在下方,歡迎大家交流學習。 官網(wǎng)示例源碼參考鏈接:doleron/yolov5-opencv-cpp-python: E

    2024年02月02日
    瀏覽(22)
  • [C++]使用yolov8的onnx模型僅用opencv和bytetrack實現(xiàn)目標追蹤

    [C++]使用yolov8的onnx模型僅用opencv和bytetrack實現(xiàn)目標追蹤

    【官方框架地址】 yolov8: https://github.com/ultralytics/ultralytics bytetrack: https://github.com/ifzhang/ByteTrack 【算法介紹】 隨著人工智能技術(shù)的不斷發(fā)展,目標追蹤已成為計算機視覺領(lǐng)域的重要研究方向。Yolov8和ByTetrack作為當前先進的算法,當它們結(jié)合使用時,能夠顯著提升目標追蹤的準

    2024年01月24日
    瀏覽(26)
  • 【YOLO】Windows 下 YOLOv8 使用 TensorRT 進行模型加速部署

    【YOLO】Windows 下 YOLOv8 使用 TensorRT 進行模型加速部署

    本文全文參考文章為 win10下 yolov8 tensorrt模型加速部署【實戰(zhàn)】 本文使用的代碼倉庫為 TensorRT-Alpha 注:其他 Yolov8 TensorRT 部署項目:YOLOv8 Tensorrt Python/C++部署教程 安裝Visual Studio 2019或者Visual Studio 2022、Nvidia驅(qū)動 安裝cuda,cudnn、opencv、tensorrt并進行相應(yīng)的環(huán)境配置,這里不做配

    2024年02月11日
    瀏覽(25)
  • C++模型部署:qt+yolov5/6+onnxruntime+opencv

    C++模型部署:qt+yolov5/6+onnxruntime+opencv

    作者平時主要是寫 c++ 庫的,界面方面了解不多,也沒有發(fā)現(xiàn)“美”的眼鏡,界面有點丑,大家多包涵。 本次介紹的項目主要是通過 cmake 構(gòu)建一個 基于 c++ 語言的,以 qt 為框架的,包含 opencv 第三方庫在內(nèi)的,跨平臺的,使用 ONNX RUNTIME 進行前向推理的 yolov5/6 演示平臺。文章

    2024年02月05日
    瀏覽(23)
  • Opencv C++實現(xiàn)yolov5部署onnx模型完成目標檢測

    頭文件 命名空間 結(jié)構(gòu)體 Net_config 里面存了三個閾值和模型地址,其中 置信度 ,顧名思義,看檢測出來的物體的精準度。以測量值為中心,在一定范圍內(nèi),真值出現(xiàn)在該范圍內(nèi)的幾率。 endsWith()函數(shù) 判斷sub是不是s的子串 anchors_640圖像接收數(shù)組 根據(jù)圖像大小,選擇相應(yīng)長度的

    2024年02月13日
    瀏覽(25)
  • [C++]使用純opencv去部署yolov9的onnx模型

    [C++]使用純opencv去部署yolov9的onnx模型

    【介紹】 部署 YOLOv9 ONNX 模型在 OpenCV 的 C++ 環(huán)境中涉及一系列步驟。以下是一個簡化的部署方案概述,以及相關(guān)的文案。 部署方案概述: 模型準備 :首先,你需要確保你有 YOLOv9 的 ONNX 模型文件。這個文件包含了模型的結(jié)構(gòu)和權(quán)重。 環(huán)境配置 :安裝 OpenCV 庫,并確保它支持

    2024年03月13日
    瀏覽(58)
  • yolov8 opencv dnn部署 github代碼

    yolov8 opencv dnn部署 github代碼

    源碼地址 本人使用的opencv c++ github代碼,代碼作者非本人 實現(xiàn)推理源碼中作者的yolov8s.onnx 推理條件 windows 10 Visual Studio 2019 Nvidia GeForce GTX 1070 opencv4.7.0 (opencv4.5.5在別的地方看到不支持yolov8的推理,所以只使用opencv4.7.0) c++部署 先將源碼復制到下圖位置中 環(huán)境和代碼的大致步驟跟

    2024年01月23日
    瀏覽(17)
  • yolov8 OpenCV DNN 部署 推理報錯

    yolov8 OpenCV DNN 部署 推理報錯

    yolov8是yolov5作者發(fā)布的新作品 目錄 1、下載源碼 2、下載權(quán)重 3、配置環(huán)境 4、導出onnx格式 ?5、OpenCV DNN 推理 項目下models/export.md有說明: ?我在目錄下用命令行沒有反應(yīng),所以在項目目錄下新建一個python文件【my_export.py】,輸入: 然后執(zhí)行: 輸出如下: 用之前博客寫的代碼

    2024年02月06日
    瀏覽(33)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包