Search code examples
javaopencvjavacvmat

Access to the pixel value of a Mat using the JavaCV API


I have recently switched from the OpenCV C++ API to JavaCV and I'm trying to perform a basic operation, such as iterating over a Mat. I'm trying to access the pixel value of the Mat, but I can't seem to find a way, and the JavaCV project is short on documentation. Using the OpenCV C++ API, I used to access the pixel value of a Mat by using the .at() method.

The Mat is loaded as CV_8UC1 Mat (greyscale), as you can see in the code below, and I would like to print/use the 0-255 value of the pixels.

    Mat image = imread("images/Text00.png", CV_8UC1);

    // Make sure it was successfully loaded.
    if (image == null) {
        System.out.println("Image not found!");
        System.exit(1);
    }

    System.out.println(image.rows());
    System.out.println(image.cols());

    for (int y = 0; y < image.rows(); y++) {

        for (int x = 0; x < image.cols(); x++) {

            // How to print the 0 to 255 value of each pixel in the Mat image.
        }
    }

Similar but not applicable answers:


Solution

  • On this, seemingly unrelated thread on the JavaCV GitHub discussion, I found the answer to my question after 1 day of googling. Pleace notice that there may be other, more efficient ways to do this, but this is the only way I found at the moment. The solution is the represented by the new "indexer" package provided by JavaCV (see this and this for more details).

    Its usage is pretty straightforward: after declaring something like DoubleIndexer idx = Mat.createIndexer() you can call idx.get(i, j) to get the elements of the matrix more easily.

    Here is my updated code (as you can see, I used a UByteBufferIndexer, since my Mat is a CV_8UC1 Mat):

        Mat image = imread("images/Text00.png", CV_8UC1);
    
        // Make sure it was successfully loaded.
        if (image == null) {
            System.out.println("Image not found!");
            System.exit(1);
        }
    
        UByteBufferIndexer sI = image.createIndexer();
    
        for (int y = 0; y < image.rows(); y++) {
    
            for (int x = 0; x < image.cols(); x++) {
    
                System.out.println( sI.get(y, x) );
            }
        }