#include <fstream>
#include <sstream>
#if defined(HAVE_THREADS)
#define USE_THREADS 1
#endif
#ifdef USE_THREADS
#include <mutex>
#include <thread>
#include <queue>
#endif
#include "common.hpp"
std::string keys =
"{ help h | | Print help message. }"
"{ @alias | | 用於從 models.yml 檔案中提取預處理引數的模型別名。}"
"{ zoo | models.yml | 包含預處理引數的檔案的可選路徑 }"
"{ device | 0 | 攝像頭裝置號。}"
"{ input i | | 輸入影像或影片檔案的路徑。跳過此引數以從攝像頭捕獲幀。}"
"{ framework f | | 模型的原始框架的可選名稱。如果未設定,則自動檢測。}"
"{ classes | | 包含用於標記檢測到的物件的類名稱的文字檔案的可選路徑。}"
"{ thr | .5 | 置信度閾值。}"
"{ nms | .4 | 非極大值抑制閾值。}"
"{ backend | 0 | 選擇一個計算後端: "
"0: 自動(預設), "
"1: Halide 語言 (http://halide-lang.org/), "
"2: 英特爾深度學習推理引擎 (https://software.intel.com/openvino-toolkit), "
"3: OpenCV 實現, "
"4: VKCOM, "
"5: CUDA }"
"{ target | 0 | 選擇一個目標計算裝置: "
"0: CPU 目標(預設), "
"1: OpenCL, "
"2: OpenCL fp16(半精度浮點), "
"3: VPU, "
"4: Vulkan, "
"6: CUDA, "
"7: CUDA fp16(半精度浮點預處理)}"
"{ async | 0 | 同時非同步前向的數量。 "
"選擇 0 為同步模式 }";
using namespace dnn;
float confThreshold, nmsThreshold;
std::vector<std::string> classes;
inline void preprocess(
const Mat& frame, Net& net,
Size inpSize,
float scale,
const Scalar& mean,
bool swapRB);
void postprocess(
Mat& frame,
const std::vector<Mat>& out, Net& net,
int backend);
void drawPred(
int classId,
float conf,
int left,
int top,
int right,
int bottom,
Mat& frame);
void callback(int pos, void* userdata);
#ifdef USE_THREADS
template <typename T>
class QueueFPS : public std::queue<T>
{
public:
QueueFPS() : counter(0) {}
void push(const T& entry)
{
std::lock_guard<std::mutex> lock(mutex);
std::queue<T>::push(entry);
counter += 1;
if (counter == 1)
{
tm.reset();
tm.start();
}
}
T get()
{
std::lock_guard<std::mutex> lock(mutex);
T entry = this->front();
this->pop();
return entry;
}
float getFPS()
{
tm.stop();
double fps = counter / tm.getTimeSec();
tm.start();
return static_cast<float>(fps);
}
void clear()
{
std::lock_guard<std::mutex> lock(mutex);
while (!this->empty())
this->pop();
}
unsigned int counter;
private:
std::mutex mutex;
};
#endif
int main(
int argc,
char** argv)
{
const std::string modelName = parser.get<
String>(
"@alias");
const std::string zooFile = parser.get<
String>(
"zoo");
keys += genPreprocArguments(modelName, zooFile);
parser.about("使用此指令碼透過 OpenCV 執行物件檢測深度學習網路。");
if (argc == 1 || parser.has("help"))
{
parser.printMessage();
return 0;
}
confThreshold = parser.get<float>("thr");
nmsThreshold = parser.get<float>("nms");
float scale = parser.get<
float>(
"scale");
bool swapRB = parser.get<bool>("rgb");
int inpWidth = parser.get<int>("width");
int inpHeight = parser.get<int>("height");
size_t asyncNumReq = parser.get<int>("async");
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");
while (std::getline(ifs, line))
{
classes.push_back(line);
}
}
Net net =
readNet(modelPath, configPath, parser.get<
String>(
"framework"));
int backend = parser.get<
int>(
"backend");
net.setPreferableBackend(backend);
net.setPreferableTarget(parser.get<int>("target"));
std::vector<String> outNames = net.getUnconnectedOutLayersNames();
static const std::string kWinName = "OpenCV 中的深度學習物件檢測";
int initialConf = (int)(confThreshold * 100);
if (parser.has("input"))
else
cap.
open(parser.get<
int>(
"device"));
#ifdef USE_THREADS
bool process = true;
QueueFPS<Mat> framesQueue;
std::thread framesThread([&](){
while (process)
{
cap >> frame;
if (!frame.empty())
framesQueue.push(frame.clone());
else
break;
}
});
QueueFPS<Mat> processedFramesQueue;
QueueFPS<std::vector<Mat> > predictionsQueue;
std::thread processingThread([&](){
std::queue<AsyncArray> futureOutputs;
while (process)
{
{
if (!framesQueue.empty())
{
frame = framesQueue.get();
if (asyncNumReq)
{
if (futureOutputs.size() == asyncNumReq)
}
else
framesQueue.clear();
}
}
{
preprocess(frame, net,
Size(inpWidth, inpHeight), scale, mean, swapRB);
processedFramesQueue.push(frame);
if (asyncNumReq)
{
futureOutputs.push(net.forwardAsync());
}
else
{
std::vector<Mat> outs;
net.forward(outs, outNames);
predictionsQueue.push(outs);
}
}
while (!futureOutputs.empty() &&
futureOutputs.front().wait_for(std::chrono::seconds(0)))
{
futureOutputs.pop();
predictionsQueue.push({out});
}
}
});
{
if (predictionsQueue.empty())
continue;
std::vector<Mat> outs = predictionsQueue.get();
Mat frame = processedFramesQueue.get();
if (predictionsQueue.counter > 1)
{
std::string label =
format(
"攝像頭: %.2f FPS", framesQueue.getFPS());
label =
format(
"網路: %.2f FPS", predictionsQueue.getFPS());
label =
format(
"跳過的幀數: %d", framesQueue.counter - predictionsQueue.counter);
}
}
process = false;
framesThread.join();
processingThread.join();
#else
if (asyncNumReq)
CV_Error(Error::StsNotImplemented,
"僅推理引擎後端支援非同步前向。");
{
cap >> frame;
if (frame.empty())
{
break;
}
preprocess(frame, net,
Size(inpWidth, inpHeight), scale, mean, swapRB);
std::vector<Mat> outs;
net.forward(outs, outNames);
std::vector<double> layersTimes;
double t = net.getPerfProfile(layersTimes) / freq;
std::string label =
format(
"推理時間: %.2f ms", t);
}
#endif
return 0;
}
inline void preprocess(
const Mat& frame, Net& net,
Size inpSize,
float scale,
const Scalar& mean,
bool swapRB)
{
net.setInput(blob, "", scale, mean);
if (net.getLayer(0)->outputNameToIndex("im_info") != -1)
{
resize(frame, frame, inpSize);
net.setInput(imInfo, "im_info");
}
}
void postprocess(
Mat& frame,
const std::vector<Mat>& outs, Net& net,
int backend)
{
static std::vector<int> outLayers = net.getUnconnectedOutLayers();
static std::string outLayerType = net.getLayer(outLayers[0])->type;
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<Rect> boxes;
if (outLayerType == "DetectionOutput")
{
for (size_t k = 0; k < outs.size(); k++)
{
float* data = (float*)outs[k].data;
for (size_t i = 0; i < outs[k].total(); i += 7)
{
float confidence = data[i + 2];
if (confidence > confThreshold)
{
int left = (int)data[i + 3];
int top = (int)data[i + 4];
int right = (int)data[i + 5];
int bottom = (int)data[i + 6];
int width = right - left + 1;
int height = bottom - top + 1;
if (width <= 2 || height <= 2)
{
left = (int)(data[i + 3] * frame.
cols);
top = (int)(data[i + 4] * frame.
rows);
right = (int)(data[i + 5] * frame.
cols);
bottom = (int)(data[i + 6] * frame.
rows);
width = right - left + 1;
height = bottom - top + 1;
}
classIds.push_back((int)(data[i + 1]) - 1);
boxes.push_back(
Rect(left, top, width, height));
confidences.push_back(confidence);
}
}
}
}
else if (outLayerType == "Region")
{
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);
double confidence;
minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
if (confidence > confThreshold)
{
int centerX = (int)(data[0] * frame.
cols);
int centerY = (int)(data[1] * frame.
rows);
int width = (int)(data[2] * frame.
cols);
int height = (int)(data[3] * frame.
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));
}
}
}
}
else
CV_Error(Error::StsNotImplemented,
"未知輸出層型別: " + outLayerType);
if (outLayers.size() > 1 || (outLayerType == "Region" && backend != DNN_BACKEND_OPENCV))
{
std::map<int, std::vector<size_t> > class2indices;
for (size_t i = 0; i < classIds.size(); i++)
{
if (confidences[i] >= confThreshold)
{
class2indices[classIds[i]].push_back(i);
}
}
std::vector<Rect> nmsBoxes;
std::vector<float> nmsConfidences;
std::vector<int> nmsClassIds;
for (std::map<int, std::vector<size_t> >::iterator it = class2indices.begin(); it != class2indices.end(); ++it)
{
std::vector<Rect> localBoxes;
std::vector<float> localConfidences;
std::vector<size_t> classIndices = it->second;
for (size_t i = 0; i < classIndices.size(); i++)
{
localBoxes.push_back(boxes[classIndices[i]]);
localConfidences.push_back(confidences[classIndices[i]]);
}
std::vector<int> nmsIndices;
NMSBoxes(localBoxes, localConfidences, confThreshold, nmsThreshold, nmsIndices);
for (size_t i = 0; i < nmsIndices.size(); i++)
{
size_t idx = nmsIndices[i];
nmsBoxes.push_back(localBoxes[idx]);
nmsConfidences.push_back(localConfidences[idx]);
nmsClassIds.push_back(it->first);
}
}
boxes = nmsBoxes;
classIds = nmsClassIds;
confidences = nmsConfidences;
}
for (size_t idx = 0; idx < boxes.size(); ++idx)
{
drawPred(classIds[idx], confidences[idx], box.
x, box.
y,
}
}
void drawPred(
int classId,
float conf,
int left,
int top,
int right,
int bottom,
Mat& frame)
{
std::string label =
format(
"%.2f", conf);
if (!classes.empty())
{
label = classes[classId] + ": " + label;
}
int baseLine;
Size labelSize =
getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
top = max(top, labelSize.
height);
Point(left + labelSize.
width, top + baseLine), Scalar::all(255), FILLED);
}
void callback(int pos, void*)
{
confThreshold = pos * 0.01f;
}
返回非同步操作的結果。
定義 async.hpp:30
void get(OutputArray dst) const
如果陣列沒有元素,則返回 true。
int64_t int64
從 Mat 派生的模板矩陣類。
定義 mat.hpp:2257
cv::getTickFrequency
double getTickFrequency()
int rows
行列數,或矩陣維度超過 2 時為 (-1, -1)
定義 mat.hpp:2165
_Tp x
點的 x 座標
定義 types.hpp:201
2D 矩形的模板類。
定義 types.hpp:444
_Tp x
左上角的 x 座標
定義 types.hpp:487
_Tp y
左上角的 y 座標
定義 types.hpp:488
_Tp width
矩形的寬度
定義 types.hpp:489
_Tp height
矩形的高度
定義 types.hpp:490
用於指定影像或矩形大小的模板類。
Definition types.hpp:335
_Tp height
高度
Definition types.hpp:363
_Tp width
寬度
Definition types.hpp:362
一個用於測量流逝時間的類。
定義 utility.hpp:326
用於從影片檔案、影像序列或攝像頭捕獲影片的類。
Definition videoio.hpp:772
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
開啟影片檔案、捕獲裝置或 IP 影片流進行影片捕獲。
Scalar mean(InputArray src, InputArray mask=noArray())
計算陣列元素的平均值(均值)。
void minMaxLoc(InputArray src, double *minVal, double *maxVal=0, Point *minLoc=0, Point *maxLoc=0, InputArray mask=noArray())
查詢陣列中的全域性最小值和最大值。
std::string String
定義 cvstd.hpp:151
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
嘗試查詢請求的資料檔案。
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)
從影像建立 4 維 blob。可選地調整大小並從中心裁剪影像,...
Net readNet(CV_WRAP_FILE_PATH const String &model, CV_WRAP_FILE_PATH const String &config="", const String &framework="")
讀取以支援格式之一表示的深度學習網路。
void NMSBoxes(const std::vector< Rect > &bboxes, const std::vector< float > &scores, const float score_threshold, const float nms_threshold, std::vector< int > &indices, const float eta=1.f, const int top_k=0)
根據框和相應的分數執行非極大值抑制。
cv::gapi::GBackend backend()
獲取對 CPU (OpenCV) 後端的引用。
void imshow(const String &winname, InputArray mat)
在指定視窗中顯示影像。
int waitKey(int delay=0)
等待按鍵按下。
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
建立視窗。
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
建立滑動條並將其附加到指定視窗。
void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
繪製一個簡單、粗或填充的矩形。
Size getTextSize(const String &text, int fontFace, double fontScale, int thickness, int *baseLine)
計算文字字串的寬度和高度。
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 line(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
繪製連線兩點的線段。
int main(int argc, char *argv[])
定義 highgui_qt.cpp:3
void postprocess(Outputs &... outs)
定義 gcpukernel.hpp:231
void scale(cv::Mat &mat, const cv::Mat &range, const T min, const T max)
Definition quality_utils.hpp:90