Path: blob/master/samples/java/tutorial_code/ImgTrans/SobelDemo/SobelDemo.java
16354 views
/**1* @file SobelDemo.java2* @brief Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector3*/45import org.opencv.core.*;6import org.opencv.highgui.HighGui;7import org.opencv.imgcodecs.Imgcodecs;8import org.opencv.imgproc.Imgproc;910class SobelDemoRun {1112public void run(String[] args) {1314//! [declare_variables]15// First we declare the variables we are going to use16Mat src, src_gray = new Mat();17Mat grad = new Mat();18String window_name = "Sobel Demo - Simple Edge Detector";19int scale = 1;20int delta = 0;21int ddepth = CvType.CV_16S;22//! [declare_variables]2324//! [load]25// As usual we load our source image (src)26// Check number of arguments27if (args.length == 0){28System.out.println("Not enough parameters!");29System.out.println("Program Arguments: [image_path]");30System.exit(-1);31}3233// Load the image34src = Imgcodecs.imread(args[0]);3536// Check if image is loaded fine37if( src.empty() ) {38System.out.println("Error opening image: " + args[0]);39System.exit(-1);40}41//! [load]4243//! [reduce_noise]44// Remove noise by blurring with a Gaussian filter ( kernel size = 3 )45Imgproc.GaussianBlur( src, src, new Size(3, 3), 0, 0, Core.BORDER_DEFAULT );46//! [reduce_noise]4748//! [convert_to_gray]49// Convert the image to grayscale50Imgproc.cvtColor( src, src_gray, Imgproc.COLOR_RGB2GRAY );51//! [convert_to_gray]5253//! [sobel]54/// Generate grad_x and grad_y55Mat grad_x = new Mat(), grad_y = new Mat();56Mat abs_grad_x = new Mat(), abs_grad_y = new Mat();5758/// Gradient X59//Imgproc.Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, Core.BORDER_DEFAULT );60Imgproc.Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, Core.BORDER_DEFAULT );6162/// Gradient Y63//Imgproc.Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, Core.BORDER_DEFAULT );64Imgproc.Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, Core.BORDER_DEFAULT );65//! [sobel]6667//![convert]68// converting back to CV_8U69Core.convertScaleAbs( grad_x, abs_grad_x );70Core.convertScaleAbs( grad_y, abs_grad_y );71//![convert]7273//! [add_weighted]74/// Total Gradient (approximate)75Core.addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );76//! [add_weighted]7778//! [display]79HighGui.imshow( window_name, grad );80HighGui.waitKey(0);81//! [display]8283System.exit(0);84}85}8687public class SobelDemo {88public static void main(String[] args) {89// Load the native library.90System.loadLibrary(Core.NATIVE_LIBRARY_NAME);91new SobelDemoRun().run(args);92}93}949596