如何将C ++数组转换为OpenCV Mat [英] How to convert C++ array to opencv Mat
问题描述
将C ++数组转换为2D opencv Mat对象的最快方法是什么?
蛮力方法是在2D垫的所有条目上循环并用数组的值填充它们.
有没有更好/更快的方法呢?
我能以某种方式将数组的指针指向2D矩阵吗?
(我使用的是opencv 2.4.8)
What is the fastest way to convert a C++ array into an 2D opencv Mat object?
Brute force method would be to loop over all entries of the 2D mat and fill them with values of the array.
Is there a better / faster way to do that?
Could I somehow just give pointer of the array to the 2D matrix?
(I'm using opencv 2.4.8)
推荐答案
Yes there is, in the documentation of cv::Mat
you can see how it can be achieved.
具体在这一行
C ++:Mat :: Mat(int行,int cols,int类型,void *数据,size_t step = AUTO_STEP)
C++: Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
这意味着您可以做类似的事情
This means that you can do something like
double x[100][100];
cv::Mat A(100, 100, CV_64F, x);
这不会将数据复制到其中.您还必须记住,OpenCV数据是以行为主的,这意味着它具有一行的所有列,然后是下一行,依此类推.因此,您的数组必须匹配此样式才能起作用.
This will not copy the data to it. You have to also remember that OpenCV data is row major, which means that it has all the columns of one rows and then the next row and so on. So your array has to match this style for it to work.
关于速度有多快,文档中也谈到了它:
About how fast it is, the documentation also talks about it:
数据 –指向用户数据的指针.带有数据和步骤参数的矩阵构造函数不分配矩阵数据.相反,它们只是初始化指向指定数据的矩阵头,这意味着不会复制任何数据.此操作非常有效,可用于使用OpenCV功能处理外部数据.外部数据不会自动释放,因此您应该注意这一点.
data – Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
它会非常快地工作,但是它是同一数组,如果在cv::Mat
之外修改它,它将在cv::Mat
中修改,并且如果它在任何时候被破坏,则data
cv::Mat
的成员将指向不存在的地方.
It will work quite fast, but it is the same array, if you modified it outside of the cv::Mat
, it will be modified in the cv::Mat
, and if it is destroyed at any point, the data
member of cv::Mat
will point to a non-existant place.
更新:
我也忘了说,您可以创建cv::Mat
并执行 std :: memcpy .这样,它将复制数据,这可能会比较慢,但是数据将由cv::Mat
对象拥有,并由cv::Mat
销毁器销毁.
I forgot to also say, that you can create the cv::Mat
and do std::memcpy. This way it will copy the data, which may be slower, but the data will be owned by the cv::Mat
object and destroyed upon with the cv::Mat
destroyer.
double x[100][100];
cv::Mat A(100,100,CV_64F);
std::memcpy(A.data, x, 100*100*sizeof(double));
这篇关于如何将C ++数组转换为OpenCV Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!