OpenCV
4.0.1
Open Source Computer Vision
|
Prev Tutorial: Image Pyramids
Next Tutorial: Thresholding Operations using inRange
In this tutorial you will learn how to:
Once we have separated properly the important pixels, we can set them with a determined value to identify them (i.e. we can assign them a value of \(0\) (black), \(255\) (white) or any value that suits your needs).
To illustrate how these thresholding processes work, let's consider that we have a source image with pixels with intensity values \(src(x,y)\). The plot below depicts this. The horizontal blue line represents the threshold \(thresh\) (fixed).
This thresholding operation can be expressed as:
\[\texttt{dst} (x,y) = \fork{\texttt{maxVal}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\]
So, if the intensity of the pixel \(src(x,y)\) is higher than \(thresh\), then the new pixel intensity is set to a \(MaxVal\). Otherwise, the pixels are set to \(0\).
This thresholding operation can be expressed as:
\[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxVal}}{otherwise}\]
If the intensity of the pixel \(src(x,y)\) is higher than \(thresh\), then the new pixel intensity is set to a \(0\). Otherwise, it is set to \(MaxVal\).
This thresholding operation can be expressed as:
\[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\]
The maximum intensity value for the pixels is \(thresh\), if \(src(x,y)\) is greater, then its value is truncated. See figure below:
This operation can be expressed as:
\[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\]
If \(src(x,y)\) is lower than \(thresh\), the new pixel value will be set to \(0\).
This operation can be expressed as:
\[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\]
If \(src(x,y)\) is greater than \(thresh\), the new pixel value will be set to \(0\).
Let's check the general structure of the program:
As you can see, the function cv::threshold is invoked. We give \(5\) parameters in C++ code:
After compiling this program, run it giving a path to an image as argument. For instance, for an input image as:
First, we try to threshold our image with a binary threshold inverted. We expect that the pixels brighter than the \(thresh\) will turn dark, which is what actually happens, as we can see in the snapshot below (notice from the original image, that the doggie's tongue and eyes are particularly bright in comparison with the image, this is reflected in the output image).
Now we try with the threshold to zero. With this, we expect that the darkest pixels (below the threshold) will become completely black, whereas the pixels with value greater than the threshold will keep its original value. This is verified by the following snapshot of the output image: