Sunday, 2 February 2020

Image thresholding with OpenCV

In the 21st century, the processing of image has become a trend. Not with the help of any photoshop tool, but for programmers they do it with the help of codes. Wonder how? Lets look into it.


A computer language Python has many libraries with different set of usage. For any work related to the visuals or images, we primarily use library OpenCV and its subordinates like numpy, Matplotlib, etc. Every library has different specific usage. We can do many process on images like Image Thresholding, Image blurring and also can change the pixel values of the same. Today apart from all this,we are going to discuss Image thresholding with OpenCV.


As we know in computer language there is either 1 or 0. Same rule applies for the images. ‘1’ resembles white light whereas ‘0’ resembles black light. In simple thresholding, it does nothing but when we set a threshold value, it applies the same threshold value for every pixel. If the value in that digital matrix hence formed is less than the threshold value , it will be set to 0 otherwise it will be set to the maximum value. The first image for this should be a gray scale image. At first we have to import libraries like OpenCV, Numpy and Matplotlib to proceed further.

We use different types of Simple thresholding like: cv.THRESH_BINARY; cv.THRESH_BINARY_INV; cv.THRESH_TRUNC; cv.THRESH_TOZERO; and cv.THRESH_TOZERO_INV. All the thresholdings serve for our different purposes. Another type of thresholding which we use is the Adaptive Threshold and Otsu’s Binarization. 


In an image, we have different pixels and different lightning conditions, hence in that case adaptive threshold helps. Its algorithm sets threshold for the small area around it and we get different threshold values for different regions.In global thresholding, we used an arbitrary chosen value as a threshold whereas in Otsu’s method avoids having to choose a value and determines it automatically.


                 Here this is an example of simple and adaptive Threshold.


So why do we do it? In computer vision, image processing and image segmentation plays a key role and for this we need to have some defined parametres. Image thresholding is one of the simplest methods to ensure that none of the pixel value is greater than the threshold.



PS: As this is my first blog, any suggestion is cordially invited.