OpenCV – Using Camera In this chapter, we will learn how to use OpenCV to capture frames using the system camera. The VideoCapture class of the org.opencv.videoio package contains classes and methods to capture video using the camera. Let’s go step by step and learn how to capture frames − Step 1: Load the OpenCV native library While writing Java code using OpenCV library, the first step you need to do is to load the native library of OpenCV using the loadLibrary(). Load the OpenCV native library as shown below. // Loading the core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Step 2: Instantiate the video capture class Instantiate the Mat class using any of the functions mentioned in this tutorial earlier. // Instantiating the VideoCapture class (camera:: 0) VideoCapture capture = new VideoCapture(0); Step 3: Read the frames You can read the frames from the camera using the read() method of the VideoCapture class. This method accepts an object of the class Mat to store the frame read. // Reading the next video frame from the camera Mat matrix = new Mat(); capture.read(matrix); Example The following program demonstrates how to capture a frame using camera and display it using JavaFX window. It also saves the captured frame. import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.FileNotFoundException; import java.io.IOException; 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; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.videoio.VideoCapture; public class CameraSnapshotJavaFX extends Application { Mat matrix = null; @Override public void start(Stage stage) throws FileNotFoundException, IOException { // Capturing the snapshot from the camera CameraSnapshotJavaFX obj = new CameraSnapshotJavaFX(); WritableImage writableImage = obj.capureSnapShot(); // Saving the image obj.saveImage(); // Setting the image view ImageView imageView = new ImageView(writableImage); // setting the fit height and width of the image view imageView.setFitHeight(400); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // 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(“Capturing an image”); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage capureSnapShot() { WritableImage WritableImage = null; // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Instantiating the VideoCapture class (camera:: 0) VideoCapture capture = new VideoCapture(0); // Reading the next video frame from the camera Mat matrix = new Mat(); capture.read(matrix); // If camera is opened if( capture.isOpened()) { // If there is next video frame if (capture.read(matrix)) { // Creating BuffredImage from the matrix BufferedImage image = new BufferedImage(matrix.width(), matrix.height(), BufferedImage.TYPE_3BYTE_BGR); WritableRaster raster = image.getRaster(); DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); byte[] data = dataBuffer.getData(); matrix.get(0, 0, data); this.matrix = matrix; // Creating the Writable Image WritableImage = SwingFXUtils.toFXImage(image, null); } } return WritableImage; } public void saveImage() { // Saving the Image String file = “E:/OpenCV/chap22/sanpshot.jpg”; // Instantiating the imgcodecs class Imgcodecs imageCodecs = new Imgcodecs(); // Saving it again imageCodecs.imwrite(file, matrix); } public static void main(String args[]) { launch(args); } } Output On executing the program, you will get the following output. If you open the specified path, you can observe the same frame which is saved as a jpg file. Learning working make money
Category: opencv
OpenCV – Hough Line Transform You can detect the shape of a given image by applying the Hough Transform technique using the method HoughLines() of the Imgproc class. Following is the syntax of this method. HoughLines(image, lines, rho, theta, threshold) This method accepts the following parameters − image − An object of the class Mat representing the source (input) image. lines − An object of the class Mat that stores the vector that stores the parameters (r, Φ) of the lines. rho − A variable of the type double representing the resolution of the parameter r in pixels. theta − A variable of the type double representing the resolution of the parameter Φ in radians. threshold − A variable of the type integer representing the minimum number of intersections to “detect” a line. Example The following program demonstrates how to detect Hough lines in a given image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class HoughlinesTest { public static void main(String args[]) throws Exception { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file = “E:/OpenCV/chap21/hough_input.jpg”; // Reading the image Mat src = Imgcodecs.imread(file,0); // Detecting edges of it Mat canny = new Mat(); Imgproc.Canny(src, canny, 50, 200, 3, false); // Changing the color of the canny Mat cannyColor = new Mat(); Imgproc.cvtColor(canny, cannyColor, Imgproc.COLOR_GRAY2BGR); // Detecting the hough lines from (canny) Mat lines = new Mat(); Imgproc.HoughLines(canny, lines, 1, Math.PI/180, 100); System.out.println(lines.rows()); System.out.println(lines.cols()); // Drawing lines on the image double[] data; double rho, theta; Point pt1 = new Point(); Point pt2 = new Point(); double a, b; double x0, y0; for (int i = 0; i < lines.cols(); i++) { data = lines.get(0, i); rho = data[0]; theta = data[1]; a = Math.cos(theta); b = Math.sin(theta); x0 = a*rho; y0 = b*rho; pt1.x = Math.round(x0 + 1000*(-b)); pt1.y = Math.round(y0 + 1000*(a)); pt2.x = Math.round(x0 – 1000*(-b)); pt2.y = Math.round(y0 – 1000 *(a)); Imgproc.line(cannyColor, pt1, pt2, new Scalar(0, 0, 255), 6); } // Writing the image Imgcodecs.imwrite(“E:/OpenCV/chap21/hough_output.jpg”, cannyColor); System.out.println(“Image Processed”); } } Assume that following is the input image hough_input.jpg specified in the above program. Output On executing the program, you will get the following output − 143 1 Image Processed If you open the specified path, you can observe the output image as follows − Learning working make money
OpenCV – Simple Threshold Thresholding is a method of image segmentation, in general it is used to create binary images. Thresholding is of two types namely, simple thresholding and adaptive thresholding. Simple Thresholding In simple thresholding operation the pixels whose values are greater than the specified threshold value, are assigned with a standard value. You can perform simple threshold operation on an image using the method threshold() of the Imgproc class, Following is the syntax of this method. threshold(src, dst, thresh, maxval, type) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. thresh − A variable of double type representing the threshold value. maxval − A variable of double type representing the value that is to be given if pixel value is more than the threshold value. type − A variable of integer type representing the type of threshold to be used. Example The following program demonstrates how to perform simple thresholding operation on an image in OpenCV. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class Thresh { public static void main(String args[]) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file =”E:/OpenCV/chap14/thresh_input.jpg”; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY); // Writing the image Imgcodecs.imwrite(“E:/OpenCV/chap14/thresh_trunc.jpg”, dst); System.out.println(“Image Processed”); } } Assume that following is the input image thresh_input.jpg specified in the above program. Output On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − Other types of simple thresholding In addition to the THRESH_BINARY operation demonstrated in the previous example, OpenCV caters various other types of threshold operations. All these types are represented by predefined static fields (fixed values) of Imgproc class. You can choose the type of the threshold operation you need, by passing its respective predefined value to the parameter named type of the threshold() method. Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY); Following are the values representing various types of threshold operations and their respective outputs. Operation and Description Output THRESH_BINARY THRESH_BINARY_INV THRESH_TRUNC THRESH_TOZERO THRESH_TOZERO_INV Learning working make money
OpenCV – Environment In this chapter, you will learn how to install OpenCV and set up its environment in your system. Installing OpenCV First of all, you need to download OpenCV onto your system. Follow the steps given below. Step 1 − Open the homepage of OpenCV by clicking the following link: On clicking, you will see its homepage as shown below. Step 2 − Now, click the Downloads link highlighted in the above screenshot. On clicking, you will be directed to the downloads page of OpenCV. Step 3 − On clicking the highlighted link in the above screenshot, a file named opencv-3.1.0.exe will be downloaded. Extract this file to generate a folder opencv in your system, as shown in the following screenshot. Step 4 − Open the folder OpenCV → build → java. Here you will find the jar file of OpenCV named opencv-310.jar. Save this file in a separate folder for further use. Eclipse Installation After downloading the required JAR files, you have to embed these JAR files to your Eclipse environment. You can do this by setting the Build Path to these JAR files and by using pom.xml. Setting Build Path Following are the steps to set up OpenCV in Eclipse − Step 1 − Ensure that you have installed Eclipse in your system. If not, download and install Eclipse in your system. Step 2 − Open Eclipse, click on File, New, and Open a new project as shown in the following screenshot. Step 3 − On selecting the project, you will get the New Project wizard. In this wizard, select Java project and proceed by clicking the Next button, as shown in the following screenshot. Step 4 − On proceeding forward, you will be directed to the New Java Project wizard. Create a new project and click Next, as shown in the following screenshot. Step 5 − After creating a new project, right-click on it. Select Build Path and click Configure Build Path… as shown in the following screenshot. Step 6 − On clicking the Build Path option, you will be directed to the Java Build Path wizard. Click the Add External JARs button, as shown in the following screenshot. Step 7 − Select the path where you have saved the file opencv-310.jar. Step 8 − On clicking the Open button in the above screenshot, those files will be added to your library. Step 9 − On clicking OK, you will successfully add the required JAR files to the current project and you can verify these added libraries by expanding the Referenced Libraries. Setting the Path for Native Libraries In addition to the JAR files, you need to set path for the native libraries (DLL files) of OpenCV. Location of DLL files − Open the installation folder of OpenCV and go to the sub-folder build → java. Here you will find the two folders x64 (64 bit) and x86 (32 bit) which contain the dll files of OpenCV. Open the respective folder suitable for your operating system, then you can see the dll file, as shown in the following screenshot. Now, set the path for this file too by following the steps given below − Step 1 − Once again, open the JavaBuildPath window. Here you can observe the added JAR file and the JRE System Library. Step 2 − On expanding it, you will get the system libraries and Native library location, as highlighted in the following screenshot. Step 3 − Double-click on the Native library location. Here, you can see the Native Library Folder Configuration window as shown below. Here, click the button External Folder… and select the location of the dll file in your system. Learning working make money
OpenCV – Overview OpenCV is a cross-platform library using which we can develop real-time computer vision applications. It mainly focuses on image processing, video capture and analysis including features like face detection and object detection. Let’s start the chapter by defining the term “Computer Vision”. Computer Vision Computer Vision can be defined as a discipline that explains how to reconstruct, interrupt, and understand a 3D scene from its 2D images, in terms of the properties of the structure present in the scene. It deals with modeling and replicating human vision using computer software and hardware. Computer Vision overlaps significantly with the following fields − Image Processing − It focuses on image manipulation. Pattern Recognition − It explains various techniques to classify patterns. Photogrammetry − It is concerned with obtaining accurate measurements from images. Computer Vision Vs Image Processing Image processing deals with image-to-image transformation. The input and output of image processing are both images. Computer vision is the construction of explicit, meaningful descriptions of physical objects from their image. The output of computer vision is a description or an interpretation of structures in 3D scene. Applications of Computer Vision Here we have listed down some of major domains where Computer Vision is heavily used. Robotics Application Localization − Determine robot location automatically Navigation Obstacles avoidance Assembly (peg-in-hole, welding, painting) Manipulation (e.g. PUMA robot manipulator) Human Robot Interaction (HRI) − Intelligent robotics to interact with and serve people Medicine Application Classification and detection (e.g. lesion or cells classification and tumor detection) 2D/3D segmentation 3D human organ reconstruction (MRI or ultrasound) Vision-guided robotics surgery Industrial Automation Application Industrial inspection (defect detection) Assembly Barcode and package label reading Object sorting Document understanding (e.g. OCR) Security Application Biometrics (iris, finger print, face recognition) Surveillance − Detecting certain suspicious activities or behaviors Transportation Application Autonomous vehicle Safety, e.g., driver vigilance monitoring Features of OpenCV Library Using OpenCV library, you can − Read and write images Capture and save videos Process images (filter, transform) Perform feature detection Detect specific objects such as faces, eyes, cars, in the videos or images. Analyze the video, i.e., estimate the motion in it, subtract the background, and track objects in it. OpenCV was originally developed in C++. In addition to it, Python and Java bindings were provided. OpenCV runs on various Operating Systems such as windows, Linux, OSx, FreeBSD, Net BSD, Open BSD, etc. This tutorial explains the concepts of OpenCV with examples using Java bindings. OpenCV Library Modules Following are the main library modules of the OpenCV library. Core Functionality This module covers the basic data structures such as Scalar, Point, Range, etc., that are used to build OpenCV applications. In addition to these, it also includes the multidimensional array Mat, which is used to store the images. In the Java library of OpenCV, this module is included as a package with the name org.opencv.core. Image Processing This module covers various image processing operations such as image filtering, geometrical image transformations, color space conversion, histograms, etc. In the Java library of OpenCV, this module is included as a package with the name org.opencv.imgproc. Video This module covers the video analysis concepts such as motion estimation, background subtraction, and object tracking. In the Java library of OpenCV, this module is included as a package with the name org.opencv.video. Video I/O This module explains the video capturing and video codecs using OpenCV library. In the Java library of OpenCV, this module is included as a package with the name org.opencv.videoio. calib3d This module includes algorithms regarding basic multiple-view geometry algorithms, single and stereo camera calibration, object pose estimation, stereo correspondence and elements of 3D reconstruction. In the Java library of OpenCV, this module is included as a package with the name org.opencv.calib3d. features2d This module includes the concepts of feature detection and description. In the Java library of OpenCV, this module is included as a package with the name org.opencv.features2d. Objdetect This module includes the detection of objects and instances of the predefined classes such as faces, eyes, mugs, people, cars, etc. In the Java library of OpenCV, this module is included as a package with the name org.opencv.objdetect. Highgui This is an easy-to-use interface with simple UI capabilities. In the Java library of OpenCV, the features of this module is included in two different packages namely, org.opencv.imgcodecs and org.opencv.videoio. A Brief History of OpenCV OpenCV was initially an Intel research initiative to advise CPU-intensive applications. It was officially launched in 1999. In the year 2006, its first major version, OpenCV 1.0 was released. In October 2009, the second major version, OpenCV 2 was released. In August 2012, OpenCV was taken by a nonprofit organization OpenCV.org. Learning working make money
OpenCV – Sobel Operator Using the sobel operation, you can detect the edges of an image in both horizontal and vertical directions. You can apply sobel operation on an image using the method sobel(). Following is the syntax of this method − Sobel(src, dst, ddepth, dx, dy) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. ddepth − An integer variable representing the depth of the image (-1) dx − An integer variable representing the x-derivative. (0 or 1) dy − An integer variable representing the y-derivative. (0 or 1) Example The following program demonstrates how to perform Sobel operation on a given image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class SobelTest { public static void main(String args[]) { // Loading the OpenCV core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Reading the Image from the file and storing it in to a Matrix object String file =”E:/OpenCV/chap16/sobel_input.jpg”; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Applying sobel on the Image Imgproc.Sobel(src, dst, -1, 1, 1); // Writing the image Imgcodecs.imwrite(“E:/OpenCV/chap16/sobel_output.jpg”, dst); System.out.println(“Image processed”); } } Assume that following is the input image sobel_input.jpg specified in the above program. Output On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − sobel Variants On passing different values to the last to parameters (dx and dy) (among 0 and 1), you will get different outputs − // Applying sobel on the Image Imgproc.Sobel(src, dst, -1, 1, 1); The following table lists various values for the variables dx and dy of the method Sobel() and their respective outputs. X-derivative Y-derivative Output 0 1 1 0 1 1 Learning working make money
OpenCV – GUI In the earlier chapters, we have discussed how to read and save an image using OpenCV Java library. In addition to it, we can also display the loaded images in a separate window using GUI libraries such as AWT/Swings and JavaFX. Converting Mat to Buffered Image To read an image we use the method imread(). This method returns the image read in the form of Matrix. But, to use this image with GUI libraries (AWT/Swings and JavaFX), it should be converted as an object of the class BufferedImage of the package java.awt.image.BufferedImage. Following are the steps to convert a Mat object of OpenCV to BufferedImage object. Step 1: encode the Mat to MatOfByte First of all, you need to convert the matrix to matrix of byte. You can do it using the method imencode() of the class Imgcodecs. Following is the syntax of this method. imencode(ext, image, matOfByte); This method accepts the following parameters − Ext − A String parameter specifying the image format (.jpg, .png, etc.) image − A Mat object of the image matOfByte − An empty object of the class MatOfByte Encode the image using this method as shown below. //Reading the image Mat image = Imgcodecs.imread(file); //instantiating an empty MatOfByte class MatOfByte matOfByte = new MatOfByte(); //Converting the Mat object to MatOfByte Imgcodecs.imencode(“.jpg”, image, matOfByte); Step 2: Convert the MatOfByte object to byte array Convert the MatOfByte object into a byte array using the method toArray(). byte[] byteArray = matOfByte.toArray(); Step 3: Preparing the InputStream object Prepare the InputStream object by passing the byte array created in the previous step to the constructor of the ByteArrayInputStream class. //Preparing the InputStream object InputStream in = new ByteArrayInputStream(byteArray); Step 4: Preparing the InputStream object Pass the Input Stream object created in the previous step to the read() method of the ImageIO class. This will return a BufferedImage object. //Preparing the BufferedImage BufferedImage bufImage = ImageIO.read(in); Displaying Image using AWT/Swings To display an image using the AWT/Swings frame, first of all, read an image using the imread() method and convert it into BufferedImage following the above-mentioned steps. Then, instantiate the JFrame class and add the buffered image created to the ContentPane of the JFrame, as shown below − //Instantiate JFrame JFrame frame = new JFrame(); //Set Content to the JFrame frame.getContentPane().add(new JLabel(new ImageIcon(bufImage))); frame.pack(); frame.setVisible(true); Example The following program code shows how you can read an image and display it through swing window using OpenCV library. import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.imgcodecs.Imgcodecs; public class DisplayingImagesUsingSwings { public static void main(String args[]) throws Exception { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the Image from the file and storing it in to a Matrix object String file = “C:/EXAMPLES/OpenCV/sample.jpg”; Mat image = Imgcodecs.imread(file); //Encoding the image MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(“.jpg”, image, matOfByte); //Storing the encoded Mat in a byte array byte[] byteArray = matOfByte.toArray(); //Preparing the Buffered Image InputStream in = new ByteArrayInputStream(byteArray); BufferedImage bufImage = ImageIO.read(in); //Instantiate JFrame JFrame frame = new JFrame(); //Set Content to the JFrame frame.getContentPane().add(new JLabel(new ImageIcon(bufImage))); frame.pack(); frame.setVisible(true); System.out.println(“Image Loaded”); } } On executing the above program, you will get the following output − Image Loaded In addition to that, you can see a window displaying the image loaded, as follows − Displaying Image using JavaFX To display an image using JavaFX, first of all, read an image using the imread() method and convert it into BufferedImage. Then, convert the BufferedImage to WritableImage, as shown below. WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null); Pass this WritableImage object to the constructor of the ImageView class. ImageView imageView = new ImageView(writableImage); Example The following program code shows how to read an image and display it through JavaFX window using OpenCV library. import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; 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; import javax.imageio.ImageIO; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.imgcodecs.Imgcodecs; public class DisplayingImagesJavaFX extends Application { @Override public void start(Stage stage) throws IOException { WritableImage writableImage = loadImage(); //Setting the image view ImageView imageView = new ImageView(writableImage); //Setting the position of the image imageView.setX(50); imageView.setY(25); //setting the fit height and width of the image view imageView.setFitHeight(400); imageView.setFitWidth(500); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); //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(“Loading an image”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public WritableImage loadImage() throws IOException { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the Image from the file and storing it in to a Matrix object String file =”C:/EXAMPLES/OpenCV/sample.jpg”; Mat image = Imgcodecs.imread(file); //Encoding the image MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(“.jpg”, image, matOfByte); //Storing the encoded Mat in a byte array byte[] byteArray = matOfByte.toArray(); //Displaying the image InputStream in = new ByteArrayInputStream(byteArray); BufferedImage bufImage = ImageIO.read(in); System.out.println(“Image Loaded”); WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null); return writableImage; } public static void main(String args[]) { launch(args); } } On executing the above program, you will get the following output − Image Loaded In addition to that, you can see a window displaying the image loaded, as follows − Learning working make money
OpenCV – Scharr Operator Scharr is also used to detect the second derivatives of an image in horizontal and vertical directions. You can perform scharr operation on an image using the method scharr(). Following is the syntax of this method − Scharr(src, dst, ddepth, dx, dy) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. ddepth − An integer variable representing the depth of the image (-1) dx − An integer variable representing the x-derivative. (0 or 1) dy − An integer variable representing the y-derivative. (0 or 1) Example The following program demonstrates how to apply scharr to a given image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class ScharrTest { public static void main( String[] args ) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file =”E:/OpenCV/chap16/sobel_input.jpg”; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Applying Box Filter effect on the Image Imgproc.Scharr(src, dst, Imgproc.CV_SCHARR, 0, 1); // Writing the image Imgcodecs.imwrite(“E:/OpenCV/chap16/scharr_output.jpg”, dst); System.out.println(“Image processed”); } } Assume that following is the input image scharr_input.jpg specified in the above program. Output On executing it, you will get the following output − Image Processed If you open the specified path you can observe the output image as follows − More scharr Derivatives On passing different values to the last to parameters (dx and dy) (among 0 and 1) you will get different outputs − // Applying scharr on the Image Imgproc.Scharr(src, dst, -1, 1, 1); Following is a table listing various values for the variables dx and dy of the method scharr() and their respective outputs. X-derivative Y-derivative Output 0 1 1 0 Learning working make money
OpenCV – Reading Images The Imgcodecs class of the package org.opencv.imgcodecs provides methods to read and write images. Using OpenCV, you can read an image and store it in a matrix (perform transformations on the matrix if needed). Later, you can write the processed matrix to a file. The read() method of the Imgcodecs class is used to read an image using OpenCV. Following is the syntax of this method. imread(filename) It accepts an argument (filename), a variable of the String type representing the path of the file that is to be read. Given below are the steps to be followed to read images in Java using OpenCV library. Step 1: Load the OpenCV native library Load the OpenCV native library using the load() method, as shown below. //Loading the core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Step 2: Instantiate the Imgcodecs class Instantiate the Imgcodecs class. //Instantiating the Imgcodecs class Imgcodecs imageCodecs = new Imgcodecs(); Step 3: Reading the image Read the image using the method imread(). This method accepts a string argument representing the path of the image and returns the image read as Mat object. //Reading the Image from the file Mat matrix = imageCodecs.imread(Path of the image); Example The following program code shows how you can read an image using OpenCV library. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; public class ReadingImages { public static void main(String args[]) { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Instantiating the Imagecodecs class Imgcodecs imageCodecs = new Imgcodecs(); //Reading the Image from the file String file =”C:/EXAMPLES/OpenCV/sample.jpg”; Mat matrix = imageCodecs.imread(file); System.out.println(“Image Loaded”); } } On executing the above program, OpenCV loads the specified image and displays the following output − Image Loaded Learning working make money
OpenCV Tutorial Job Search OpenCV is a cross-platform library using which we can develop real-time computer vision applications. It mainly focuses on image processing, video capture and analysis including features like face detection and object detection. In this tutorial, we explain how you can use OpenCV in your applications. Audience This tutorial has been prepared for beginners to make them understand the basics of OpenCV library. We have used the Java programming language in all the examples, therefore you should have a basic exposure to Java in order to benefit from this tutorial. Prerequisites For this tutorial, it is assumed that the readers have a prior knowledge of Java programming language. In some of the programs of this tutorial, we have used JavaFX for GUI purpose. So, it is recommended that you go through our JavaFX tutorial before proceeding further . Learning working make money