java - 将 OpenCV 矩阵循环转换为 JavaCV

标签 java c pointers opencv javacv

不久前拿到了 O'Reilly 的《学习 OpenCV》一书,从那时起,我一直忙于将在那里看到的所有示例代码从 OpenCV 转换为 JavaCV,通常还会进行一些我自己的修改。一直以来,我都在尝试尽可能多地使用纯 OpenCV(C 语言)代码并避免使用 Java。例如,我直接通过 JavaCV 中的 OpenCV highgui 包实现了所有界面元素,而不是通过 Java Swing。通过这样做,我希望在相对较短的时间内学习 OpenCV 库和一些 C,并建立一个有用的函数库,如果我决定以后切换到纯 OpenCV,我将能够轻松地将其转换为 C。

反正我对C的了解很少,在处理指针的时候有时会遇到麻烦。本书推荐以下代码作为迭代 3 channel 矩阵的最佳方式:

float sum( const CvMat* mat ) {
    float s = 0.0f;
    for(int row=0; row<mat->rows; row++ ) {
        const float* ptr = (const float*)(mat->data.ptr + row * mat->step);
        for( col=0; col<mat->cols; col++ ) {
            s += *ptr++;
        }
    }
    return( s );
}

下面是这段代码的解释:

When computing the pointer into the matrix, remember that the matrix element data is a union. Therefore, when de-referencing this pointer, you must indicate the correct element of the union in order to obtain the correct pointer type. Th en, to off set that pointer, you must use the step element of the matrix. As noted previously, the step element is in bytes. To be safe, it is best to do your pointer arithmetic in bytes and > then cast to the appropriate type, in this case float. Although the CVMat structure has > the concept of height and width for compatibility with the older IplImage structure, we > use the more up-to-date rows and cols instead. Finally, note that we recompute ptr for > every row rather than simply starting at the beginning and then incrementing that pointer every read. Th is might seem excessive, but because the CvMat data pointer could just point to an ROI within a larger array, there is no guarantee that the data will be > contiguous across rows.

但是我无法将其转换为 JavaCV。 ptr 字段(指针)似乎是一个 float ,这让我很困惑。我认为它实际上不是一个“指针”,而是一个值,每个像素的值都添加到该值?或者它实际上是一个指针,s 值找到给定行内所有列的总和?

无论如何,如果有人能为我发布一些等效循环的 JavaCV 代码,我将不胜感激。我知道还有其他方法可以访问 CvMat 中的每个像素,但据我所知,它们的效率都较低或不准确。

最佳答案

您提供的特定示例将以最佳方式转换为 Java 为

float sum(CvMat mat) {
    final int rows = mat.rows();
    final int cols = mat.cols();
    final int step = mat.step()/4;
    FloatBuffer buf = mat.getFloatBuffer();
    float s = 0.0f;
    for (int row = 0; row < rows; row++) {
        buf.position(row * step);
        for (int col = 0; col< cols; col++) {
            s += buf.get();
        }
    }
    return s;
}

关于java - 将 OpenCV 矩阵循环转换为 JavaCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9920449/

相关文章:

java - 使用 Jersey 防止对象属性内的空值

java - 在测试 Google 应用程序内时对测试购买进行退款

Java Sleep 不在循环中工作

c - Makefile 子目录

c++ - 数组的地址

java - 自动在多个位置部署 Java 应用程序(RMI 服务器)

c - 为什么 Clang 认为这些类型在开罗会发生冲突?

c - 局部静态变量存储在哪里?如果是数据段,为什么它的范围不是整个程序?

c - 将一个指向struct的指针和一个int传递给C中的函数以实现堆栈

c - 如何在C中为用户实时输入的字符串分配内存?