1

I want to read an array of images in c++ and I wrote this sample code:

std::vector<Mat> ReadInputImages()
{
    Mat tmp1=imread("C:/tmp/im1.jpg");
    Mat tmp2=imread("C:/tmp/im2.jpg");
    Mat tmp3=imread("C:/tmp/im3.jpg");
    Mat tmp4=imread("C:/tmp/im4.jpg");
    std::vector<Mat> images;
    images={tmp1,tmp2,tmp3,tmp4};
    return images;
}

But it doesn't work and I am getting compiler error on

   images={tmp1,tmp2,tmp3,tmp4};

What is the best way to return an array of images from a function.

1 Answer 1

7

The C++11 initialitzation syntax would be

std::vector<Mat> images={tmp1,tmp2,tmp3,tmp4};

or

std::vector<Mat> images{tmp1,tmp2,tmp3,tmp4};

But you do not need to declare a temporary vector, you can return one directly:

std::vector<Mat> ReadInputImages()
{
  return std::vector<Mat>{imread("C:/tmp/im1.jpg"),
                          imread("C:/tmp/im2.jpg"),
                          imread("C:/tmp/im3.jpg"),
                          imread("C:/tmp/im4.jpg")};
}

If you do not have C++11 support, you can simply push elements back into an existing vector,

std::vector<Mat> ReadInputImages()
{
    std::vector<Mat> images;
    images.push_back(imread("C:/tmp/im1.jpg"));
    images.push_back(imread("C:/tmp/im2.jpg"));
    images.push_back(imread("C:/tmp/im3.jpg"));
    images.push_back(imread("C:/tmp/im4.jpg"));
    return images;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Does visual studio 2012 support c++11?
@mans my understanding is that it supports a large subset of it. Unfortunately, according to that page, initializer lists isn't part of it.
Thanks. Which page do you referring?
@mans click on "a large subset of it" in my previous comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.