垫copyTo从行到col不起作用!为什么? [英] Mat copyTo from row to col doesn't work! Why?

查看:124
本文介绍了垫copyTo从行到col不起作用!为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案说明了如何将矩阵的一行复制到另一行:

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));

可能的解决方法是:

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

但是如果A是其他类型,如何在B中获得类型CV_64F?数据类型也被复制吗?而且-最重要的-为什么我需要这种解决方法?

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?

推荐答案

copyTo()函数只能在相同大小(宽度和高度)和相同类型的矩阵之间复制数据.因此,您不能直接使用它来将矩阵的行复制到矩阵的列.通常,OpenCV将重新分配目标矩阵,以便其大小和类型与原始图像匹配,但是对col()函数的调用将返回无法重新分配的常量临时对象.结果您的程序崩溃了.

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.

实际上这个问题可以解决.您可以将行复制到列(如果它们具有相同数量的元素),并且可以在不同类型的矩阵之间复制数据. Mat为它的数据提供了一个迭代器,这意味着您可以使用所有与迭代器一起使用的C ++函数.例如copy()函数.

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>());

这篇关于垫copyTo从行到col不起作用!为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆