如何访问 std::vector<cv::Mat> 的元素并将它们放在单独的矩阵中 cv::Mat
How to access elements of a std::vector<cv::Mat> and put them in separate matrices cv::Mat
我有一个包含 3 个矩阵(3 个图像)的 const std::vector<cv::Mat>
,为了在我的程序中进一步使用每个图像,我需要将它们保存在单独的矩阵中 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);
}
在您的代码中,请注意 imagesRGB
未初始化,其大小为 0
。 for
循环未被评估。此外,copyTo
方法将矩阵数据复制到另一个矩阵(如 paste 函数),它不用于将 cv::Mat
存储到 std::vector
.
您的描述不够清楚,但这里有一个我认为您可能需要的示例。如果要将 RGB
(3 个通道)图像拆分为三个单独的垫子,可以使用 cv::split
函数来完成。如果你想将 3 个单独的通道合并到一个 RGB
垫中,你可以通过 cv::merge
函数来实现。让我们看一下使用 this 测试图像的示例:
//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]);
请注意,我已经将频道存储在 array
中。但是,如果你想将单独的垫子存储到一个 std::vector
中,你可以使用 push_back
方法:
//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);
这是结果:
我有一个包含 3 个矩阵(3 个图像)的 const std::vector<cv::Mat>
,为了在我的程序中进一步使用每个图像,我需要将它们保存在单独的矩阵中 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);
}
在您的代码中,请注意 imagesRGB
未初始化,其大小为 0
。 for
循环未被评估。此外,copyTo
方法将矩阵数据复制到另一个矩阵(如 paste 函数),它不用于将 cv::Mat
存储到 std::vector
.
您的描述不够清楚,但这里有一个我认为您可能需要的示例。如果要将 RGB
(3 个通道)图像拆分为三个单独的垫子,可以使用 cv::split
函数来完成。如果你想将 3 个单独的通道合并到一个 RGB
垫中,你可以通过 cv::merge
函数来实现。让我们看一下使用 this 测试图像的示例:
//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]);
请注意,我已经将频道存储在 array
中。但是,如果你想将单独的垫子存储到一个 std::vector
中,你可以使用 push_back
方法:
//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);
这是结果: