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%。