1

I am new to C++ and OpenCV and I am stuck on this problem. I am using VS Code version 1.68.1 and when I try to run a main.cpp file, I always get this error:

main.cpp:2:10: fatal error: opencv2/opencv.hpp: No such file or directory 

    2 | #include "opencv2/opencv.hpp"
      |          ^~~~~~~~~~~~~~~~~~~~

This is the main.cpp code:

#include <stdio.h>
#include "opencv2/opencv.hpp"

using namespace cv;
int main(int argc, char** argv )
{

    Mat image;
    image = imread("lenna.jpg");
    if ( !image.data )
    {
        printf("No image data \n");
        return -1;
    }
    namedWindow("Display Image", WINDOW_AUTOSIZE );
    imshow("Display Image", image);
    waitKey(0);
    return 0;
}

My CMakelists.txt file:

cmake_minimum_required(VERSION 3.0.0)
project(opencvTest)

include(CTest)
enable_testing()

set("OpenCV_DIR" "C:\\opencv4")
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )

add_executable(opencvTest main.cpp)
target_link_libraries(opencvTest ${OpenCV_LIBS} )

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "g++.exe build active file",
            "command": "C:\\msys64\\mingw64\\bin\\g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "-ID","C:\\opencv4\\install\\include",
                "-LD","C:\\opencv4\\install\\x64\\mingw\\bin",                
                "-llibopencv_calib3d411",
                "-llibopencv_core411",
                "-llibopencv_dnn411",
                "-llibopencv_features2d411",
                "-llibopencv_flann411",
                "-llibopencv_highgui411",
                "-llibopencv_imgcodecs411",
                "-llibopencv_imgproc411",
                "-llibopencv_ml411",
                "-llibopencv_objdetect411",
                "-llibopencv_photo411",
                "-llibopencv_stitching411",
                "-llibopencv_video411",
                "-llibopencv_videoio411"
            ],
            "options": {
                "cwd": "C:\\msys64\\mingw64\\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: C:/msys64/mingw64/bin/gcc.exe"
        }
    ]
}

launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "g++.exe build and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "args": [],
      "stopAtEntry": true,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "g++.exe build active file"
    }
  ]
}

c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\\opencv4\\install\\include",
                "C:\\opencv4\\install\\x64\\mingw\\lib"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:/msys64/mingw64/bin/g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64",
            "configurationProvider": "ms-vscode.cmake-tools"
        }
    ],
    "version": 4
}

What I noticed is that the definitions of the header point to this location for some reason

path being run but all my header files are in the opencv4 location. I do not know what to do about this and I have spent the last couple of hours trying to find a solution. Any help would be appreciated.

Faisal_L
  • 21
  • 1
  • 8

2 Answers2

1

For anyone having this issue, this is what I did to start using OpenCV.

I switched to using Microsoft Visual Studio instead of VS Code for building Open CV projects. You can download it from this link: https://visualstudio.microsoft.com/vs/community/

When installing, you must make sure that you select the option to install the "Visual C++ build tools"

You will also need to have CMake installed on your computer which can be downloaded from the CMake website

The Next Step is to download the source files for OpenCV. You will need to download both OpenCV and OpenCV_Contrib from their respective Github Pages. You can do this by clicking the green button at the 'top-right' of the page. Extract these folders to a convenient location and create a New Folder.

Next, you have to generate the Visual Studio Project with CMake. Launch CMake to open the GUI. at the top, there will be two text boxes, one for the source folder and another for the location where to build the binaries. The source folder is the opencv_master folder you extracted previously and the build folder is the newly created build folder. Once that's done, Click the Configure Button.

This will open another dialogue box to configure what sort of project we want to configure. In the dropdown, choose your version of Visual Studio. Once that is done, click finish and wait for the configuration to complete.

Once this step completes you will be presented with a whole bunch of configuration options. For the most part, we will be leaving these as their default values. I wouldn’t change these unless you know what you’re doing (specifically for adding new libraries).

That is, except for one option that we do need to change. In the search box at the top, type the word path. This will limit the display to just a few options. The option we want to adjust is the one called OPENCV_EXTRA_MODULES_PATH. We want to change this value to be the path to the modules directory located within the opencv_contrib-master directory we created earlier.

Once you enter this new value hit the Configure button and wait once again. This process should be much quicker this time around.

If all goes well, you should see a Configuring done message at the bottom of the log output. If it fails with any errors you’ll have to get those worked out before continuing on.

As a final step here, hit the Generate button to create the Visual Studio project that we will use to build OpenCV.

Now, this is the longest part of the process. Take a look in the build directory and after scrolling down a bit you should find a file called OpenCV.sln This is the Solution file for the Visual Studio Project. Double click it to open the project in Visual Studio.

NOTE: It may take a while for Visual Studio to fully load this project. It has a whole bunch of files to index!

Now, we have to build both the debug and release versions of the library here. To start with, ensure that your build configuration is set to debut like in the image below, then either choose Build Solution from the Build Menu or hit F6 on your keyboard.

Debug

Note: Building the library can take a bit of time.

When this debug build completes, go ahead and change the build configuration to Release (same place as in the picture) and build again.

After both of these builds are complete, change the build configuration back to Debug. Find the INSTALL entry in the solution explorer, right-click on it, and choose Build.

Once again, you will need to do this step for both the Release and Debug configurations. This build process shouldn’t take nearly as much time as the two previous ones!

enter image description here

This should create a lot of files in the build folder. The only folder that is strictly necessary is the install folder. You can copy the contents of this folder and move it to a location that is readily accessible and paste the contents.

You now have the OpenCV library.

To start creating projects, you can have a look at the video at this link: https://www.youtube.com/watch?v=p-6rG6Zgu4U

In summary, open Visual Studio and ensure that you specify the include directories, Library Directories and the Input directories for the .lib files.

Faisal_L
  • 21
  • 1
  • 8
0

Since we don't have that much information, I will just explain how include directories in CMake works.

When you do #include "opencv2/opencv.hpp", you are telling it to look in the provided include_directories() path ../include/opencv2/opencv.hpp where ../ are the previous directories. So the problem can be the directories path, improper installation of OpenCV, or because find_package() look for the packages in windows' package registry and that results in a different include path. So you can try to replace ${OpenCV_INCLUDE_DIRS} in

include_directories( ${OpenCV_INCLUDE_DIRS} )

with the full path to the folder named "include" that contains the file opencv.hpp. Note that doing it this way would likely require you to specify the library file path of the OpenCV library, which would include file name and the extension.

target_link_libraries("C:/Example/libs/example.lib")

example CMakeLists.txt file:

cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)


project("EXAMPLE" VERSION 0.1 LANGUAGES CXX)


message("CMake is running for windows version")
file(GLOB_RECURSE SRC_FILES src/*.cpp)  #the /* made it a comment lol*/

add_executable("${PROJECT_NAME}" ${SRC_FILES})

target_include_directories("${PROJECT_NAME}" PUBLIC
    "${CMAKE_SOURCE_DIR}/Dependencies/Example/include"
    "${CMAKE_SOURCE_DIR}/Dependencies/SDL2-2.0.22/include"
    "${CMAKE_SOURCE_DIR}/Dependencies/SDL2_image-2.0.5/include"
)

target_link_libraries("${PROJECT_NAME}"
    "${CMAKE_SOURCE_DIR}/Dependencies/SDL2-2.0.22/lib/x64/SDL2.lib"
    "${CMAKE_SOURCE_DIR}/Dependencies/SDL2-2.0.22/lib/x64/SDL2main.lib"
    "${CMAKE_SOURCE_DIR}/Dependencies/SDL2-2.0.22/lib/x64/SDL2test.lib"
    "${CMAKE_SOURCE_DIR}/Dependencies/SDL2_image-2.0.5/lib/x64/SDL2_image.lib"
)
  • Hi, so this is what I did: `cmake_minimum_required(VERSION 3.0.0) project(opencvTest) include(CTest) enable_testing() add_executable("${PROJECT_NAME}" main.cpp) include_directories("C:/opencv4/install/include") target_link_libraries("${PROJECT_NAME}" "C:\\opencv4\\install\\x64\\mingw\\lib" ) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack)` I am not too sure about the lib path I should put in the target_link_libraries(). when I run this though, it says target may link only to libraries. – Faisal_L Jun 30 '22 at 07:46
  • @Faisal_L target_link_libraries() need to have the full path including the filename and extension. – powerover9001 Jun 30 '22 at 08:16
  • okay, but I am not sure which folder contains the required library files. I can't find any ".lib" files, only ".dll.a" and ".a" files. These are the folders in the opencv4 folder. https://i.stack.imgur.com/3LVax.png – Faisal_L Jun 30 '22 at 09:53
  • @Faisal_L .a are static libraries which are the same as .lib, and .dll.a files are files that help link to a dll file. Both can be included in target_link_libraries(). – powerover9001 Jun 30 '22 at 22:00
  • Okay, so I should input the paths for all the library files that I need? I will try that now. – Faisal_L Jul 01 '22 at 18:04
  • https://i.stack.imgur.com/EksLr.png This is my new Cmakelists.txt. vscode still gives the can't find the opencv2/opencv.hpp error – Faisal_L Jul 01 '22 at 18:17
  • @Faisal_L Remove the find_package() and put the path directly inside include_directories() – powerover9001 Jul 01 '22 at 22:43
  • So, I just tried that and it still gives the same error. Although, there is something I just discovered: https://i.stack.imgur.com/5gYuh.png In the cmakecache.txt file, it is taking the binary directory and the source directory as the current work folder. how do I change cmakelists.txt so that it redirects to the correct paths in the opencv folder? – Faisal_L Jul 02 '22 at 01:06