opencv3 dnn模块 调用darknet

这个示例展示了如何使用OpenCV的dnn模块结合Darknet的YOLO检测器,实现实时摄像头、视频或图像上的物体检测。模型和类名可以从指定链接下载,程序读取配置文件和权重文件加载网络,并对捕获的每一帧进行处理,将检测到的物体框出来并显示置信度。
摘要由CSDN通过智能技术生成

#include "stdafx.h"
// Brief Sample of using OpenCV dnn module in real time with device capture, video and image.
#include <opencv2/dnn.hpp>
#include <opencv2/dnn/shape_utils.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstdlib>

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

static const char* about =
"This sample uses You only look once (YOLO)-Detector (https://arxiv.org/abs/1612.08242) to detect objects on camera/video/image.\n"
"Models can be downloaded here: https://pjreddie.com/darknet/yolo/\n"
"Default network is 416x416.\n"
"Class names can be downloaded here: https://github.com/pjreddie/darknet/tree/master/data\n";

static const char* params =
"{ help           |false | print usage         }"
"{ cfg            |yolov3-voc.cfg | yolov3-voc.cfg}"   //模型配置文件
"{ model          |yolov3.weights |yolov3.weights}" //模型权重文件
"{ camera_device  | 0     | 0}" //摄像头
"{ source         | road.avi |road.avi}" //图片路径
"{ save           |       | path/}" //可设置保存文件路径
"{ fps            | 3     | 3 }"
"{ style          | box   | box  }"
"{ min_confidence | 0.24  | 0.24     }" //最小置信阀值
"{ class_names    | voc.names| voc.names }"; //分类文件

int main(int argc, char** argv)
{
    /*CommandLineParser parser(argc, argv, params);

    if (parser.get<bool>("help"))
    {
        cout << about << endl;
        parser.printMessage();
        return 0;
    }*/

    //String modelConfigur

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 以下是一个使用OpenCV DNN模块的C语言示例: ```c #include <opencv2/opencv.hpp> #include <opencv2/dnn.hpp> #include <iostream> using namespace cv; using namespace dnn; using namespace std; int main(int argc, char** argv) { // 加载模型和权重 String modelTxt = "path/to/model.txt"; String modelBin = "path/to/model.bin"; Net net = readNetFromCaffe(modelTxt, modelBin); // 加载图像 String imagePath = "path/to/image.jpg"; Mat image = imread(imagePath); // 预处理图像 Mat inputBlob = blobFromImage(image, 1.0, Size(300, 300), Scalar(104, 177, 123)); // 输入图像到网络中 net.setInput(inputBlob, "data"); // 运行前向传递 Mat detection = net.forward("detection_out"); // 解析输出 Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>()); for(int i = 0; i < detectionMat.rows; i++) { float confidence = detectionMat.at<float>(i, 2); if(confidence > 0.5) { int xLeftBottom = static_cast<int>(detectionMat.at<float>(i, 3) * image.cols); int yLeftBottom = static_cast<int>(detectionMat.at<float>(i, 4) * image.rows); int xRightTop = static_cast<int>(detectionMat.at<float>(i, 5) * image.cols); int yRightTop = static_cast<int>(detectionMat.at<float>(i, 6) * image.rows); // 绘制矩形框 rectangle(image, Point(xLeftBottom, yLeftBottom), Point(xRightTop, yRightTop), Scalar(0, 255, 0), 2); } } // 显示结果 imshow("detection result", image); waitKey(0); return 0; } ``` 此示例使用OpenCV DNN模块加载Caffe模型,对输入的图像进行检测,并将结果绘制在图像上。首先,我们需要加载模型和权重文件,然后加载要检测的图像。接下来,我们使用blobFromImage函数对图像进行预处理,然后将其输入到网络中进行前向传递。最后,我们解析输出结果并绘制检测结果的矩形框。 ### 回答2: OpenCV是一个开源的计算机视觉库,而OpenCV dnn模块则是其中的一个重要模块,用于深度神经网络的相关操作。下面我将给出一个使用OpenCV dnn模块进行目标检测的C语言示例。 ``` #include <opencv2/dnn.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <iostream> using namespace cv; using namespace cv::dnn; using namespace std; int main() { // 加载模型与相关参数 Net net = readNetFromDarknet("yolov3.cfg", "yolov3.weights"); vector<string> classNames; ifstream classNamesFile("coco.names"); string className; while (getline(classNamesFile, className)) { classNames.push_back(className); } // 加载图像 Mat image = imread("test.jpg"); if (image.empty()) { cerr << "无法读取图像文件!" << endl; return -1; } // 对图像进行目标检测 Mat blob = blobFromImage(image, 1 / 255.0, Size(416, 416), Scalar(0, 0, 0), true, false); net.setInput(blob); vector<Mat> outs; net.forward(outs); // 解析检测结果 float confidenceThreshold = 0.5; float nmsThreshold = 0.4; vector<int> classIds; vector<float> confidences; vector<Rect> boxes; for (size_t i = 0; i < outs.size(); ++i) { Mat detection = outs[i]; for (int j = 0; j < detection.rows; ++j) { Mat scores = detection.row(j).colRange(5, detection.cols); Point classIdPoint; double confidence; minMaxLoc(scores, 0, &confidence, 0, &classIdPoint); if (confidence > confidenceThreshold) { int centerX = (int)(detection.at<float>(j, 0) * image.cols); int centerY = (int)(detection.at<float>(j, 1) * image.rows); int width = (int)(detection.at<float>(j, 2) * image.cols); int height = (int)(detection.at<float>(j, 3) * image.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)); } } } // 对检测结果进行非最大值抑制 vector<int> indices; NMSBoxes(boxes, confidences, confidenceThreshold, nmsThreshold, indices); // 绘制检测框及类别标签 for (size_t i = 0; i < indices.size(); ++i) { int idx = indices[i]; Rect box = boxes[idx]; String label = classNames[classIds[idx]] + ": " + to_string(confidences[idx]); rectangle(image, box, Scalar(0, 0, 255), 2); putText(image, label, Point(box.x, box.y - 10), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 1); } // 显示结果 namedWindow("Object Detection", WINDOW_NORMAL); imshow("Object Detection", image); waitKey(0); return 0; } ``` 以上是一个使用OpenCV dnn模块进行目标检测的C语言例子。该例子首先加载了预训练的模型和相关参数,然后读取待检测的图像。接下来,通过设置输入并调用forward函数,使用模型对图像进行目标检测并得到检测结果。最后,根据检测结果,利用OpenCV提供的函数将检测框和类别标签绘制在图像上,并显示结果。 ### 回答3: 以下是一个使用OpenCV DNN模块的C语言示例: ```c #include <opencv2/opencv.hpp> #include <opencv2/dnn.hpp> #include <vector> using namespace cv; using namespace dnn; int main() { // 加载预训练的模型 String modelTxt = "path/to/model.txt"; String modelBin = "path/to/model.bin"; Net net = readNetFromDarknet(modelTxt, modelBin); // 加载输入图片 Mat image = imread("path/to/image.jpg"); // 图片预处理 Mat blob; blobFromImage(image, blob, 1.0, Size(416, 416), Scalar(), true, false); // 将blob输入到网络中 net.setInput(blob); // 进行目标检测 std::vector<Mat> outputs; std::vector<String> outputNames = net.getUnconnectedOutLayersNames(); net.forward(outputs, outputNames); // 处理输出结果 for (size_t i = 0; i < outputs.size(); ++i) { Mat output = outputs[i]; for (int j = 0; j < output.rows; ++j) { float* data = output.ptr<float>(j); for (int k = 0; k < output.cols; ++k) { // 处理输出数据,如绘制边界框等 // 示例:绘制边界框 if (data[k] > 0.5) { // 获取边界框的坐标 int x = data[k+1] * image.cols; int y = data[k+2] * image.rows; int width = data[k+3] * image.cols; int height = data[k+4] * image.rows; // 绘制边界框 rectangle(image, Point(x-width/2, y-height/2), Point(x+width/2, y+height/2), Scalar(0, 255, 0), 2); } } } } // 显示处理后的图片 imshow("Output", image); waitKey(0); return 0; } ``` 这个例子中,首先你需要使用`readNetFromDarknet`函数加载预训练的Darknet模型。然后,你使用`imread`函数加载待处理的图片。接下来,你需要对输入图片进行预处理,这里使用了`blobFromImage`函数。然后,你将预处理后的图片输入到网络中,使用`setInput`函数。之后,你可以通过调用`forward`函数进行目标检测,并将输出结果存储在一个`std::vector`中。最后,你可以根据输出结果对图片进行后处理,例如绘制边界框。最后,你使用`imshow`函数显示处理后的图片,在窗口中等待用户按下键盘。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值