1

I wrote a simple OpenCV code using C++ and run it in linux:

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
int main()
{
    cv::Mat image;
    image = cv::imread("sajjad.jpg", 1);
 
    cv::namedWindow("Display Image", cv::WINDOW_AUTOSIZE);
    cv::imshow("Display Image", image);
    cv::waitKey(0);
    return 0;
}

I get this error:

opencv_test.cpp:2:10: fatal error: opencv2/opencv.hpp: No such file or directory
 #include <opencv2/opencv.hpp>
          ^~~~~~~~~~~~~~~~~~~~
compilation terminated.

how to install OpenCV for c++ in linux?

2
  • you building it in wrong way. How do you do that? This should work: g++ opencv_test.cpp $(pkg-config --cflags opencv)
    – Marek R
    Jan 15, 2021 at 15:07
  • @MarekR zsh: command not found: pkg-config cv_test.cpp:3:10: fatal error: 'opencv2/opencv.hpp' file not found Jan 17, 2021 at 19:15

1 Answer 1

6

1- Install dependencies:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install libgtk2.0-dev pkg-config

2- To compile OpenCV you will need a C++ compiler. Usually it is G++/GCC or Clang/LLVM. also OpenCV uses CMake build configuration tool:

sudo apt install -y g++
sudo apt-get install cmake make

3- Clone repository using git:

git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git

4- Create build directory:

mkdir -p build && cd build

5- Configure - generate build scripts for the preferred build system:

cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ../opencv

6- Build - run actual compilation process. 4 is number of used processor cores. this part may takes some minutes.

make -j4

7- Installation process copies files to predefined locations and do minor patching:

sudo make install

7.1- You can remove opencv if you want:

sudo make uninstall

8- Create a CMake file. the name of the source code is DisplayImage.cpp for example:

cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )

9- Generate the executable. This part is easy, just proceed as with any other project using CMake:

cd <DisplayImage_directory>
cmake .
make

10- run executable file:

./DisplayImage
2
  • 3
    Why all the downvotes? Why is this a bad answer?
    – Stefan
    Jul 19, 2021 at 9:32
  • what global var OpenCV_INCLUDE_DIRS mean and do I need to configure myself?
    – Guy Sadoun
    Feb 9, 2022 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.