C++调用yolov3模型-opencv3.4.2

介绍

基本思想:通过darknet在线下进行训练,生成yolov3.weights文件,然后opencv通过线上进行调用,模型可以落地了~~~

源代码

#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include<vector>


using namespace std;
using namespace cv;
using namespace dnn;

vector<string> classes;

vector<String> getOutputsNames(Net&net)
{
    static vector<String> names;
    if (names.empty())
    {
        //Get the indices of the output layers, i.e. the layers with unconnected outputs
        vector<int> outLayers = net.getUnconnectedOutLayers();

        //get the names of all the layers in the network
        vector<String> layersNames = net.getLayerNames();

        // Get the names of the output layers in names
        names.resize(outLayers.size());
        for (size_t i = 0; i < outLayers.size(); ++i)
            names[i] = layersNames[outLayers[i] - 1];
    }
    return names;
}
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
    //Draw a rectangle displaying the bounding box
    rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 178, 50), 3);

    //Get the label for the class name and its confidence
    string label = format("%.5f", conf);
    if (!classes.empty())
    {
        CV_Assert(classId < (int)classes.size());
        label = classes[classId] + ":" + label;
    }

    //Display the label at the top of the bounding box
    int baseLine;
    Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
    top = max(top, labelSize.height);
    rectangle(frame, Point(left, top - round(1.5*labelSize.height)), Point(left + round(1.5*labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED);
    putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 0), 1);
}
void postprocess(Mat& frame, const vector<Mat>& outs, float confThreshold, float nmsThreshold)
{
    vector<int> classIds;
    vector<float> confidences;
    vector<Rect> boxes;

    for (size_t i = 0; i < outs.size(); ++i)
    {
        // Scan through all the bounding boxes output from the network and keep only the
        // ones with high confidence scores. Assign the box's class label as the class
        // with the highest score for the box.
        float* data = (float*)outs[i].data;
        for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
        {
            Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
            Point classIdPoint;
            double confidence;
            // Get the value and location of the maximum score
            minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
            if (confidence > confThreshold)
            {
                int centerX = (int)(data[0] * frame.cols);
                int centerY = (int)(data[1] * frame.rows);
                int width = (int)(data[2] * frame.cols);
                int height = (int)(data[3] * frame.rows);
                int left = centerX - width / 2;
                int top = centerY - height / 2;

                classIds.push_back(classIdPoint.x);
                confidences.push_back((float)confidence);
                boxes.push_back(Rect(left, top, width, height));
            }
        }
    }

    // Perform non maximum suppression to eliminate redundant overlapping boxes with
    // lower confidences
    vector<int> indices;
    NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
    for (size_t i = 0; i < indices.size(); ++i)
    {
        int idx = indices[i];
        Rect box = boxes[idx];
        drawPred(classIds[idx], confidences[idx], box.x, box.y,
            box.x + box.width, box.y + box.height, frame);
    }
}

int main()
{
    string names_file = "/home/oliver/darknet-master/data/coco.names";
    String model_def = "/home/oliver/darknet-master/cfg/yolov3.cfg";
    String weights = "/home/oliver/darknet-master/yolov3.weights";

    int in_w, in_h;
    double thresh = 0.5;
    double nms_thresh = 0.25;
    in_w = in_h = 608;

    string img_path = "/home/oliver/darknet/data/dog.jpg";

    //read names

    ifstream ifs(names_file.c_str());
    string line;
    while (getline(ifs, line)) classes.push_back(line);

    //init model
    Net net = readNetFromDarknet(model_def, weights);
    net.setPreferableBackend(DNN_BACKEND_OPENCV);
    net.setPreferableTarget(DNN_TARGET_CPU);

    //read image and forward
    VideoCapture capture(2);// VideoCapture:OENCV中新增的类,捕获视频并显示出来
    while (1)
    {
    Mat frame, blob;
    capture >> frame;


    blobFromImage(frame, blob, 1 / 255.0, Size(in_w, in_h), Scalar(), true, false);

    vector<Mat> mat_blob;
    imagesFromBlob(blob, mat_blob);

    //Sets the input to the network
    net.setInput(blob);

    // Runs the forward pass to get output of the output layers
    vector<Mat> outs;
    net.forward(outs, getOutputsNames(net));

    postprocess(frame, outs, thresh, nms_thresh);

    vector<double> layersTimes;
    double freq = getTickFrequency() / 1000;
    double t = net.getPerfProfile(layersTimes) / freq;
    string label = format("Inference time for a frame : %.2f ms", t);
    putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255));

    imshow("res", frame);

    waitKey(10);
    }
    return 0;
}

要在C++调用Yolov5模型,可以使用以下步骤: 1. 安装OpenCV和Libtorch库。OpenCV用于图像处理,Libtorch用于深度学习模型的加载和预测。 2. 下载并加载Yolov5模型。可以使用PyTorch将预训练的Yolov5模型转换为Libtorch格式,然后在C++中加载它们。加载模型时,需要指定输入图像的大小和通道数,并设置模型的推理模式为eval。 3. 准备输入图像。将输入图像读入内存并转换为Libtorch张量。 4. 运行模型。将输入张量传递给模型,并使用forward函数进行推理。模型将返回一个输出张量,其中包含检测到的物体的位置和类别。 5. 解析输出结果。从输出张量中提取检测结果,并将它们绘制到图像上,或者将它们输出到控制台。 这里是一个简单的示例代码,演示如何加载Yolov5模型并运行它: ```c++ #include <torch/script.h> #include <opencv2/opencv.hpp> int main() { // Load model torch::jit::script::Module module = torch::jit::load("yolov5s.pt"); // Input image size const int input_size = 640; // Input channels const int input_channels = 3; // Set model to evaluation mode module.eval(); // Prepare input image cv::Mat image = cv::imread("test.jpg"); cv::resize(image, image, cv::Size(input_size, input_size)); cv::cvtColor(image, image, cv::COLOR_BGR2RGB); torch::Tensor input_tensor = torch::from_blob(image.data, {1, input_size, input_size, input_channels}, torch::kByte); input_tensor = input_tensor.permute({0, 3, 1, 2}).to(torch::kFloat).div(255); // Run model std::vector<torch::jit::IValue> inputs; inputs.push_back(input_tensor); torch::Tensor output_tensor = module.forward(inputs).toTensor(); // Parse output results const int num_classes = 80; const float conf_threshold = 0.5; const float nms_threshold = 0.5; std::vector<cv::Rect> boxes; std::vector<int> classes; std::vector<float> scores; auto output = output_tensor.squeeze().detach().cpu(); auto idxs = output.slice(1, 4, 5).argmax(1); auto confs = output.slice(1, 4, 5).index_select(1, idxs).squeeze(); auto mask = confs.gt(conf_threshold); auto boxes_tensor = output.slice(1, 0, 4).masked_select(mask.unsqueeze(1).expand_as(output.slice(1, 0, 4))).view({-1, 4}); auto scores_tensor = confs.masked_select(mask).view({-1}); auto classes_tensor = output.slice(1, 5).masked_select(mask).view({-1}); torch::Tensor keep = torch::empty({scores_tensor.size(0)}, torch::kBool); torch::argsort(scores_tensor, 0, true, keep); auto keep_vec = keep.cpu().numpy(); for (int i = 0; i < keep_vec.shape[0]; i++) { int index = keep_vec[i]; int cls = classes_tensor[index].item<int>(); float score = scores_tensor[index].item<float>(); cv::Rect box; box.x = boxes_tensor[index][0].item<int>(); box.y = boxes_tensor[index][1].item<int>(); box.width = boxes_tensor[index][2].item<int>() - box.x; box.height = boxes_tensor[index][3].item<int>() - box.y; boxes.push_back(box); classes.push_back(cls); scores.push_back(score); } // Non-maximum suppression std::vector<int> indices; cv::dnn::NMSBoxes(boxes, scores, conf_threshold, nms_threshold, indices); // Draw detection results for (int i = 0; i < indices.size(); i++) { int idx = indices[i]; cv::rectangle(image, boxes[idx], cv::Scalar(0, 255, 0), 2); cv::putText(image, cv::format("%s %.2f", "class", scores[idx]), cv::Point(boxes[idx].x, boxes[idx].y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 2); } // Display detection results cv::imshow("Detection", image); cv::waitKey(); return 0; } ``` 其中,test.jpg是输入图像的文件名,yolov5s.pt是预训练的Yolov5模型文件名。在该代码中,我们使用OpenCV对输入图像进行处理,并使用Libtorch加载和运行模型,最终将检测结果绘制到图像上。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值