Wednesday, 21 November 2012

Getting Started with QT and OpenCV 2.4.2

I recently started developing with OpenCV 2.4.2 and Qt on a Linux machine (Ubuntu 12.0.4), so I decided to write a few tutorials. Here, we are going to see how to set-up a development environment particularly Qt-creator to work with OpenCV.
First, you need to install OpenCV as this has been dealt with severally I don't bother with this. If you have not yet installed this have a look at this tutorial or just search Google for a tutorial that suits you.

Next step you would need to install Qt-creator. This can be done either via the Ubuntu Software Centre or by directly downloading the .bin installer from here.

Now we can begin, launch QT creator and then Go to File > New File or Project. Select a QT Console Application (Use a QT GUI Application if you OpenCV installation is configured to use QT and  not GTK ) give the project a name e.g. “FirstQtProject”




You could leave the other settings in the wizard as they are or change them to suit your own projects. With the default settings, two files would be created: 'FirstQtProject.pro' ( this will vary depending on the Project Name you have chosen) and 'main.cpp'. To run OpenCV programs in QT creator we need to let the IDE know where to find the OpenCV libraries.

Open the .pro file associated with the project and append the following lines at the end of the file. This should be included in every OpenCV Project you create but remember to change the include Path "/usr/local/include/opencv2" to the location of your OpenCV include directory on your PC.

#Change this to your include directory.
INCLUDEPATH += "/usr/local/include/opencv2" 
LIBS += `pkg-config --cflags --libs opencv`
If you don't have Pkg-config installed replace the last line with the following and replace “/usr/local/lib” with the location of the openCV libraries on your PC.
# Confirm the location of you opencv libraries and change appropriately.
LIBS += usr/local/lib \
-lopencv_core \
-lopencv_highgui \
-lopencv_imgproc \
-lopencv_flann \
-lopencv_legacy \
-lopencv_ml \
-lopencv_features2d \
-lopencv_calib3d
Now go to 'main.cpp' file and type in the following lines of code and press Ctrl+R to run it.
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main(void)
{
    // Load an image from the disk and store in variable.
    cv::Mat image1 = cv::imread("/home/stephen/Pictures/download.jpg");
    // Create a image display window called Figure1. 
    cv::namedWindow("Figure1");
    // Display image in Figure1.  
    cv::imshow("Figure1", image1);
    // Wait until user closes the window or presses Esc Key. 
    cv::waitKey(0);
    
    return 0;
}
The result should be an empty console window called "qtcreator_process_sub” and a window called “Figure1” containing the loaded image.

Please let me know if this was helpful and if there is tutorial you would like me to write mention it in the comments. Happy Coding!