C++ 如何使用浮点数组中的数据初始化 cv::Mat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22739320/
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 can I initialize a cv::Mat with data from a float array
提问by Brett
I need to create a cv::Mat
variable that is initialized with my data from a float *
array.
This should be basic, but I'm having trouble figuring it out.
我需要创建一个cv::Mat
用float *
数组中的数据初始化的变量。这应该是基本的,但我无法弄清楚。
I have the code:
我有代码:
float *matrixAB = <120 floating point array created elsewhere>;
cv::Mat cv_matrixAB = cv::Mat(12, 10, CV_32F, &matrixAB);
but cv_matrixAB
never contains float
values, and more importantly doesn't match the data contained in matrixAB
.
但从cv_matrixAB
不包含float
值,更重要的是不匹配包含在matrixAB
.
If I change the line to:
如果我将行更改为:
cv::Mat cv_matrixAB = cv::Mat(12, 10, CV_32F, matrixAB);
then the cv_matrixAB.data
are all 0
. I have also tried using CV_64F
as the type, but I see the same behaivor.
那么cv_matrixAB.data
都是0
。我也尝试使用CV_64F
as 类型,但我看到了相同的行为。
Can anyone help me identify where I am going wrong?According to the cv::Mat
constructor documentation, I should be able to provide my data in the form of a float *
array.
谁能帮我确定我哪里出错了?根据cv::Mat
构造函数文档,我应该能够以float *
数组的形式提供我的数据。
Update:a little more info here:
Even the following code does not work. The printf
displays 63
, which of course is not a value in dummy_query_data
.
更新:这里有更多信息:即使下面的代码也不起作用。的printf
显示器63
,这当然不是一个值dummy_query_data
。
float dummy_query_data[10] = { 1, 2, 3, 4,
5, 6, 7, 8 };
cv::Mat dummy_query = cv::Mat(2, 4, CV_32F, dummy_query_data);
printf("%f\n", (float)dummy_query.data[3]);
回答by herohuyongtao
You're doing fine. But you should access the mat element by using at<float>()
instead of .data
(which will give you uchar *
). Or simply use cout << mat;
to print all its elements. It will give you the expected result.
你做的不错。但是你应该使用at<float>()
而不是访问 mat 元素.data
(这会给你uchar *
)。或者简单地用于cout << mat;
打印其所有元素。它会给你预期的结果。
float dummy_query_data[10] = { 1, 2, 3, 4, 5, 6, 7, 8 };
cv::Mat dummy_query = cv::Mat(2, 4, CV_32F, dummy_query_data);
cout << dummy_query.at<float>(0,2) << endl;
cout << dummy_query << endl;
It will output:
它会输出:
3
[1, 2, 3, 4;
5, 6, 7, 8]