Thursday, September 12, 2013

Using Opencv with CMAKE

How to code OpenCV program using CMake.

Why CMake? - Because there is no need to change anything while porting between windows and linux.
Let us take an example where we need to write Opencv code for viewing an Image on screen.

Steps:-
   1. Create a file ShowImage.cpp.
   2. Create CMakeLists.txt
   3. Save both files (ShowImage.cpp, CMakeLists.txt) into  same folder named Show(say).
   4. Change your directory to  /Show.
   5. Create Executables.
   6. Run Executable.

Download the code from here

Step 1.    ShowImage.cpp
#include <stdio.h> 
#include <opencv2/opencv.hpp> 
using namespace cv; 
int main( int argc, char** argv ) 
{  
   Mat image; 
   image = imread( argv[1], 1 ); 
   if( argc != 2 || !image.data )  
   { 
     printf( "Image data not found \n" ); 
     return -1; 
   } 
  namedWindow( "Show Image", CV_WINDOW_AUTOSIZE ); 
  imshow( "Show Image", image ); 
  waitKey(0); 
  return 0; 
}
Step 2. CMakeLists.txt For More info about CMake check this Tutorial
cmake_minimum_required(VERSION 2.8) 
project( ShowImage )  
find_package( OpenCV REQUIRED ) 
add_executable( ShowImage ShowImage.cpp )  
target_link_libraries( ShowImage ${OpenCV_LIBS} )

Step 3. Save both files and image into folder "Show" .

Step 4. Change directory to Show
cd <Show_Directory>
Step 5. cmake <Show_Directory> make
Step 6. ./ShowImage loki.jpeg

OUTPUT:

 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hope you enjoy this post. Don't Forget to share this post.