Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/java/tutorial_code/ImgTrans/SobelDemo/SobelDemo.java
16354 views
1
/**
2
* @file SobelDemo.java
3
* @brief Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector
4
*/
5
6
import org.opencv.core.*;
7
import org.opencv.highgui.HighGui;
8
import org.opencv.imgcodecs.Imgcodecs;
9
import org.opencv.imgproc.Imgproc;
10
11
class SobelDemoRun {
12
13
public void run(String[] args) {
14
15
//! [declare_variables]
16
// First we declare the variables we are going to use
17
Mat src, src_gray = new Mat();
18
Mat grad = new Mat();
19
String window_name = "Sobel Demo - Simple Edge Detector";
20
int scale = 1;
21
int delta = 0;
22
int ddepth = CvType.CV_16S;
23
//! [declare_variables]
24
25
//! [load]
26
// As usual we load our source image (src)
27
// Check number of arguments
28
if (args.length == 0){
29
System.out.println("Not enough parameters!");
30
System.out.println("Program Arguments: [image_path]");
31
System.exit(-1);
32
}
33
34
// Load the image
35
src = Imgcodecs.imread(args[0]);
36
37
// Check if image is loaded fine
38
if( src.empty() ) {
39
System.out.println("Error opening image: " + args[0]);
40
System.exit(-1);
41
}
42
//! [load]
43
44
//! [reduce_noise]
45
// Remove noise by blurring with a Gaussian filter ( kernel size = 3 )
46
Imgproc.GaussianBlur( src, src, new Size(3, 3), 0, 0, Core.BORDER_DEFAULT );
47
//! [reduce_noise]
48
49
//! [convert_to_gray]
50
// Convert the image to grayscale
51
Imgproc.cvtColor( src, src_gray, Imgproc.COLOR_RGB2GRAY );
52
//! [convert_to_gray]
53
54
//! [sobel]
55
/// Generate grad_x and grad_y
56
Mat grad_x = new Mat(), grad_y = new Mat();
57
Mat abs_grad_x = new Mat(), abs_grad_y = new Mat();
58
59
/// Gradient X
60
//Imgproc.Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, Core.BORDER_DEFAULT );
61
Imgproc.Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, Core.BORDER_DEFAULT );
62
63
/// Gradient Y
64
//Imgproc.Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, Core.BORDER_DEFAULT );
65
Imgproc.Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, Core.BORDER_DEFAULT );
66
//! [sobel]
67
68
//![convert]
69
// converting back to CV_8U
70
Core.convertScaleAbs( grad_x, abs_grad_x );
71
Core.convertScaleAbs( grad_y, abs_grad_y );
72
//![convert]
73
74
//! [add_weighted]
75
/// Total Gradient (approximate)
76
Core.addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );
77
//! [add_weighted]
78
79
//! [display]
80
HighGui.imshow( window_name, grad );
81
HighGui.waitKey(0);
82
//! [display]
83
84
System.exit(0);
85
}
86
}
87
88
public class SobelDemo {
89
public static void main(String[] args) {
90
// Load the native library.
91
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
92
new SobelDemoRun().run(args);
93
}
94
}
95
96