如何将具有两个通道的Mat转换为vector <vector <int >>?

时间:2018-08-14 05:38:35

标签: c++ opencv vector vectorization mat

如果我有垫子

Mat mat = (Mat_<int>(1, 8) << 5, 6, 0, 4, 0, 1, 9, 9);

我当然可以将mat转换为向量vec

vector<int> vec(mat.begin<int>(), mat.end<int>());

但是当mat有2个或更多通道时,如何将其转换为vector<vector<int>>?我的意思是如果我有这样的mat

int vec[4][2] = { {5, 6}, {0, 4}, {0,1}, {9, 9} };
Mat mat(4,1,CV_32SC2,vec);

如何获得vector<vector<int>> vec2{ {5, 6}, {0, 4}, {0,1}, {9, 9} }?当然,我们可以像这样遍历非常大的像素

vector<vector<int>> vec2;
for (int i = 0; i < 4; i++) {
    Vec2i*p = mat.ptr<Vec2i>(i);
    vec2.push_back(vector<int>());
    vec2[vec2.size() - 1].push_back(p[0][0]);
    vec2[vec2.size() - 1].push_back(p[0][1]);
}

但是任何更好的方法都可以做到这一点?

2 个答案:

答案 0 :(得分:1)

对于CV_32SC3类型的图像,请尝试以下代码段:

cv::Mat image = imread("picture.jpg");
cv::Scalar scalar[3] = { { 255, 0, 0}, { 0,255,  0 }, { 0, 0, 255 } };
Mat channel[3];
vector<vector<int>> splitted_images;
for (int i = 0; i < 3; i++) {
    channel[i] = image & scalar[i];
    vector<int> vec(channel[i].begin<int>(), channel[i].end<int>());
    splitted_images.push_back(vec);
}

答案 1 :(得分:0)

您可以尝试使用具有2个或更多通道的Mat

vector<int> vec1, vec2;
//we can convert the 2 channel image into a single channel image with 2 columns
mat.reshape(1).col(0).copyTo(vec1); //to access the first column
mat.reshape(1).col(1).copyTo(vec2); //to access the second column


//Or like this (if you know the number of channels
vector<vector<int>> vec(2);
mat.reshape(1).col(0).copyTo(vec[0]); //to access the first column
mat.reshape(1).col(1).copyTo(vec[1]); //to access the second column


//You can make them into a vector of points like this
vector<Point> pts;
mat.copyTo(pts);