OpenCV 4.12.0
開源計算機視覺
載入中...
搜尋中...
無匹配項
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 | | 從 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: 英特爾深度學習推理引擎 (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("使用此指令碼透過 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 = "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())
{
cv::Mat::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 毫秒", t1);
std::string label2 = format("200 輪平均時間:%.2f 毫秒", 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;
}
如果陣列沒有元素,則返回 true。
int64_t int64
T get(const String &name, bool space_delete=true) const
按名稱訪問引數。
定義 utility.hpp:956
void about(const String &message)
設定 about 訊息。
void printErrors() const
打印發生的錯誤列表。
void printMessage() const
列印幫助資訊。
bool has(const String &name) const
檢查命令列中是否提供了欄位。
bool check() const
檢查解析錯誤。
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)
計算每個陣列元素的指數。
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 名稱空間。