Java example demonstrating Sobel edge detection in OpenCV.


The Sobel operator for edge detections allows you to find the edges in a given image in both horizontal and vertical directions.

The Sobel() method of the Imgproc class applies the Sobel Edge Detection algorithm on the given image. This method accepts −

  • Two Mat objects representing the source and destination images.

  • An integer variable representing the depth of an image.

  • Two double variables to hold the x and y derivatives.

Example

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class SobelEdgeDetection {
   public static void main(String args[]) {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      String file ="D:\Images\win2.jpg";
      Mat src = Imgcodecs.imread(file);
      //Creating an empty matrix for the destination image
      Mat dst = new Mat();
      //Applying sobel derivative with values x:0 y:1
      Imgproc.Sobel(src, dst, -1, 0, 1);
      HighGui.imshow("Sobel - x:0 & y:1 ", dst);
      HighGui.waitKey();
      //Applying sobel derivative with values x:1 y:0
      Imgproc.Sobel(src, dst, -1, 1, 0);
      HighGui.imshow("Sobel - x:1 & y:0 ", dst);
      HighGui.waitKey();
      //Applying sobel derivative with values x:1 y:1
      Imgproc.Sobel(src, dst, -1, 1, 1);
      HighGui.imshow("Sobel - x:1 & y:1 ", dst);
      HighGui.waitKey();
   }
}

Output

On executing, the above program generates the following windows −

Sobel - x:0 & y:1 − 

Sobel - x:1 & y:0 − 

Sobel - x:1 & y:1 − 

Updated on: 13-Apr-2020

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements