OpenCV 4.12.0
开源计算机视觉
加载中...
搜索中...
无匹配项
加载 Caffe 框架模型

下一篇教程: 如何启用 Halide 后端以提高效率

原始作者Vitaliy Lyudvichenko
兼容性OpenCV >= 3.3

简介

在本教程中,您将学习如何使用 opencv_dnn 模块,通过 Caffe 模型库 中的 GoogLeNet 训练模型进行图像分类。

我们将通过以下图片演示本示例的结果。

源代码

我们将使用示例应用程序中的代码片段,您可以在此处下载该应用程序。

#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>
#include "common.hpp"
std::string keys =
"{ help h | | Print help message. }"
"{ @alias | | 用于从 models.yml 文件中提取预处理参数的模型别名。 }"
"{ zoo | models.yml | 包含预处理参数文件的可选路径 }"
"{ input i | | 输入图像或视频文件的路径。跳过此参数可从摄像头捕获帧。}"
"{ initial_width | 0 | 通过初始调整大小将输入图像预处理为特定宽度。}"
"{ initial_height | 0 | 通过初始调整大小将输入图像预处理为特定高度。}"
"{ std | 0.0 0.0 0.0 | 通过除以标准差对输入图像进行预处理。}"
"{ crop | false | 通过中心裁剪对输入图像进行预处理。}"
"{ framework f | | 模型原始框架的可选名称。如果未设置,则自动检测。 }"
"{ needSoftmax | false | 使用 Softmax 对网络输出进行后处理。}"
"{ classes | | 包含类别名称文本文件的可选路径。 }"
"{ backend | 0 | 选择一个计算后端: "
"0: 自动(默认), "
"1: Halide 语言 (http://halide-lang.org/), "
"2:Intel 深度学习推理引擎 (https://software.intel.com/openvino-toolkit), "
"3: OpenCV 实现, "
"4: VKCOM, "
"5:CUDA, "
"6:WebNN }"
"{ target | 0 | 选择一个目标计算设备: "
"0: CPU 目标(默认), "
"1: OpenCL, "
"2: OpenCL fp16(半精度浮点), "
"3: VPU, "
"4: Vulkan, "
"6: CUDA, "
"7: CUDA fp16(半精度浮点预处理)}";
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("Use this script to run classification deep learning networks using 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;
// 打开包含类名称的文件。
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 " + file + " not found");
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);
// 创建一个窗口
static const std::string kWinName = "Deep learning image classification in OpenCV";
namedWindow(kWinName, WINDOW_NORMAL);
if (parser.has("input"))
cap.open(parser.get<String>("input"));
else
cap.open(0);
// 处理帧。
Mat frame, blob;
while (waitKey(1) < 0)
{
cap >> frame;
if (frame.empty())
{
break;
}
if (rszWidth != 0 && rszHeight != 0)
{
resize(frame, frame, Size(rszWidth, rszHeight));
}
blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, crop);
// 检查 std 值。
if (std.val[0] != 0.0 && std.val[1] != 0.0 && std.val[2] != 0.0)
{
// 将 blob 除以 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;
// 显示效率信息。
// 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("1轮推理时间:%.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("Class #%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;
}
如果数组没有元素,则返回 true。
int64_t int64
n 维密集数组类
定义 mat.hpp:830
Mat reshape(int cn, int rows=0) const
更改二维矩阵的形状和/或通道数,而不复制数据。
MatIterator_< _Tp > end()
返回矩阵迭代器并将其设置为矩阵的最后一个元素之后。
MatIterator_< _Tp > begin()
返回矩阵迭代器并将其设置为矩阵的第一个元素。
_Tp x
点的 x 坐标
定义 types.hpp:201
用于指定图像或矩形大小的模板类。
Definition 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
用于从视频文件、图像序列或摄像头捕获视频的类。
Definition videoio.hpp:772
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
打开视频文件、捕获设备或 IP 视频流以进行视频捕获。
void exp(InputArray src, OutputArray dst)
计算每个数组元素的指数。
void divide(InputArray src1, InputArray src2, OutputArray dst, double scale=1, int dtype=-1)
对两个数组进行逐元素除法,或用数组除以标量。
Scalar sum(InputArray src)
计算数组元素的和。
void minMaxLoc(InputArray src, double *minVal, double *maxVal=0, Point *minLoc=0, Point *maxLoc=0, InputArray mask=noArray())
查找数组中的全局最小值和最大值。
std::string String
定义 cvstd.hpp:151
String format(const char *fmt,...)
使用类似 printf 的表达式格式化文本字符串。
#define CV_Error(code, msg)
调用错误处理程序。
定义 base.hpp:399
#define CV_Assert(expr)
在运行时检查条件,如果失败则抛出异常。
定义 base.hpp:423
Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size &size=Size(), const Scalar &mean=Scalar(), bool swapRB=false, bool crop=false, int ddepth=CV_32F)
从图像创建四维 blob。可选地调整图像大小并从中心裁剪,...
Net readNet(CV_WRAP_FILE_PATH const String &model, CV_WRAP_FILE_PATH const String &config="", const String &framework="")
读取支持格式之一表示的深度学习网络。
void imshow(const String &winname, InputArray mat)
在指定窗口中显示图像。
int waitKey(int delay=0)
等待按键按下。
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
创建窗口。
void putText(InputOutputArray img, const String &text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=LINE_8, bool bottomLeftOrigin=false)
绘制文本字符串。
void resize(InputArray src, OutputArray dst, Size dsize, double fx=0, double fy=0, int interpolation=INTER_LINEAR)
调整图像大小。
int main(int argc, char *argv[])
定义 highgui_qt.cpp:3
定义 core.hpp:107
STL 命名空间。

解释

  1. 首先,下载 GoogLeNet 模型文件:bvlc_googlenet.prototxtbvlc_googlenet.caffemodel

    您还需要包含 ILSVRC2012 类别名称的文件:classification_classes_ILSVRC2012.txt

    将这些文件放入此程序示例的工作目录中。

  2. 使用 .prototxt 和 .caffemodel 文件路径读取并初始化网络

    Net net = readNet(model, config, framework);
    net.setPreferableBackend(backendId);
    net.setPreferableTarget(targetId);

    如果文件 modelconfig 之一的扩展名为 .caffemodel.prototxt,您可以跳过参数 framework。这样,函数 cv::dnn::readNet 可以自动检测模型的格式。

  3. 读取输入图像并转换为 GoogLeNet 可接受的 blob

    if (parser.has("input"))
    cap.open(parser.get<String>("input"));
    else
    cap.open(0);

    cv::VideoCapture 可以加载图像和视频。

    blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, crop);
    // 检查 std 值。
    if (std.val[0] != 0.0 && std.val[1] != 0.0 && std.val[2] != 0.0)
    {
    // 将 blob 除以 std。
    divide(blob, std, blob);
    }

    我们使用 cv::dnn::blobFromImage 函数,在应用必要的预处理(如调整大小和均值减法 (-104, -117, -123),分别针对蓝色、绿色和红色通道)后,将图像转换为形状为 1x3x224x224 的四维 blob(即批次)。

  4. 将 blob 传递给网络
    net.setInput(blob);
  5. 执行前向传播
    // 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++) {
    在前向传播过程中,会计算每个网络层的输出,但在此示例中,我们只需要最后一层的输出。
  6. 确定最佳类别
    Point classIdPoint;
    minMaxLoc(prob.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
    classId = classIdPoint.x;
    我们将网络输出(其中包含 1000 个 ILSVRC2012 图像类别中每个类别的概率)放入 prob blob 中。然后找到其中具有最大值的元素的索引。此索引对应于图像的类别。
  7. 从命令行运行示例
    ./example_dnn_classification --model=bvlc_googlenet.caffemodel --config=bvlc_googlenet.prototxt --width=224 --height=224 --classes=classification_classes_ILSVRC2012.txt --input=space_shuttle.jpg --mean="104 117 123"
    对于我们的图像,我们得到类别 space shuttle 的预测,置信度超过 99%。