使用 JavaCV 访问 Mat 的像素值 API

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

我最近从 OpenCV C++ API 切换到 JavaCV,我正在尝试执行基本操作,例如迭代 Mat。我正在尝试访问 Mat 的像素值,但我似乎找不到办法,而且 JavaCV 项目缺少文档。使用 OpenCV C++ API,我曾经使用 .at() 方法访问 Mat 的像素值。

垫子加载为 CV_8UC1 垫子(灰度),如您在下面的代码中所见,我想 print/use 像素的 0-255 值。

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

相似但不适用的答案:

关于这个,seemingly unrelated thread 在 JavaCV GitHub 讨论中,经过 1 天的谷歌搜索,我找到了问题的答案。请注意,可能还有其他更有效的方法可以做到这一点,但这是我目前找到的唯一方法。 解决方案由 JavaCV 提供的新 "indexer" 包 表示(有关详细信息,请参阅 this and this)。

它的用法非常简单:在声明类似 DoubleIndexer idx = Mat.createIndexer() 的内容后,您可以调用 idx.get(i, j) 来更轻松地获取矩阵的元素。

这是我更新的代码(如您所见,我使用了 UByteBufferIndexer,因为我的垫子是 CV_8UC1 垫子):

    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) );
        }
    }