Basic Thresholding Tutorial

Advertisements


In this chapter we are going to perform some basic thresholding operations on images.

We are going to use OpenCV function threshold. It can be found under Imgproc package. Its syntax is given below:

Imgproc.threshold(source, destination, thresh , maxval , type);

The parameters along with their description are listed below:

Sr.NoParameters & description
1source
The Source image.
2destination
The destination image.
3thresh
Threshold value.
4maxval
maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.
5type
The possible types are THRESH_BINARY,THRESH_BINARY_INV,THRESH_TRUNC,THRESH_TOZERO.

Apart from the threshold method, there are other methods provide by the Imgproc class. They are listed below:

Sr.NoMethod & Description
1cvtColor(Mat src, Mat dst, int code, int dstCn)
Converts an image from one colour space to another.
2dilate(Mat src, Mat dst, Mat kernel)
Dilates an image by using a specific structuring element.
3equalizeHist(Mat src, Mat dst)
Equalizes the histogram of a grayscale image.
4filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
Convolves an image with the kernel.
5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)
Blurs an image using a Gaussian filter.
6integral(Mat src, Mat sum)
Calculates the integral of an image.

Example

The following example demonstrates the use of Imgproc class to perform thresholding operations to an image.

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class main {
   public static void main( String[] args )
   {
      try{

         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         Mat source = Highgui.imread("digital_image_processing.jpg", 
         Highgui.CV_LOAD_IMAGE_COLOR);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());

         destination = source;
         Imgproc.threshold(source,destination,127,255,Imgproc.THRESH_TOZERO);
         Highgui.imwrite("ThreshZero.jpg", destination);
         }catch (Exception e) {
            System.out.println("error: " + e.getMessage());
         }
   }
}

Output

Original Image

Basic Thresholding Tutorial

On the above original image, some thresholding operations has been performed which have been shown in the output below:

Thresh Binary

Basic Thresholding Tutorial

Thresh Binary Invert

Basic Thresholding Tutorial

Thresh Zero

Basic Thresholding Tutorial

Advertisements
Advertisements