MATLAB 上的矩阵操作到 C++ 或 OpenCV

Matrix manipulation on MATLAB to C++ or OpenCV

本文关键字:C++ OpenCV 操作 MATLAB      更新时间:2023-10-16

我正在尝试在C++中执行此操作,但我无法理解它。我试着看 http://mathworks.com/help/matlab/ref/image.html 但我仍然不明白。

im 是 Matlab 中的一个矩阵。宽度为 640

im(:,Width+(1:2),:) = im(:,1:2,:);

在矩阵或C++中是否有与此类似的操作OpenCV

解决方案 1

您可以使用 colRange 函数:

mat.colRange(0, 2).copyTo(mat.colRange(w, 2 + w)); 

例:

//initilizes data
float data[2][4] = { { 1, 2, 3, 4}, { 5, 6, 7, 8 } };
Mat mat(2, 4, CV_32FC1, &data);
int w = 2; //w is equivelant to Width in your script, in this case I chose it to be 2
std::cout << "mat before: n" << mat << std::endl;
mat.colRange(0, 2).copyTo(mat.colRange(w, 2 + w)); 
std::cout << "mat after: n" << mat << std::endl;

结果:

mat before:
[1, 2, 3, 4;
 5, 6, 7, 8]
mat after:
[1, 2, 1, 2;
 5, 6, 5, 6]

解决方案 2

或者,使用 cv::Rect 对象,如下所示:

cv::Mat roi = mat(cv::Rect(w, 0, 2, mat.rows));
mat(cv::Rect(0, 0, 2, mat.rows)).copyTo(roi);

有几种方法可以初始化 Rect,在我的情况下,我选择了以下 c-tor:

cv::Rect(int x, int y, int width, int height);

结果与解决方案 1 中的 相同。

也许你也可以使用可以满足需求的本征。它具有块操作

改编链接下提供的示例,您需要像这样:

Eigen::MatrixXf m(4, 4);
m << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
cout <<"original matrix n" << m << endl;
m.block<2, 2>(1, 1) = m.block<2, 2>(2, 2);
cout <<"modified matrix n" << m << endl;

输出:

original matrix 
1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16
modified matrix 
1  2  3  4
5 11 12  8
9 15 16 12
13 14 15 16