OpenCV - Grayscale to Binary


You can use the same method mentioned in the previous chapter to convert a grayscale image to a binary image. Just pass the path for a grayscale image as input to this program.


The following program demonstrates how to read a grayscale image as a binary image and display it using JavaFX window.

import java.awt.image.BufferedImage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

public class GrayScaleToBinary extends Application {
   public void start(Stage stage) throws Exception {
      WritableImage writableImage = loadAndConvert();
      // Setting the image view
      ImageView imageView = new ImageView(writableImage);

      // Setting the position of the image
      // Setting the fit height and width of the image view

      // Setting the preserve ratio of the image view

      // Creating a Group object
      Group root = new Group(imageView);

      // Creating a scene object
      Scene scene = new Scene(root, 600, 400);

      // Setting title to the Stage
      stage.setTitle("Grayscale to binary image");

      // Adding scene to the stage

      // Displaying the contents of the stage;
   public WritableImage loadAndConvert() throws Exception {
      // Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      // Instantiating the imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

      String input = "E:/OpenCV/chap7/grayscale.jpg";

      // Reading the image
      Mat src = imageCodecs.imread(input);

      // Creating the destination matrix
      Mat dst = new Mat();

      // Converting to binary image...
      Imgproc.threshold(src, dst, 200, 500, Imgproc.THRESH_BINARY);

      // Extracting data from the transformed image (dst)
      byte[] data1 = new byte[dst.rows() * dst.cols() * (int)(dst.elemSize())];
      dst.get(0, 0, data1);

      // Creating Buffered image using the data
      BufferedImage bufImage = new BufferedImage(dst.cols(),dst.rows(), 

      // Setting the data elements to the image
      bufImage.getRaster().setDataElements(0, 0, dst.cols(), dst.rows(), data1);

      // Creating a Writable image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      System.out.println("Converted to binary");
      return writableImage;
   public static void main(String args[]) throws Exception {

Input Image

Assume that following is the input image sample.jpg specified in the above program.

Sample Image

Output Image

On executing the program, you will get the following output.

GrayScale to Binary