Introduction
Previously we saw how to build and install the OpenCV libraries and header files. If you haven’t built and installed them, my suggestion is to do so. In this tutorial we will use them and the examples assume they are available. We will write our first Hello World program with OpenCV. It is pretty simple – it will just load and display one image. Later we will be doing more complex things with OpenCV.
I am hosting this project as well as the upcoming ones in GitHub. You can get it from there. I will also add it as an archive in the post so you can download it from here as well.
The source code of the Hello World application
Following is the source code of the Hello World application and explanation about it.
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; int main(int argc, char** argv ) { Mat image; image = imread( "../op.jpg", IMREAD_COLOR ); if ( !image.data ) { std::cout << "No image data \n"; return -1; } namedWindow("Display Image", WINDOW_AUTOSIZE ); imshow("Display Image", image); waitKey(0); return 0; }
Lines [1-4]
In the first line we include the opencv.hpp header file. It will include other header files, which we need to use in our application. Next, we include the iostream library in order to use the std::cout functionality. Lastly, we set to use the namespace cv in order to access the OpenCV methods and classes without the need to append that namespace.
Lines [6-15]
First, we define the main method. Then we create one object of Mat type. This object will store the image pixels information. Next, using the imread method we read the image and store it in the Mat object. We provide this method with the path to the image file. Here you can find more information regarding the supported image formats. You can provide a path to another image. I am using one, which is part of the project I have prepared and hosted in GitHub.
The second parameter is a flag, giving hint to the OpenCV library on how to open the image. In my case it will convert it to a BGR color image. More information about the flag is available here.
The imread method will return null if it is not able to read the image for some reason – the file is corrupted, not found or we don’t have access to it. This is why the next statements are to check whether we have read the image correctly and if not, we will print an error message.
Lines[17-21]
After we have read the image, now it is time to display it. The method namedWindow creates a window with the name, we provide as an argument. It will be used to display the image. The second argument again provides some additional flags. In our case, the flag states that the window will resize to the resolution of the image. Here is more information about the available flags.
Next, we have the method imshow. The application use it to display the image, we stored in the image object. This function will display it in the window with the name we provide. In our case this is the window we created previously.
Lastly, we have the waitKey method which will wait there until the user presses a key. The argument 0 means that the program will wait forever until a key is pressed. The last line is the return of the main method.
As you can see, the program is not that complex. It is self-explanatory. Next, let’s see the other files needed to build and run the application.
The CMake files for the Hello World example
In order to build the application, I will use CMake to generate a project and then build it. For this goal I have prepared two CMake files. One is the main CMake file which will start the generation and the second one will be included in it. The second file will contain operations, specific for OpenCV. The name of the main file shall be CMakeLists.txt.
The main CMake file
Here is how my main CMake file looks like.
cmake_minimum_required(VERSION 3.0) project( HelloOpenCV ) set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/HelloOpenCV.cpp) add_executable( ${PROJECT_NAME} ${SOURCE_FILES} ) include(${CMAKE_CURRENT_SOURCE_DIR}/../Cmake/OpenCVCMake.cmake)
Firstly, I am setting the minimum required version of CMake. I am setting 3.0, but you can set something else. We don’t have any specific commands that will depend on a specific version so it is OK to use this lower version as a minimum one.
Second, I am creating the project. It will be named HelloOpenCV. Nothing specific here.
Next I am creating one variable which will hold the source files. The ${CMAKE_CURRENT_SOURCE_DIR} variable gives the path to the main CMake file. From there I am accessing the source file.
On line 7 I am defining the project to be an executable. ${PROJECT_NAME} holds the name of the project we set previously. ${SOURCE_FILES} contains the list of source files to be compiled.
Lastly, I include the second CMake file, which contains OpenCV specific operations. If you are keeping it in another folder, change the path respectively.
The OpenCV specific CMake file
Here is the second CMake file, which contains some logic, specific for the OpenCV part of the application. It holds also some OS specific logic. I have separated it from the main file in order to reuse it for the other projects. Here it is:
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux") set(OPENCV_INCLUDE_DIRS /usr/local/include/opencv4) set(OPENCV_LIBRARY_DIRS /usr/local/lib) set(OPENCV_LIBRARIES ${OPENCV_LIBRARY_DIRS}/libopencv_calib3d.so ${OPENCV_LIBRARY_DIRS}/libopencv_core.so ${OPENCV_LIBRARY_DIRS}/libopencv_dnn.so ${OPENCV_LIBRARY_DIRS}/libopencv_features2d.so ${OPENCV_LIBRARY_DIRS}/libopencv_flann.so ${OPENCV_LIBRARY_DIRS}/libopencv_gapi.so ${OPENCV_LIBRARY_DIRS}/libopencv_highgui.so ${OPENCV_LIBRARY_DIRS}/libopencv_imgcodecs.so ${OPENCV_LIBRARY_DIRS}/libopencv_imgproc.so ${OPENCV_LIBRARY_DIRS}/libopencv_ml.so ${OPENCV_LIBRARY_DIRS}/libopencv_objdetect.so ${OPENCV_LIBRARY_DIRS}/libopencv_photo.so ${OPENCV_LIBRARY_DIRS}/libopencv_stitching.so ${OPENCV_LIBRARY_DIRS}/libopencv_video.so ${OPENCV_LIBRARY_DIRS}/libopencv_videoio.so) elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") set(OPENCV_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../../opencv_build/install/include) set(OPENCV_LIBRARY_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../../opencv_build/install/x64/vc16/lib) set(OPENCV_LIBRARIES ${OPENCV_LIBRARY_DIRS}/opencv_calib3d450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_core450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_dnn450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_features2d450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_flann450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_gapi450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_highgui450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_imgcodecs450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_imgproc450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_ml450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_objdetect450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_photo450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_stitching450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_video450d.lib ${OPENCV_LIBRARY_DIRS}/opencv_videoio450d.lib) endif() target_include_directories(${PROJECT_NAME} PUBLIC ${OPENCV_INCLUDE_DIRS} ) target_link_libraries( ${PROJECT_NAME} ${OPENCV_LIBRARIES})
Lines [1-20]
This part is specific for the Linux build. Firstly, I do a check whether the operating system I am building for is Linux. If that is true I store the path to the folder, which contains all the OpenCV header files. In the previous post I installed the header files and the libraries. They are installed in the given folder. That is how I am going to access them. In line 4 I do the same for the OpenCV libraries. Lastly, I am storing all the OpenCV libraries into another variable to use later. Notice how I am adding the full path to each library. This is a recommended approach.
Lines [22-41]
This part is taken into consideration when we are building for Windows. It does the same as in the Linux part – sets variables, containing the header files and libraries locations. Again, here you need to set your own paths, where you keep the libraries and header files. Keep in mind that I am using those paths, where I installed OpenCV previously.
Lines [45-47]
Finally we set the include directories so the CMake generator will know where to search for. We do the same for the libraries on the last line.
Pretty much this is all we need in order to generate a project and build it. Next, let’s see how to run CMake and build the project.
Building the Hello World project
Now, all that we left with is to generate the project and build it. For this purpose I have created one shell file for Linux and one batch file for Windows. Here they are.
The shell file
#!/bin/sh rm -rf ../build mkdir ../build cmake -G "Eclipse CDT4 - Unix Makefiles" -S . -B ../build cd ../build make
Firstly, it removes the build folder if exists and creates it anew. Then it calls CMake. We provide the -G “Eclipse CDT4 – Unix Makefiles” argument in order to tell CMake to generate a project for Eclipse. -S is the folder, where the main CMake file is found. -B is the folder, where the build should be placed.
When done with the generation, we move to the build directory and call make. This will start the building of the generated project. If everything with the build is fine, it will build one executable.
The batch file for Windows
rmdir /s/q ..\build mkdir ..\build cmake -G "Visual Studio 16 2019" -S . -B ..\build cd ../build SET MSBUILD=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe IF NOT EXIST "%MSBUILD%" GOTO NOMSB "%MSBUILD%" HelloOpenCV.sln /t:rebuild /p:configuration=Debug /m GOTO :EOF :NOMSB echo. echo MSBUILD not found echo. GOTO :EOF
Again here we delete and recreate the build folder. Then we call CMake in order to generate the project. On my side it will generate a Visual Studio project, because I have set this: “-G “Visual Studio 16 2019″”. If you are using different tool, change it here respectively. When the generation is done we switch to the build folder and build the project using MSBuild.exe. Keep in mind that on your side the path to MSBuild.exe might be different so set it accordingly. If you are not using Visual Studio, then use the respective tool to build your project.
We have some checks whether the tool exists and we can print some error messages. Once the build is over, you will have an application to be run.
Running the application
On Linux you can go ahead and run the Hello World application without any issues. Just make sure to have the correct image in the correct folder as it is used in the source code.
On Windows you will need the OpenCV .dll libraries. They are usually found in the install\x64\vc16\bin or something similar. There are three approaches to provide them. Firstly you can copy them in the same folder as the application. This is fast but not so convenient, because it will mean for every application to copy them. Second approach is to copy them in Windows/System32 folder (or the respective folder for 64bit versions of Windows). I prefer the third approach – to add the path to the OpenCV .dll files in the Path environment variable. Thus, I will not pollute the Windows folders with additional libraries and I will be able to use them with every application.
Once you have done all this you can run the application. The result is one window, which displays the image. On my side it looks like this:

Conclusion
In this tutorial we wrote our first application, which uses OpenCV. We wrote some CMake files in order to generate the project. Finally we wrote some shell/batch files in order to execute the generation and build process.
Next we will start looking at the OpenCV libraries and their functionality. Firstly we will see how to read, display and write images. Then we will continue with the other functionalities
You can find the project so far attached below. It is also available in GitHub.

Passionate developer, loving husband and caring father. As an introvert programming is my life. I work as a senior software engineer in a big international company. My hobbies include playing computer games (mostly World of Warcraft), watching TV series and hiking.