【问题标题】:NullPointerException when filling a 2d array from Mat Object in OpenCV [duplicate]从 OpenCV 中的 Mat 对象填充二维数组时出现 NullPointerException [重复]
【发布时间】:2021-03-31 17:22:19
【问题描述】:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import java.util.Arrays;

public class Main {

private static double getRGB(int i, int j, Mat matrix) { //this method is used to obtain pixel values of an image
    double rgbVal; 
    double[] pixel = matrix.get(i, j);
    rgbVal = pixel[0] + pixel[1] + pixel[2]; //error on this line 
    rgbVal = rgbVal / 3;
    return rgbVal;
}

public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    Imgcodecs imageCodecs = new Imgcodecs();
    Mat matrix = imageCodecs.imread("/Users/brand/Downloads/SPACE.JPG");
    System.out.println("Image loaded");
    System.out.println("Image size : " + matrix.width() + " x " + matrix.height());
    double[][] rgb = new double[matrix.width()][matrix.height()]; //this is where i want to store the values

    for (int i = 0 ; i < matrix.width(); i++) {
        for (int j = 0; j < matrix.height(); j++) {
            rgb[i][j] = getRGB(i, j, matrix); //iterating through my Mat object and storing here
        }
    }
    System.out.println(Arrays.deepToString(rgb)); //checking if it works
}
}

我在第 11 行抛出一个空指针异常:线程“main”java.lang.NullPointerException 中的异常:无法从双精度数组加载,因为“pixel”为空。

我已尝试添加代码:System.out.println(Arrays.deepToString(pixel));

执行此操作后,我可以看到我的程序实际上对前几个饥饿的像素值按预期工作,但由于某种原因,它一直停止在相同的值上,然后在抛出异常之前读取 null。任何建议将不胜感激。

【问题讨论】:

  • @fantaghirocco 不幸的是它没有:(。关于这一点最大的头疼是它只是在迭代数百次后抛出空指针异常。我不明白是什么让它突然为空。

标签: java arrays opencv nullpointerexception


【解决方案1】:

在 OpenCV 中,图像被视为 2D(或 3D)数组,并通过矩阵索引(rowcolumn)而不是笛卡尔坐标(xy)进行索引。问题是您的代码使用索引i 来表示x 坐标而不是row 索引,并且使用图像的width 作为限制。要解决此问题,请将i 用作row 索引,并将图像中的行数限制为基本matrix.height()。类似的逻辑也适用于j 索引。请检查以下嵌套循环的更正:

    for (int i = 0 ; i < matrix.height(); i++) { // Height is the # of rows not width.
        for (int j = 0; j < matrix.width(); j++) { // Width is the # of columns not height.
            rgb[i][j] = getRGB(i, j, matrix); //iterating through my Mat object and storing here
        }
    }

【讨论】:

  • 更好的是,我会更明确,更喜欢使用 rc 作为循环计数器的名称,而不是模棱两可的 ij 索引。
  • 非常感谢!!!这是一场噩梦!有时你会在自己的脑海中变得如此,以至于你没有意识到从一开始就应该显而易见的事情。这是一次很棒的学习体验
  • @Stonezarcon,您可以标记具有启发性并解决了您的问题的答案。
【解决方案2】:
double rgbVal; 
double[] pixel = matrix.get(i, j);
rgbVal = pixel[0] + pixel[1] + pixel[2]; 

我相信你的问题是像素数组实际上并没有 3 个元素。 pixel[0] 和 pixel[1] 都占了,但是 pixel[2] 不存在?

RGB 应该有三个值,我会在 rgb 中为蓝色值添加另一个 int,然后通过数组传递它

【讨论】:

  • matrix.get(i, j) 返回这些坐标处的值,即 3 个 rgb 值,并将它们存储在我的 pixel[] 变量中。如果我在每次更新时添加代码来打印像素,它会正常工作一段时间,然后最终抛出异常。我希望这是有道理的。
  • 好吧,这很有趣,如果它无限期地工作直到某个特定点,那么这意味着图像中的某些东西可能会弄乱它。也许它是透明的(就像图像有内容一样,它有魔杖使它透明)并且没有实际的 rgb 值?我只是在这里吐个球,但我可以看到这是一个问题
猜你喜欢
  • 2013-11-26
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
相关资源
最近更新 更多