O'Reilly logo

Learn OpenCV 4 by Building Projects - Second Edition by Prateek Joshi, Vinicius G. Mendonca, David Millan Escriva

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Thresholding the image

We usually start preprocessing by thresholding the image. This eliminates all color information. Most OpenCV functions consider information to be written in white, and the background to be black. So, let's start by creating a threshold function to match this criteria:

#include opencv2/opencv.hpp; #include vector; using namespace std; using namespace cv; Mat binarize(Mat input) { //Uses otsu to threshold the input image Mat binaryImage; cvtColor(input, input, COLOR_BGR2GRAY); threshold(input, binaryImage, 0, 255, THRESH_OTSU); //Count the number of black and white pixels int white = countNonZero(binaryImage); int black = binaryImage.size().area() - white; //If the image is mostly white (white background), invert it return ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required