nullpointerexception

cnjp1d6j  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(240)

这个问题在这里已经有答案了

什么是nullpointerexception,如何修复它(12个答案)
18天前关门了。

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

我在线程“main”java.lang.nullpointerexception:的第11行抛出一个空指针异常,因为“pixel”为空,所以无法从双数组加载。
我尝试添加代码:system.out.println(arrays.deeptostring(pixel));
在这样做之后,我可以看到我的程序实际上是按照预期的方式为前几个百像素值工作的,但是出于某种原因,它一直在相同的值上停止,然后在抛出异常之前读取null。如有任何建议,将不胜感激。

3duebb1j

3duebb1j1#

double rgbVal; 
double[] pixel = matrix.get(i, j);
rgbVal = pixel[0] + pixel[1] + pixel[2];

我相信你的问题是像素阵列实际上没有3个元素。像素[0]和像素[1]已计算,但像素[2]不存在?
rgb应该有三个值,我会为rgb中的蓝色值添加另一个int,然后通过数组传递它

vaqhlq81

vaqhlq812#

在opencv中,图像被视为2d(或3d)数组,并通过矩阵索引进行索引( row , column )而不是笛卡尔坐标( x , y ). 问题是您的代码正在使用索引 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
        }
    }

相关问题