English 中文(简体)
OpenCV Tutorial

Types of Images

Image Conversion

Drawing Functions

Blur

Filtering

Thresholding

Sobel Derivatives

Transformation Operations

Camera and Face Detection

Geometric Transformations

Miscellaneous Chapters

OpenCV Useful Resources

Selected Reading

OpenCV - Reading Images
  • 时间:2024-09-08

OpenCV - Reading Images


Previous Page Next Page  

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 pbrary.

Step 1: Load the OpenCV native pbrary

Load the OpenCV native pbrary using the load() method, as shown below.

//Loading the core pbrary 
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 pbrary.

import org.opencv.core.Core; 
import org.opencv.core.Mat;  
import org.opencv.imgcodecs.Imgcodecs;
 
pubpc class ReadingImages {
   pubpc static void main(String args[]) { 
      //Loading the OpenCV core pbrary  
      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