fatal error: opencv2/opencv_modules.hpp: No such file or directory #include "opencv2/opencv_modules.hpp"

Atharva Dubey picture Atharva Dubey · Aug 17, 2020 · Viewed 14.3k times · Source

Hello all I am trying to use opencv-c++ API (version 4.4.0) which I have built from source. It is installed in /usr/local/ and I was simply trying to load and display an image using the following code -

#include <iostream>
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/core.hpp>
#include <opencv4/opencv2/imgcodecs.hpp>
#include <opencv4/opencv2/highgui.hpp>
#include <opencv4/opencv2/core/cuda.hpp>

using namespace cv;

int main()
{
    std::string image_path = "13.jpg";
    cv::Mat img = cv::imreadmulti(image_path, IMREAD_COLOR);
    if(img.empty())
    {
        std::cout<<"COULD NOT READ IMAGE"<<std::endl;
        return 1;
    }
    imshow("Display Window", img);
    return 0;
}

And when I compile it throws the following error during compilation -

In file included from /CLionProjects/opencvTest/main.cpp:2:
/usr/local/include/opencv4/opencv2/opencv.hpp:48:10: fatal error: opencv2/opencv_modules.hpp: No such file or directory
 #include "opencv2/opencv_modules.hpp"

My Cmake is as follows -

cmake_minimum_required(VERSION 3.15)
project(opencvTest)

set(CMAKE_CXX_STANDARD 17)
include_directories("/usr/local/include/opencv4/opencv2/")
add_executable(opencvTest main.cpp)
target_link_libraries(opencvTest PUBLIC "/usr/local/lib/")

I do not know what am I doing wrong here.. This might be a noob question, But I ahev just started using opencv in C++

Answer

Atharva Dubey picture Atharva Dubey · Aug 17, 2020

The solution is to just include_directories path till /usr/local/opencv4 and it works perfectly.

However, the best way I believe is to use the find_package function. I updated my Cmake to the following and it takes care of linking during build.

cmake_minimum_required(VERSION 3.15)
project(opencvTest)

set(CMAKE_CXX_STANDARD 17)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(opencvTest main.cpp)
target_link_libraries(opencvTest ${OpenCV_LIBS})