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