../
Looking for a senior C++ dev? I'm looking for work. Hire me!

Summary

OpenCV's C++ API doesn't have to be complicated to use. This is the first in a series of articles on how to get started with OpenCV. First step is to get everything installed and to build your first OpenCV application.

Installing

Installing OpenCV on Ubuntu 18.04 is simple:

sudo apt-get install libopencv-dev

In your CMake projects, include the following:

FIND_PACKAGE ( OpenCV REQUIRED ) INCLUDE_DIRECTORIES ( ${OpenCV_INCLUDE_DIRS} )

And when you link your application, include the necessary OpenCV libraries, with the usual ${OpenCV_LIBS} which for me seems to expand to a list of about 40 libraries at /usr/lib/x86_64-linux-gnu/libopencv_*.so. See the CMakeLists.txt included in this post for a working example.

Source Code

You'll want to keep an open browser tab on the OpenCV API. For example:

The central class in OpenCV is cv::Mat. Everything revolves around the matrix cv::Mat. It is used to for source images, destination images, and various types of parameters. It is also reference counted, so copying from one cv::Mat to another is quick unless you make a deep copy with a call such as cv::Mat::clone().

For our first simple OpenCV application, this is how we open, read, and display an image file:

#include <opencv2/opencv.hpp> int main(void) { cv::Mat input_image = cv::imread("capture.jpg"); cv::namedWindow("My Image"); cv::imshow("My Image", input_image); cv::waitKey(); return 0; }

How you obtain the input image is outside the scope of OpenCV. In my case, I use the C++ library CamCap to capture images from the attached webcam.

If you ran the code above against capture.jpg, you should see something similar to this:

With this example, I'd like to rotate the image 180° so the stapler is right-side up. A 2nd cv::Mat is instantiated, and the image rotation is applied like this:

#include <opencv2/opencv.hpp> int main(void) { cv::Mat original_image; cv::Mat rotated_image; original_image = cv::imread("capture.jpg", cv::IMREAD_COLOR); cv::rotate(original_image, rotated_image, cv::ROTATE_180); cv::namedWindow("Image #1", cv::WINDOW_AUTOSIZE); cv::imshow("Image #1", original_image); cv::namedWindow("Image #2", cv::WINDOW_AUTOSIZE); cv::imshow("Image #2", rotated_image); cv::waitKey(0); return; }

Take a peek at the incredibly simple CMakeLists.txt file used to create the necessary makefile. Similar to the previous code above, this will create 2 windows that looks like this:

You now have your first OpenCV application. The next post covers some OpenCV API calls to manage colour, grayscale, and binary thresholds.

Last modified: 2018-06-06
Stéphane Charette, stephanecharette@gmail.com
../