我目前正在使用一段代码,使用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)”
谁能指出我这段代码出了什么问题?当它不是灰度时,它适用于图像...
最佳答案
并非所有图像都具有相同数量的通道,也许您需要一个条件:
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;
}