OpenCV  3.4.20-dev
Open Source Computer Vision
Using OpenCV with gcc and CMake

Prev Tutorial: Installation in Linux

Next Tutorial: Using OpenCV with Eclipse (plugin CDT)

We assume that you have successfully installed OpenCV in your workstation.


Create a program using OpenCV

Let's use a simple program such as DisplayImage.cpp shown below.

#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
if ( argc != 2 )
printf("usage: DisplayImage.out <Image_Path>\n");
return -1;
Mat image;
image = imread( argv[1], IMREAD_COLOR );
if ( ! )
printf("No image data \n");
return -1;
namedWindow("Display Image", WINDOW_AUTOSIZE );
imshow("Display Image", image);
return 0;

Create a CMake file

Now you have to create your CMakeLists.txt file. It should look like this:

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} )

Generate the executable

This part is easy, just proceed as with any other project using CMake:

cd <DisplayImage_directory>
cmake .


By now you should have an executable (called DisplayImage in this case). You just have to run it giving an image location as an argument, i.e.:

./DisplayImage lena.jpg

You should get a nice window as the one shown below: