0

我有一个const std::vector<cv::Mat>包含 3 个矩阵(3 个图像),为了在我的程序中进一步使用每个图像,我需要将它们保存在单独的矩阵cv::Mat中。我知道我需要遍历向量元素,因为这个向量是一个矩阵列表,但不知何故我无法管理它。最后,我还需要将 3 个矩阵推回一个向量。如果有人可以帮助我解决这个问题,我将不胜感激。我还在学习它。

std::vector<cv::Mat> imagesRGB;
cv::Mat imgR, imgG, imgB;

for(size_t i=0; i<imagesRGB.size(); i++)
{
   imagesRGB[i].copyTo(imgR);
}
4

1 回答 1

0

In your code, note that imagesRGB is uninitialized, and its size is 0. The for loop is not evaluated. Additionally, the copyTo method copies matrix data into another matrix (like a paste function), it is not used to store a cv::Mat into a std::vector.

Your description is not clear enough, however here's an example of what I think you might be needing. If you want to split an RGB (3 channels) image into three individual mats, you can do it using the cv::split function. If you want to merge 3 individual channels into an RGB mat, you can do that via the cv::merge function. Let's see the example using this test image:

//Read input image:
cv::Mat inputImage = cv::imread( "D://opencvImages//lena512.png" );

//Split the BGR image into its channels:
cv::Mat splitImage[3];
cv::split(inputImage, splitImage);

//show images:
cv::imshow("B", splitImage[0]);
cv::imshow("G", splitImage[1]);
cv::imshow("R", splitImage[2]);

Note that I'm already storing the channels in an array. However, if you want to store the individual mats into a std::vector, you can use the push_back method:

//store the three channels into a vector:
std::vector<cv::Mat> matVector;

for( int i = 0; i < 3; i++ ){
    //get current channel:
    cv::Mat currentChannel = splitImage[i];
    //store into vector
    matVector.push_back(currentChannel);
}

//merge the three channels back into an image:
cv::Mat mergedImage;
cv::merge(matVector, mergedImage);

//show final image:
cv::imshow("Merged Image", mergedImage);
cv::waitKey(0);

This is the result:

于 2021-03-15T04:39:44.643 回答