函数返回并使用copyTo的OpenCV Mat [英] OpenCV Mat in function return and using copyTo

查看:454
本文介绍了函数返回并使用copyTo的OpenCV Mat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个片段来执行齐次矩阵的逆运算

I have this snippet to perform inverse of a homogeneous matrix

Mat invHom(const Mat A)
{
    Mat invA = Mat::eye(4,4,CV_64FC1);
    Mat R, P;

    A(Range(0,3), Range(0,3)).copyTo(R);
    A(Range(0,3), Range(3,4)).copyTo(P);

    invA(Range(0,3), Range(0,3)) = R.t();
    invA(Range(0,3), Range(3,4)) = -R.t()*P;
    return invA;
}

此代码容易出错吗?因为invA,R,P是在功能范围内创建的Mat.函数的返回"执行创建和创建吗?复制到新的Mat对象(即Mat :: copyTo()),以便在函数外仍然可以使用invA的值?

is this code tend to error? since invA, R, P are Mat created in function scope. Does the "return" of the function perform creation & copying to a new Mat object (i.e. Mat::copyTo()) so that value of invA is still available outside the function?

对不起,我的英语不好和编程的条件

Sorry for my bad English and terms of programming

一个没有错误:

int invHom(const Mat A, Mat& invA_ou)
{
    Mat invA = Mat::eye(4,4,CV_64FC1);

    Mat R, P;
    A(Range(0,3), Range(0,3)).copyTo(R);
    A(Range(0,3), Range(3,4)).copyTo(P);

    //invA(Range(0,3), Range(0,3)) = R.t();
    //invA(Range(0,3), Range(3,4)) = -R.t()*P;

    Mat tmp1 = R.t();
    tmp1.copyTo(invA(Range(0,3), Range(0,3)));

    Mat tmp = -R.t()*P;
    tmp.copyTo(invA(Range(0,3), Range(3,4)));

    invA.copyTo(invA_ou);
    return 1;
}

推荐答案

代码正常. Mat是基本上由标头和实际数据组成的对象.复制Mat时,仅复制标头,而不复制数据(这就是复制速度非常快的原因).复制时,内部参考计数器会增加.当参考计数器为零时,将释放数据. 要执行深度复制,您需要方法clone()copyTo(...).

The code is ok. Mat is an object basically composed by an header and the actual data. When you copy a Mat you're copying the header only, not the data (that's why it's very fast). When you copy, an internal reference counter is incremented. When the reference counter is zero, data will be released. To perform a deep copy, you need the method clone() or copyTo(...).

所以,就您而言,您还可以.

So, in your case you're fine.

您可以在此处以获得更多详细信息.

You can look at OpenCV doc here for further details.

另一种编码方式是将输出矩阵作为参数传递,例如:

An alternative coding style would be to pass the output matrix as argument, like:

void invHom(const Mat& A, Mat& invA)
{
    invA = Mat::eye(4,4,CV_64FC1);
    Mat R, P;

    A(Range(0,3), Range(0,3)).copyTo(R);
    A(Range(0,3), Range(3,4)).copyTo(P);

    invA(Range(0,3), Range(0,3)) = R.t();
    invA(Range(0,3), Range(3,4)) = -R.t()*P;        
}

请注意,将引用(&)传递给Mat,您甚至都不会复制标题.

Note that passing references (&) to Mat, you don't even copy the header.

这篇关于函数返回并使用copyTo的OpenCV Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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