将矩阵复制到另一个矩阵的子集

时间:2021-08-24 16:02:49

I'm having difficulty copying a subset of a matrix into another larger matrix using OpenCV in C++.

我很难在C ++中使用OpenCV将矩阵的子集复制到另一个更大的矩阵中。

I tried the following code:

我尝试了以下代码:

#include <opencv2/opencv.hpp>

void printMatrix(const cv::Mat &M, std::string matrix)
{
    printf("Matrix \"%s\" is %i x %i\n", matrix.c_str(), M.rows, M.cols);
    std::cout << M << std::endl;
}

int main(int argc, char ** argv)
{
    cv::Mat P0(3, 4, CV_32F);
    printMatrix(P0, "P0 Initial");

    cv::Mat R0 = cv::Mat::eye(3,3,CV_32F);
    printMatrix(R0, "R0 I");

    R0.copyTo(P0.colRange(0,2));
    printMatrix(P0, "P0 with R");

    return 0;
}

Which produces the following output:

其中产生以下输出:

Matrix "P0 Initial" is 3 x 4
[-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008]

Matrix "R0 I" is 3 x 3
[1, 0, 0;
0, 1, 0;
0, 0, 1]

Matrix "P0 with R" is 3 x 4
[-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008;
-4.3160208e+008, -4.3160208e+008, -4.3160208e+008, -4.3160208e+008]

While suggests that the copy operation is not doing anything.

虽然表明复制操作没有做任何事情。

I found a similar post here but updating the relevant line to the following as suggested in that post still produces the same output.

我在这里发现了一个类似的帖子,但是根据该帖子的建议将相关的行更新为以下内容仍会产生相同的输出。

//R0.copyTo(P0.colRange(0,2));
cv::Mat dest = P0.colRange(0,2);
printMatrix(P0, "P0 with R");

1 个解决方案

#1


4  

Your code doesn't compile for me. I get an error at R0.copyTo(P0.colRange(0,2)); (and also if I try R0.copyTo(P0.colRange(0,3)); which has the correct range.) But this does work for me:

你的代码不能为我编译。我在R0.copyTo收到错误(P0.colRange(0,2)); (如果我尝试R0.copyTo(P0.colRange(0,3));它具有正确的范围。)但这对我有用:

    cv::Mat dest(P0.colRange(0,3));
    R0.copyTo(dest);
    printMatrix(P0, "P0 with R");

You almost had it in your last code example, but you left out copyTo (and your range was incorrect).

你几乎已经在最后一个代码示例中使用了它,但是你遗漏了copyTo(并且你的范围不正确)。

#1


4  

Your code doesn't compile for me. I get an error at R0.copyTo(P0.colRange(0,2)); (and also if I try R0.copyTo(P0.colRange(0,3)); which has the correct range.) But this does work for me:

你的代码不能为我编译。我在R0.copyTo收到错误(P0.colRange(0,2)); (如果我尝试R0.copyTo(P0.colRange(0,3));它具有正确的范围。)但这对我有用:

    cv::Mat dest(P0.colRange(0,3));
    R0.copyTo(dest);
    printMatrix(P0, "P0 with R");

You almost had it in your last code example, but you left out copyTo (and your range was incorrect).

你几乎已经在最后一个代码示例中使用了它,但是你遗漏了copyTo(并且你的范围不正确)。