Prev Tutorial: Using OpenCV with gdb-powered IDEs
Next Tutorial: Using OpenCV with Eclipse (plugin CDT)
| |
Original author | Ana Huamán |
Compatibility | OpenCV >= 3.0 |
- Warning
- This tutorial can contain obsolete information.
- Note
- We assume that you have successfully installed OpenCV in your workstation.
- The easiest way of using OpenCV in your code is to use CMake. A few advantages (taken from the Wiki):
- 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 )
- If you are not familiar with CMake, checkout the tutorial on its website.
Steps
Create a program using OpenCV
Let's use a simple program such as DisplayImage.cpp shown below.
#include <stdio.h>
#include <opencv2/opencv.hpp>
int main(
int argc,
char** argv )
{
if ( argc != 2 )
{
printf("usage: DisplayImage.out <Image_Path>\n");
return -1;
}
Mat image;
if ( !image.data )
{
printf("No image data \n");
return -1;
}
imshow(
"Display Image", image);
return 0;
}
@ WINDOW_AUTOSIZE
the user cannot resize the window, the size is constrainted by the image displayed.
Definition: highgui.hpp:144
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
@ IMREAD_COLOR
Same as IMREAD_COLOR_BGR.
Definition: imgcodecs.hpp:72
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
int main(int argc, char *argv[])
Definition: highgui_qt.cpp:3
Definition: core/include/opencv2/core.hpp:107
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 .
make
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.:
You should get a nice window as the one shown below: