OpenCV 4.12.0
開源計算機視覺
載入中...
搜尋中...
無匹配項
samples/dnn/segmentation.cpp
#include <fstream>
#include <sstream>
#include <opencv2/dnn.hpp>
#include "common.hpp"
std::string keys =
"{ help h | | Print help message. }"
"{ @alias | | 模型別名,用於從 models.yml 檔案中提取預處理引數。}"
"{ zoo | models.yml | 包含預處理引數檔案的可選路徑 }"
"{ device | 0 | 攝像頭裝置號。}"
"{ input i | | 輸入影像或影片檔案的路徑。跳過此引數以從攝像頭捕獲幀。}"
"{ framework f | | 模型原始框架的可選名稱。如果未設定,則自動檢測。}"
"{ classes | | 包含類別名稱文字檔案的可選路徑。}"
"{ colors | | 包含每個類別顏色文字檔案的可選路徑。"
"每種顏色由BGR通道順序的0到255的三個值表示。}"
"{ 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(半精度浮點預處理)}";
using namespace cv;
using namespace dnn;
std::vector<std::string> classes;
std::vector<Vec3b> colors;
void showLegend();
void colorizeSegmentation(const Mat &score, Mat &segm);
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;
}
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");
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");
// 開啟包含類名稱的檔案。
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 + " 未找到");
std::string line;
while (std::getline(ifs, line))
{
classes.push_back(line);
}
}
// 開啟顏色檔案。
if (parser.has("colors"))
{
std::string file = parser.get<String>("colors");
std::ifstream ifs(file.c_str());
if (!ifs.is_open())
CV_Error(Error::StsError, "檔案 " + file + " 未找到");
std::string line;
while (std::getline(ifs, line))
{
std::istringstream colorStr(line.c_str());
Vec3b color;
for (int i = 0; i < 3 && !colorStr.eof(); ++i)
colorStr >> color[i];
colors.push_back(color);
}
}
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(parser.get<int>("device"));
// 處理幀。
Mat frame, blob;
while (waitKey(1) < 0)
{
cap >> frame;
if (frame.empty())
{
break;
}
blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, false);
net.setInput(blob);
Mat score = net.forward();
Mat segm;
colorizeSegmentation(score, segm);
resize(segm, segm, frame.size(), 0, 0, INTER_NEAREST);
addWeighted(frame, 0.1, segm, 0.9, 0.0, frame);
// 顯示效率資訊。
std::vector<double> layersTimes;
double freq = getTickFrequency() / 1000;
double t = net.getPerfProfile(layersTimes) / freq;
std::string label = format("推理時間:%.2f 毫秒", t);
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
imshow(kWinName, frame);
if (!classes.empty())
showLegend();
}
return 0;
}
void colorizeSegmentation(const Mat &score, Mat &segm)
{
const int rows = score.size[2];
const int cols = score.size[3];
const int chns = score.size[1];
if (colors.empty())
{
// Generate colors.
colors.push_back(Vec3b());
for (int i = 1; i < chns; ++i)
{
Vec3b color;
for (int j = 0; j < 3; ++j)
color[j] = (colors[i - 1][j] + rand() % 256) / 2;
colors.push_back(color);
}
}
else if (chns != (int)colors.size())
{
CV_Error(Error::StsError, format("輸出類別數量與"
"顏色數量不匹配 (%d != %zu)", chns, colors.size()));
}
Mat maxCl = Mat::zeros(rows, cols, CV_8UC1);
Mat maxVal(rows, cols, CV_32FC1, score.data);
for (int ch = 1; ch < chns; ch++)
{
for (int row = 0; row < rows; row++)
{
const float *ptrScore = score.ptr<float>(0, ch, row);
uint8_t *ptrMaxCl = maxCl.ptr<uint8_t>(row);
float *ptrMaxVal = maxVal.ptr<float>(row);
for (int col = 0; col < cols; col++)
{
if (ptrScore[col] > ptrMaxVal[col])
{
ptrMaxVal[col] = ptrScore[col];
ptrMaxCl[col] = (uchar)ch;
}
}
}
}
segm.create(rows, cols, CV_8UC3);
for (int row = 0; row < rows; row++)
{
const uchar *ptrMaxCl = maxCl.ptr<uchar>(row);
Vec3b *ptrSegm = segm.ptr<Vec3b>(row);
for (int col = 0; col < cols; col++)
{
ptrSegm[col] = colors[ptrMaxCl[col]];
}
}
}
void showLegend();
{
static const int kBlockHeight = 30;
static Mat legend;
if (legend.empty())
{
const int numClasses = (int)classes.size();
if ((int)colors.size() != numClasses)
{
CV_Error(Error::StsError, format("輸出類別數量與"
"標籤數量不匹配 (%zu != %zu)", colors.size(), classes.size()));
}
legend.create(kBlockHeight * numClasses, 200, CV_8UC3);
for (int i = 0; i < numClasses; i++)
{
Mat block = legend.rowRange(i * kBlockHeight, (i + 1) * kBlockHeight);
block.setTo(colors[i]);
putText(block, classes[i], Point(0, kBlockHeight / 2), FONT_HERSHEY_SIMPLEX, 0.5, Vec3b(255, 255, 255));
}
namedWindow("圖例", WINDOW_NORMAL);
imshow("圖例", legend);
}
}
如果陣列沒有元素,則返回 true。
int64_t int64
n 維密集陣列類
定義 mat.hpp:830
Mat & setTo(InputArray value, InputArray mask=noArray())
將所有或部分陣列元素設定為指定值。
MatSize size
定義 mat.hpp:2187
uchar * data
指向資料的指標
定義 mat.hpp:2167
void create(int rows, int cols, int type)
如果需要,分配新的陣列資料。
uchar * ptr(int i0=0)
返回指向指定矩陣行的指標。
Mat rowRange(int startrow, int endrow) const
為指定的行跨度建立一個矩陣頭。
cv::getTickFrequency
double getTickFrequency()
用於指定影像或矩形大小的模板類。
Definition types.hpp:335
用於短數值向量的模板類,是 Matx 的特例。
定義 matx.hpp:369
用於從影片檔案、影像序列或攝像頭捕獲影片的類。
Definition videoio.hpp:772
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
開啟影片檔案、捕獲裝置或 IP 影片流以進行影片捕獲。
void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst, int dtype=-1)
計算兩個陣列的加權和。
std::string String
定義 cvstd.hpp:151
#define CV_32FC1
定義 interface.h:118
I.at<uchar>(y, x) = saturate_cast<uchar>(r);
uchar
unsigned char uchar
#define CV_8UC1
定義 interface.h:88
CV_8UC3
#define CV_8UC3
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 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 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
定義 core.hpp:107