Mat copyTo from row to col doesn't work! Why?

霸气de小男生 提交于 2020-01-23 02:18:07

问题


This answer states how to copy a row of a matrix to another row: How to copy a row of a Mat to another Mat's column in OpenCv? However if I try to copy a row of a matrix to a column vector the program is ends abruptly. Example:

Mat A(640,480,CV_64F);
Mat B(480,1,CV_64F);
A.row(0).copyTo(B.col(0));

A possible workaround is:

Mat A(640,480,CV_64F);
Mat B;
A.row(0).copyTo(B);
B = B.t();

But how can I get type CV_64F in B if A is a different type? Is the data type copied, too? And - most important – why do I need this workaround?


回答1:


copyTo() function can only copy data between the matrices of same size (width and height) and same type. For this reason you can't use it directly to copy row of matrix to column of matrix. Normally OpenCV will reallocate target matrix so that its size and type will match original image, but call to col() function returns constant temporary object that can't be reallocated. As a result your program crushed.

Actually this problem can be solved. You can copy row to column (if they have same amount of elements) and you can copy data between matrices of different types. Mat provides an iterator to its data, and that means you can use all C++ functions that works with iterators. copy() function for example.

Mat A(640, 480, CV_64F);
Mat B(480, 1, CV_32S); // note that the type don't have to be the same
Mat tmp = A.row(0); // no data is copied here. it is needed only because taking iterator to temporary object is really bad idea
copy(tmp.begin<double>(), tmp.end<double>(), B.begin<int>());



回答2:


Since code like the following (transposing the row only) is not supported by the API:

A.row(0).t().copyTo( B.col(0) );

The workaround is either create a temporary matrix from the row, transpose it, then copy to your target matrix

Mat temp = A.row(0);
temp = temp.t();
temp.copyTo( B.col(0) );

I would rather do something like this though:

Mat A( 640, 480,CV_64F );
Mat B( 1, 480, CV_64F );  /* rather than 480 x 1, make a 1 x 480 first */
A.row(0).copyTo( B.row(0) );
B = B.t(); /* transpose it afterwards */

I presume this is all just because the API is not supporting it yet.



来源:https://stackoverflow.com/questions/23613787/mat-copyto-from-row-to-col-doesnt-work-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!