OpenCV: Build a simple OpenCV program using CMake in Ubuntu


Building on our progress with usage of OpenCV, a demo on how to build and run a C++ based OpenCV program is described below.

To understand whats happing under the hood we shall dig up some basics -
g++ is GNU compiler for C++. Capable of generating both program object files and Executables
Make is a Build Tool that generates executables also by invoking g++
CMake , I would prefer to call it as Build Environment Tool that manages and assists the Build Process

CMake is a tool that takes care of managing what are the key requisites for the source to be compiled. More often than not, the source are dependent on other sources that have their own stipulations and methods to build them.  Usually the build requirements of these components are mentioned in their respective 'CMakeLists'. Thus combining the 'CMakeLists' of the program and dependent sources,  CMake makes it easier to manage and mitigate the task of providing and maintaining these component specific build requirements. This way the programmer can focus more on the necessities of the program rather than the needs of its dependent components. Further more, a well written CMake file makes the sources portable for building across platforms.

Quick Bullets:
Author --> Creates a program and CMakeList.txt
CMake and CMakeList.txt --> Generates Build Parameters [Makefile] for Build tools
Make and Makefile --> Generates Compiler Parameters and Invokes g++
g++ and Compiler Options --> Generates Object files and Executables

A simple diagram  might provide more clarity. See below -



Let us call our sample program as 'display_code.cpp' and the executable as 'display'

Create simple OpenCV program named 'display_code.cpp' [Note: Using legacy OpenCV 1.0 API]
#include <cv.h>
#include <highgui.h>

int main(int argc, char** argv )
{
 IplImage* img = cvLoadImage("nexus.jpg");
 cvNamedWindow("Image",CV_WINDOW_AUTOSIZE);
 cvShowImage( "Image",img);
 int key = cvWaitKey(0);

 cvDestroyWindow( "Image" );
 cvReleaseImage(&img);
}

Create 'CMakeLists.txt'
cmake_minimum_required(VERSION 2.8)
project( display )
find_package( OpenCV REQUIRED )
add_executable( display display_code.cpp )
target_link_libraries( display ${OpenCV_LIBS} )

Build the application
cmake .

make

Run the application
./display

OR
Using g++ directly
g++ display_code.cpp -o display `pkg-config --cflags --libs opencv`
./display

Result:


Files:
Download from DsynFLO box folder - https://app.box.com/s/yn3lwcmx1sv4slz0wfru

Further Reading:
GCC and Make : http://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html
Writing Makefiles : https://www.cs.bu.edu/teaching/cpp/writing-makefiles/
Follow the informative answer explaining  'CMake' and 'Make' here - http://stackoverflow.com/a/19266355

No comments:

Post a Comment