OpenCV 4.12.0
開源計算機視覺
載入中...
搜尋中...
無匹配項
samples/dnn/object_detection.cpp

有關更多詳細資訊,請檢視相應的教程

#include <fstream>
#include <sstream>
#include <opencv2/dnn.hpp>
#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 cv;
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 // USE_THREADS
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;
}
confThreshold = parser.get<float>("thr");
nmsThreshold = parser.get<float>("nms");
float scale = parser.get<float>("scale");
Scalar mean = parser.get<Scalar>("mean");
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");
CV_Assert(parser.has("model"));
std::string modelPath = findFile(parser.get<String>("model"));
std::string configPath = findFile(parser.get<String>("config"));
// 開啟包含類名稱的檔案。
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);
}
}
// 載入模型。
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 中的深度學習物件檢測";
namedWindow(kWinName, WINDOW_NORMAL);
int initialConf = (int)(confThreshold * 100);
createTrackbar("置信度閾值, %", kWinName, &initialConf, 99, callback);
// 開啟影片檔案或影像檔案或攝像頭流。
if (parser.has("input"))
cap.open(parser.get<String>("input"));
else
cap.open(parser.get<int>("device"));
#ifdef USE_THREADS
bool process = true;
// 幀捕獲執行緒
QueueFPS<Mat> framesQueue;
std::thread framesThread([&](){
Mat frame;
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;
Mat blob;
while (process)
{
// 獲取下一幀
Mat frame;
{
if (!framesQueue.empty())
{
frame = framesQueue.get();
if (asyncNumReq)
{
if (futureOutputs.size() == asyncNumReq)
frame = Mat();
}
else
framesQueue.clear(); // 跳過剩餘幀
}
}
// 處理幀
if (!frame.empty())
{
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)))
{
AsyncArray async_out = futureOutputs.front();
futureOutputs.pop();
Mat out;
async_out.get(out);
predictionsQueue.push({out});
}
}
});
// 後處理和渲染迴圈
while (waitKey(1) < 0)
{
if (predictionsQueue.empty())
continue;
std::vector<Mat> outs = predictionsQueue.get();
Mat frame = processedFramesQueue.get();
postprocess(frame, outs, net, backend);
if (predictionsQueue.counter > 1)
{
std::string label = format("攝像頭: %.2f FPS", framesQueue.getFPS());
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
label = format("網路: %.2f FPS", predictionsQueue.getFPS());
putText(frame, label, Point(0, 30), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
label = format("跳過的幀數: %d", framesQueue.counter - predictionsQueue.counter);
putText(frame, label, Point(0, 45), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
}
imshow(kWinName, frame);
}
process = false;
framesThread.join();
processingThread.join();
#else // USE_THREADS
if (asyncNumReq)
CV_Error(Error::StsNotImplemented, "僅推理引擎後端支援非同步前向。");
// 處理幀。
Mat frame, blob;
while (waitKey(1) < 0)
{
cap >> frame;
if (frame.empty())
{
break;
}
preprocess(frame, net, Size(inpWidth, inpHeight), scale, mean, swapRB);
std::vector<Mat> outs;
net.forward(outs, outNames);
postprocess(frame, outs, net, backend);
// 顯示效率資訊。
std::vector<double> layersTimes;
double freq = getTickFrequency() / 1000;
double t = net.getPerfProfile(layersTimes) / freq;
std::string label = format("推理時間: %.2f ms", t);
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
imshow(kWinName, frame);
}
#endif // USE_THREADS
return 0;
}
inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
const Scalar& mean, bool swapRB)
{
static Mat blob;
// 從幀建立 4D blob。
if (inpSize.width <= 0) inpSize.width = frame.cols;
if (inpSize.height <= 0) inpSize.height = frame.rows;
blobFromImage(frame, blob, 1.0, inpSize, Scalar(), swapRB, false, CV_8U);
// 執行模型。
net.setInput(blob, "", scale, mean);
if (net.getLayer(0)->outputNameToIndex("im_info") != -1) // Faster-RCNN 或 R-FCN
{
resize(frame, frame, inpSize);
Mat imInfo = (Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
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")
{
// 網路生成形狀為 1x1xNx7 的輸出 blob,其中 N 是檢測的數量,
// 每個檢測都是一個值向量
// [batchId, classId, confidence, left, top, right, bottom]
CV_Assert(outs.size() > 0);
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); // 跳過第 0 個背景類 ID。
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)
{
// 網路生成形狀為 NxC 的輸出 blob,其中 N 是檢測到的物件數量,
// C 是類數量 + 4,前 4 個數字為
// [center_x, center_y, width, height]
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);
Point classIdPoint;
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);
// NMS 僅在 DNN_BACKEND_OPENCV 的 Region 層內部使用,對於其他後端,我們需要在示例中
// 使用 NMS,或者當輸出數量 > 1 時需要 NMS
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)
{
Rect box = boxes[idx];
drawPred(classIds[idx], confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
}
}
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0));
std::string label = format("%.2f", conf);
if (!classes.empty())
{
CV_Assert(classId < (int)classes.size());
label = classes[classId] + ": " + label;
}
int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
top = max(top, labelSize.height);
rectangle(frame, Point(left, top - labelSize.height),
Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar());
}
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
n 維密集陣列類
定義 mat.hpp:830
int cols
定義 mat.hpp:2165
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_8U
#define CV_8U
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)
繪製連線兩點的線段。
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
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
定義 core.hpp:107