首页 > 解决方案 > Java中的OpenCV ptr

问题描述

我想知道如何用 Java 制作这个 opencv c++ 代码

uchar *ptr = eye.ptr<uchar>(y);

我一直在环顾四周,我想我可以将 uchar 用作字节......但我不知道在 java 中获取 .ptr 的代码是什么

到目前为止,这是我的代码

private Rect getEyeball(Mat eye, MatOfRect circles) {
    int[] sums = new int[circles.toArray().length];

    for (int y = 0; y < eye.rows(); y++) {
        // OpenCV method uchar *ptr = eye.ptr<uchar>(y); Goes here 
    }

    int smallestSum = 9999999;
    int smallestSumIndex = -1;

    for (int i = 0; i < circles.toArray().length; i++) {
        if (sums[i] < smallestSum) {
            smallestSum = sums[i];
            smallestSumIndex = i;
        }
    }

    return circles.toArray()[smallestSumIndex];
}

完整的 C++ 代码是

cv::Vec3f getEyeball(cv::Mat &eye, std::vector<cv::Vec3f> &circles)
{
    std::vector<int> sums(circles.size(), 0);
    for (int y = 0; y < eye.rows; y++)
    {
        uchar *ptr = eye.ptr<uchar>(y);
        for (int x = 0; x < eye.cols; x++)
        {
            int value = static_cast<int>(*ptr);
            for (int i = 0; i < circles.size(); i++)
            {
                cv::Point center((int)std::round(circles[i][0]), (int)std::round(circles[i][1]));
                int radius = (int)std::round(circles[i][2]);
                if (std::pow(x - center.x, 2) + std::pow(y - center.y, 2) < std::pow(radius, 2))
                {
                    sums[i] += value;
                }
            }
        ++ptr;
        }
    }
    int smallestSum = 9999999;
    int smallestSumIndex = -1;
    for (int i = 0; i < circles.size(); i++)
    {
        if (sums[i] < smallestSum)
        {
            smallestSum = sums[i];
            smallestSumIndex = i;
         }
    }
    return circles[smallestSumIndex];
}

标签: javac++opencv

解决方案


提炼你的 C++:

for (int y = 0; y < eye.rows; y++)
{
    uchar *ptr = eye.ptr<uchar>(y);
    for (int x = 0; x < eye.cols; x++)
    {
      int value = static_cast<int>(*ptr);
      // A loop not using ptr.
      ++ptr;
    }
}

您只是从 .x 获取 (x,y) 处的像素值eye

因此,只需使用Mat.get.

int[] values = new int[eye.channels()];
for (int y = 0; y < eye.rows(); y++) {
  for (int x = 0; x < eye.cols(); x++) {
    eye.get(x, y, values);
    int value = values[0];

    // A loop not using ptr.
  }
}

请注意,使用get(int, int, int[])而不是get(int, int)在这里意味着您避免为每次迭代分配一个新数组,这将使事情变得快得多。


推荐阅读