How to declare OpenCV Mat object using Java?


In OpenCV Mat class represents a matrix object which is used to store images. You can also declare a Mat object manually −

  • 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().

  • Instantiate the Mat class − Instantiate the Mat class using any of the functions mentioned in this chapter earlier.

  • Fill the matrix using the methods − You can retrieve particular rows/columns of a matrix by passing index values to the methods row()/col().

  • you can set values to these using any of the variants of the setTo() methods.

Example

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;
public class CreatingMat {
   public static void main(String[] args) {
      //Loading the core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      //Creating a matrix
      Mat matrix = new Mat(5, 5, CvType.CV_8UC1, new Scalar(0));
      //Adding values
      Mat row0 = matrix.row(0);
      row0.setTo(new Scalar(1));
      Mat col3 = matrix.col(3);
      col3.setTo(new Scalar(3));
      //Printing the matrix
      System.out.println("Matrix data:\n" + matrix.dump());
   }
}

Output

Matrix data:
[
   1, 1, 1, 3, 1;
   0, 0, 0, 3, 0;
   0, 0, 0, 3, 0;
   0, 0, 0, 3, 0;
   0, 0, 0, 3, 0
]

Updated on: 09-Apr-2020

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements