OpenCV - Reading Images


Advertisements

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
Advertisements