C++ 如何在 OpenCV 中创建空 Mat?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31337397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create empty Mat in OpenCV?
提问by mrgloom
How to create empty Mat in OpenCV? After creation I want to use push_back method to push rows in Mat.
如何在 OpenCV 中创建空 Mat?创建后,我想使用 push_back 方法在 Mat 中推送行。
Something like:
就像是:
Mat M(0,3,CV_32FC1);
or only option is:
或唯一的选择是:
Mat M;
M.converTo(M,CV_32FC1);
?
?
回答by Miki
You can create an empty matrix simply using:
您可以简单地使用以下方法创建一个空矩阵:
Mat m;
If you already know its type, you can do:
如果你已经知道它的type,你可以这样做:
Mat1f m; // Empty matrix of float
If you know its size:
如果你知道它的大小:
Mat1f m(rows, cols); // rows, cols are int
or
Mat1f m(size); // size is cv::Size
And you can also add the default value:
您还可以添加默认值:
Mat1f m(2, 3, 4.1f);
//
// 4.1 4.1 4.1
// 4.1 4.1 4.1
If you want to add values to an empty matrix with push_back
, you can do as already suggested by @berak:
如果您想使用 将值添加到空矩阵push_back
,您可以按照@berak 的建议进行操作:
Mat1f m;
m.push_back(Mat1f(1, 3, 3.5f)); // The first push back defines type and width of the matrix
m.push_back(Mat1f(1, 3, 9.1f));
m.push_back(Mat1f(1, 3, 2.7f));
// m
// 3.5 3.5 3.5
// 9.1 9.1 9.1
// 2.7 2.7 2.7
If you need to push_back data contained in vector<>
, you should take care to put values in a matrix and transpose it.
如果需要 push_back 中包含的数据vector<>
,则应注意将值放入矩阵中并对其进行转置。
vector<float> v1 = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};
vector<float> v2 = {1.2f, 2.3f, 3.4f, 4.5f, 5.6f};
Mat1f m1(Mat1f(v1).t());
Mat1f m2(Mat1f(v2).t());
Mat1f m;
m.push_back(m1);
m.push_back(m2);
// m
// 1.1 2.2 3.3 4.4 5.5
// 1.2 2.3 3.4 4.5 5.6
回答by berak
just start with an empty Mat. the 1st push_back will determine type and size.
只需从一个空的垫子开始。第一个 push_back 将确定类型和大小。
Mat big;
big.push_back(Mat(1,5,CV_64F,3.5));
big.push_back(Mat(1,5,CV_64F,9.1));
big.push_back(Mat(1,5,CV_64F,2.7));
[3.5, 3.5, 3.5, 3.5, 3.5;
9.1, 9.1, 9.1, 9.1, 9.1;
2.7, 2.7, 2.7, 2.7, 2.7]