How to run a simple OpenCV code in C++ on linux?


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);
    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?


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
git clone

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 .

10- run executable file:


Answered By – Sajjad Aemmi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published