How to write an image using Java OpenCV library?

JavaObject Oriented ProgrammingProgramming

Using the OpenCV library you can perform image processing operations such as image filtering, geometrical image transformations, color space conversion, histograms, etc.

Writing an image

Whenever you read the contents of an image using the imread() method of the Imgcodecs class the result is read into the Matrix object.

You can write/save an image using the imwrite() method. This accepts two parameters namely −

  • File − A string value representing the file path to which the result should be stored.

  • Img − A matrix object containing the data of the image to be saved.

Example

The following Java example reads the contents of the image cat.jpg as a greyscale image and re-saves it with another name.

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public class WritingImages {
   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 ="D://images//cat.jpg";
      Mat matrix = Imgcodecs.imread(file);
      System.out.println("Image Loaded");
      String file2 = "D://images//sample_resaved.jpg";
      //Writing the image
      Imgcodecs.imwrite(file2, matrix);
      System.out.println("Image Saved");
   }
}

Input: cat.jpg

Output: sample_resaved.jpg

raja
Published on 08-Apr-2020 13:05:30
Advertisements