有一个3*3的Mat变量,元素分别是1、2、3、4、5、6、7、8、9,现把这个矩阵展开,顺序是1、4、7、8、5、2、3、6、9,用c++和opencv写出代码
时间: 2023-12-19 19:05:42 浏览: 19
以下是使用C++和OpenCV将3x3矩阵展开的代码:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 创建3x3矩阵
Mat mat(3, 3, CV_32FC1);
mat.at<float>(0, 0) = 1;
mat.at<float>(0, 1) = 2;
mat.at<float>(0, 2) = 3;
mat.at<float>(1, 0) = 4;
mat.at<float>(1, 1) = 5;
mat.at<float>(1, 2) = 6;
mat.at<float>(2, 0) = 7;
mat.at<float>(2, 1) = 8;
mat.at<float>(2, 2) = 9;
// 展开矩阵
Mat result(1, 9, CV_32FC1);
int index = 0;
for (int i = 0; i < 3; i++) {
if (i % 2 == 0) {
for (int j = 0; j < 3; j++) {
result.at<float>(0, index) = mat.at<float>(j, i);
index++;
}
}
else {
for (int j = 2; j >= 0; j--) {
result.at<float>(0, index) = mat.at<float>(j, i);
index++;
}
}
}
// 输出结果
cout << "展开后的矩阵为:" << endl;
for (int i = 0; i < 9; i++) {
cout << result.at<float>(0, i) << " ";
}
cout << endl;
return 0;
}
```