我目前正在开发一段代码,使用OpenCV将图像转换为灰度。我已设法将图像变为黑白,如我所愿,使用以下代码:
public static void Greyscale() {
Mat inputImage = Highgui.imread("files/lena.png");
Mat greyImage = new Mat();
Imshow ims4 = new Imshow("Grey Image");
Imgproc.cvtColor(inputImage, greyImage, Imgproc.COLOR_BGR2GRAY);
ims4.showImage(greyImage);
但是,我现在想对某些特定像素运行get()方法,以确保所有BGR值都相等。但是,这不起作用:
double[] bgr = greyImage.get(0, 0);
System.out.println( "colour @ (0,0) = B: " + bgr[0] + " G: " + bgr[1] + " R: " + bgr[2]);
运行上面的代码会导致错误消息,如“线程中的异常”主“java.lang.ArrayIndexOutOfBoundsException:1 在ColourQuery.Greyscale(ColourQuery.java:129) 在ColourQuery.main(ColourQuery.java:67)“
有人能指出我在这个代码出错的地方吗?当图像不是灰度时,它适用于图像......
答案 0 :(得分:1)
并非所有图片都有相同数量的频道,也许你需要一个条件:
double[] pixel = img.get(0, 0);
switch( img.channels() ) {
case 1: // grayscale, luminance only
System.out.println( "colour @ (0,0) = L: " + pixel[0]);
break;
case 3: // bgr
System.out.println( "colour @ (0,0) = B: " + pixel[0] + " G: " + pixel[1] + " R: " + pixel[3]);
break;
case 4: // bgra
System.out.println( "colour @ (0,0) = B: " + pixel[0] + " G: " + pixel[1] + " R: " + pixel[3]+ " A: " + pixel[3]);
break;
}