我正在尝试将彩色图像转换为灰度图像并将其作为BYTE值保存到2D数组中,之后我需要在此2D数组上执行一些处理。虽然,我的数组的值都是字节,但我的输出图像变为蓝色而不是灰色。有人可以帮我吗? 这是我的代码:
public class HW {
public static void main(String[] args) {
int[][] savedImage = readimage(new File("C:\\Images\\input.jpg"));
BufferedImage grayImage = new BufferedImage(savedImage.length, savedImage[0].length, BufferedImage.TYPE_INT_RGB);
for (int i =0 ; i<savedImage.length ; i ++){
for (int j=0 ; j<savedImage[0].length ; j++){
grayImage.setRGB(i, j, savedImage[i][j]);
System.out.print(savedImage[i][j] + ",");
}
System.out.println();
}
try {
File outputfile = new File ("C:\\Images\\garyoutput.jpg");
ImageIO.write(grayImage, "jpg", outputfile);
}
catch(IOException e ) {
e.printStackTrace();
}
}
public static int[][] readimage(File filename) throws IOException {
// Grayscale Image output
BufferedImage img = ImageIO.read(filename);
int width = img.getWidth();
int height = img.getHeight();
int [][] readimageVal = new int [width][height];
for (int i = 0; i<height ; i++) {
for (int j =0 ; j<width ; j++) {
int p = img.getRGB(j,i);
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff;
int avg = ((r+b+g)/3);
readimageVal[j][i] = avg;
}
}
return readimageVal;
}
}
答案 0 :(得分:2)
问题出在main
方法的主要嵌套循环中:
for (int i =0 ; i<savedImage.length ; i ++){
for (int j=0 ; j<savedImage[0].length ; j++){
grayImage.setRGB(i, j, savedImage[i][j]);//← Here
System.out.print(savedImage[i][j] + ",");
}
}
int[][] savedImage
包含一个代表灰度值的字节,但grayImage
仍为BufferedImage.TYPE_INT_RGB
类型。因此,如果您只拨打grayImage.setRGB(i, j, savedImage[i][j])
,则只会设置int
的蓝色部分:
RRRRRRRR GGGGGGGG BBBBBBBB
00000000 00000000 xxxxxxxx
所以你需要改为调用它:
int rgb = savedImage[i][j];
rgb = (rgb<<16)|(rgb<<8)|(rgb);
grayImage.setRGB(i, j, rgb);
答案 1 :(得分:1)
你有不同的可能性,但首先,这是一种更简单的方法来访问像素:
public static int[][] readimage(File filename) throws IOException {
BufferedImage img = ImageIO.read(filename) ;// Grayscale Image output
final int width = img.getWidth() ;
final int height = img.getHeight() ;
int[][] graylevelarray = new int[height][width] ;
for (int y=0 ; y < height ; y++)
for (int x=0 ; x < width ; x++) {
int r = img.getRaster().getSample(x, y, 0) ;
int g = img.getRaster().getSample(x, y, 1) ;
int b = img.getRaster().getSample(x, y, 2) ;
graylevelarray[y][x] = ??? ;
}
return graylevelarray ;
}
正如我所说,对于转换,你有很多不同的可能性: