Unable to read file "lenna.png" (OpenCV 4.5.1, Ubuntu 20.04, Visual studio Code)

OpenCV journey starting off not so good. The CMake build executes and links the executable successfully however the program is unable to find lenna.png when it is in the same directory as main.cpp


#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

int main()
    std::cout << "Found OpenCV cmake package" << std::endl;
    cv::Mat image = cv::imread("lenna.png", cv::IMREAD_GRAYSCALE);

    if (! image.data)
        std::cerr << "Image not found" << std::endl;
        return 1;

    const std::string window_name{"lenna"};
    cv::imshow(window_name, image);

    return 0;

Directory structure:
├── build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ ├── compile_commands.json
│ └── Makefile
├── CMakeLists.txt
├── include
│ └── CMakeLists.txt
├── lenna.png
├── libs
└── main.cpp


john@ubuntu:~/Documents/test/opencv/build$ ./opencv_example 
Found OpenCV cmake package
Image not found

your current working directory is ~/Documents/test/opencv/build

is lenna.jpg in your current working directory?

processes don’t know where their source is. they only know where they’re executing.

Perhaps you are looking for lena.png not lenna.png.

As @crackwitz already mentioned - you run code in different folder and there is no lenna.png in this folder.

First you could try with /full/path/to/lenna.png in code.

If you don’t use full path then you should go back to folder with image and run from this folder:

cd ..

Or you should copy opencv_example to folder with image. And run from folder with image


But even if you have code in the same folder as image you may try to run code from other folder and then system may use other folder as so called Current Working Directory (cwd) and search image in this cwd - and then you may try to use argv[0] to create full path to image. But I don’t know how it will be in C/C++. In Python I would do

APP_FOLDER = os.path.dirname(os.path.abspath(sys.argv[0]))

full_path_to_image = os.path.join(APP_FOLDER, "lenna.png")

BTW: To check in Linux/Bash current working directory