OpenCV imread(std::string filename, int flags) problem when using a variable for string filename in c++

  arguments, c++, imread, opencv

I have a function that is something like this:

void OpenPattern(std::string filename, bool type){
    Mat img = cv::imread(filename, cv::IMREAD_COLOR);
    if(img.empty()){
        printf("CANNOT OPEN IMAGE");
    }else{
        doSomethingElse();
    }
}

the code compiles alright, but when I run it, img is always empty.
I’ve tested filename storing a relative path and a full path to the image. Neither worked here.
I printed the filename content every time and it matched with the image address perfectly.
It only worked when I tested like this:

void OpenPattern(std::string filename, bool type){
    filename="path to image" //worked with relative and full path
    Mat img = cv::imread(filename, cv::IMREAD_COLOR);
    //or
   //Mat img = cv::imread("path to image", cv::IMREAD_COLOR);
    if(img.empty()){
        printf("CANNOT OPEN IMAGE");
    }else{
        doSomethingElse();
    }
}

I think many people have asked something similar to this (like this one here imread() won't read string variable in c++), but I haven’t found an answer yet.

Does anyone know why the imread() simply can’t open when the filename is a function argument? Or does anyone know if there is a way to investigate where imread decides to return the NULL Mat, so I can better investigate what is happening?

Thanks a lot!

Source: Windows Questions C++

LEAVE A COMMENT