linux_gcc_cmake.markdown 2.1 KB
Newer Older
1 2 3
Using OpenCV with gcc and CMake {#tutorial_linux_gcc_cmake}
===============================

4 5 6 7
@prev_tutorial{tutorial_linux_install}
@next_tutorial{tutorial_linux_eclipse}


M
Maksim Shabunin 已提交
8
@note We assume that you have successfully installed OpenCV in your workstation.
9 10 11

-   The easiest way of using OpenCV in your code is to use [CMake](http://www.cmake.org/). A few
    advantages (taken from the Wiki):
M
Maksim Shabunin 已提交
12 13
    -#  No need to change anything when porting between Linux and Windows
    -#  Can easily be combined with other tools by CMake( i.e. Qt, ITK and VTK )
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
-   If you are not familiar with CMake, checkout the
    [tutorial](http://www.cmake.org/cmake/help/cmake_tutorial.html) on its website.

Steps
-----

### Create a program using OpenCV

Let's use a simple program such as DisplayImage.cpp shown below.
@code{.cpp}
#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], 1 );

    if ( !image.data )
    {
        printf("No image data \n");
        return -1;
    }
    namedWindow("Display Image", WINDOW_AUTOSIZE );
    imshow("Display Image", image);

    waitKey(0);

    return 0;
}
@endcode
### Create a CMake file

Now you have to create your CMakeLists.txt file. It should look like this:
@code{.cmake}
cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
M
Maksim Shabunin 已提交
60
include_directories( ${OpenCV_INCLUDE_DIRS} )
61
add_executable( DisplayImage DisplayImage.cpp )
M
Maksim Shabunin 已提交
62
target_link_libraries( DisplayImage ${OpenCV_LIBS} )
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
@endcode
### Generate the executable

This part is easy, just proceed as with any other project using CMake:
@code{.bash}
cd <DisplayImage_directory>
cmake .
make
@endcode
### Result

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.:
@code{.bash}
./DisplayImage lena.jpg
@endcode
You should get a nice window as the one shown below:

M
Maksim Shabunin 已提交
81
![](images/GCC_CMake_Example_Tutorial.jpg)