OpenCV 4.13.0
开源计算机视觉库 (Open Source Computer Vision)
正在加载...
正在搜索...
未找到匹配项
samples/dnn/classification.cpp

查看相应的教程以获取更多详细信息

#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>
#include "common.hpp"
std::string keys =
"{ help h | | Print help message. }"
"{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }"
"{ zoo | models.yml | An optional path to file with preprocessing parameters }"
"{ input i | | 输入图像或视频文件的路径。跳过此参数可从相机捕获帧。}"
"{ initial_width | 0 | 通过将初始图像缩放到特定宽度来预处理输入图像。}"
"{ initial_height | 0 | 通过将初始图像缩放到特定高度来预处理输入图像。}"
"{ std | 0.0 0.0 0.0 | 通过除以标准差来预处理输入图像。}"
"{ crop | false | 通过中心裁剪预处理输入图像。}"
"{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
"{ needSoftmax | false | 使用 Softmax 后处理网络的输出。}"
"{ classes | | 包含类名称的文本文件可选路径。 }"
"{ backend | 0 | Choose one of computation backends: "
"0: automatically (by default), "
"1: Halide language (http://halide-lang.org/), "
"2: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"3: OpenCV implementation, "
"4: VKCOM, "
"5: CUDA, "
"6: WebNN }"
"{ target | 0 | Choose one of target computation devices: "
"0: CPU target (by default), "
"1: OpenCL, "
"2: OpenCL fp16 (half-float precision), "
"3: VPU, "
"4: Vulkan, "
"6: CUDA, "
"7: CUDA fp16 (half-float preprocess) }";
using namespace cv;
using namespace dnn;
std::vector<std::string> classes;
int main(int argc, char** argv)
{
CommandLineParser parser(argc, argv, keys);
const std::string modelName = parser.get<String>("@alias");
const std::string zooFile = parser.get<String>("zoo");
keys += genPreprocArguments(modelName, zooFile);
parser = CommandLineParser(argc, argv, keys);
parser.about("使用此脚本使用OpenCV运行分类深度学习网络。");
if (argc == 1 || parser.has("help"))
{
parser.printMessage();
return 0;
}
int rszWidth = parser.get<int>("initial_width");
int rszHeight = parser.get<int>("initial_height");
float scale = parser.get<float>("scale");
Scalar mean = parser.get<Scalar>("mean");
Scalar std = parser.get<Scalar>("std");
bool swapRB = parser.get<bool>("rgb");
bool crop = parser.get<bool>("crop");
int inpWidth = parser.get<int>("width");
int inpHeight = parser.get<int>("height");
String model = findFile(parser.get<String>("model"));
String config = findFile(parser.get<String>("config"));
String framework = parser.get<String>("framework");
int backendId = parser.get<int>("backend");
int targetId = parser.get<int>("target");
bool needSoftmax = parser.get<bool>("needSoftmax");
std::cout<<"mean: "<<mean<<std::endl;
std::cout<<"std: "<<std<<std::endl;
// Open file with classes names.
if (parser.has("classes"))
{
std::string file = parser.get<String>("classes");
std::ifstream ifs(file.c_str());
if (!ifs.is_open())
CV_Error(Error::StsError, "文件 " + file + " 未找到");
std::string line;
while (std::getline(ifs, line))
{
classes.push_back(line);
}
}
if (!parser.check())
{
parser.printErrors();
return 1;
}
CV_Assert(!model.empty());
Net net = readNet(model, config, framework);
net.setPreferableBackend(backendId);
net.setPreferableTarget(targetId);
// Create a window
static const std::string kWinName = "OpenCV中的深度学习图像分类";
namedWindow(kWinName, WINDOW_NORMAL);
if (parser.has("input"))
cap.open(parser.get<String>("input"));
else
cap.open(0);
// Process frames.
Mat frame, blob;
while (waitKey(1) < 0)
{
cap >> frame;
if (frame.empty())
{
waitKey();
break;
}
if (rszWidth != 0 && rszHeight != 0)
{
resize(frame, frame, Size(rszWidth, rszHeight));
}
blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, crop);
// Check std values.
if (std.val[0] != 0.0 && std.val[1] != 0.0 && std.val[2] != 0.0)
{
// Divide blob by std.
divide(blob, std, blob);
}
net.setInput(blob);
// double t_sum = 0.0;
// double t;
int classId;
double confidence;
cv::TickMeter timeRecorder;
timeRecorder.reset();
Mat prob = net.forward();
double t1;
timeRecorder.start();
prob = net.forward();
timeRecorder.stop();
t1 = timeRecorder.getTimeMilli();
timeRecorder.reset();
for(int i = 0; i < 200; i++) {
timeRecorder.start();
prob = net.forward();
timeRecorder.stop();
Point classIdPoint;
minMaxLoc(prob.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
classId = classIdPoint.x;
// Put efficiency information.
// std::vector<double> layersTimes;
// double freq = getTickFrequency() / 1000;
// t = net.getPerfProfile(layersTimes) / freq;
// t_sum += t;
}
if (needSoftmax == true)
{
float maxProb = 0.0;
float sum = 0.0;
Mat softmaxProb;
maxProb = *std::max_element(prob.begin<float>(), prob.end<float>());
cv::exp(prob-maxProb, softmaxProb);
sum = (float)cv::sum(softmaxProb)[0];
softmaxProb /= sum;
Point classIdPoint;
minMaxLoc(softmaxProb.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
classId = classIdPoint.x;
}
std::string label = format("单轮推理时间: %.2f ms", t1);
std::string label2 = format("200轮平均时间: %.2f ms", timeRecorder.getTimeMilli()/200);
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
putText(frame, label2, Point(0, 35), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
// 打印预测类别。
label = format("%s: %.4f", (classes.empty() ? format("类别 #%d", classId).c_str()
classes[classId].c_str()),
confidence);
putText(frame, label, Point(0, 55), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
imshow(kWinName, frame);
}
return 0;
}
专为命令行解析设计。
定义 utility.hpp:890
T get(const String &name, bool space_delete=true) const
按名称访问参数。
Definition utility.hpp:956
void about(const String &message)
设置关于信息。
void printErrors() const
打印发生的错误列表。
void printMessage() const
打印帮助信息。
bool has(const String &name) const
检查字段是否在命令行中提供。
bool check() const
检查解析错误。
n 维密集数组类
定义于 mat.hpp:840
Mat reshape(int cn, int rows=0) const
在不复制数据的情况下更改 2D 矩阵的形状和/或通道数。
MatIterator_< _Tp > end()
返回矩阵迭代器并将其设置为最后一个矩阵元素之后的位置。
MatIterator_< _Tp > begin()
返回矩阵迭代器并将其设置为第一个矩阵元素。
_Tp x
点的 x 坐标
定义 types.hpp:201
用于指定图像或矩形大小的模板类。
定义 types.hpp:335
一个用于测量经过时间的类。
定义在 utility.hpp:326
void start()
开始计算周期数。
定义在 utility.hpp:335
void stop()
停止计算周期数。
定义在 utility.hpp:341
void reset()
重置内部值。
定义 utility.hpp:430
double getTimeMilli() const
返回以毫秒为单位经过的时间。
定义 utility.hpp:365
从视频文件、图像序列或摄像头捕获视频的类。
定义 videoio.hpp:786
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
打开视频文件、捕获设备或 IP 视频流进行视频捕获。
void exp(InputArray src, OutputArray dst)
计算每个数组元素的指数。
Scalar sum(InputArray src)
计算数组元素的总和。
std::string String
定义 cvstd.hpp:151
#define CV_Error(code, msg)
调用错误处理器。
定义 base.hpp:399
#define CV_Assert(expr)
在运行时检查条件,如果失败则抛出异常。
定义于 base.hpp:423
int main(int argc, char *argv[])
定义 highgui_qt.cpp:3
定义 core.hpp:107
STL 命名空间。