用代码写C++用yolo推理多张图片随机返回一个框xy 坐标
时间: 2024-05-16 14:17:45 浏览: 109
以下是用C++代码使用YOLO进行推理,并随机返回一个框的xy坐标。
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/dnn/dnn.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
using namespace cv::dnn;
int main()
{
// 加载标签文件和模型文件
vector<string> classes;
ifstream ifs("coco.names");
string line;
while (getline(ifs, line)) classes.push_back(line);
Net net = readNetFromDarknet("yolov3.cfg", "yolov3.weights");
net.setPreferableBackend(DNN_BACKEND_OPENCV);
net.setPreferableTarget(DNN_TARGET_CPU);
// 加载图片
Mat image = imread("test.jpg");
// 构建blob
Mat blob;
blobFromImage(image, blob, 1 / 255.0, Size(416, 416), Scalar(), true, false);
// 运行前向推理
net.setInput(blob);
vector<Mat> outs;
net.forward(outs, net.getUnconnectedOutLayersNames());
// 解析输出
vector<int> classIds;
vector<float> confidences;
vector<Rect> boxes;
for (size_t i = 0; i < outs.size(); ++i)
{
// 获取当前输出层的所有检测结果
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;
minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
if (confidence > 0.5)
{
// 获取检测结果的坐标和宽高
int centerX = (int)(data[0] * image.cols);
int centerY = (int)(data[1] * image.rows);
int width = (int)(data[2] * image.cols);
int height = (int)(data[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));
}
}
}
// 随机返回一个框的xy坐标
if (boxes.size() > 0)
{
srand((unsigned)time(NULL));
int index = rand() % boxes.size();
Rect box = boxes[index];
cout << "x: " << box.x << ", y: " << box.y << endl;
}
else
{
cout << "no detection result" << endl;
}
return 0;
}
```
在上面的代码中,需要将YOLO模型文件和标签文件放在与代码文件相同的目录下,并将图片文件名改为对应的文件名。运行代码后,将随机返回一张图片中检测到的一个物体框的x和y坐标。
阅读全文