[英]Reading a gray scale image into 1-d array
我已经编写了以下代码,将灰度图像的像素读取到1 d数组中。 运行代码时我怎么会出错
public class LoadImage {
BufferedImage image;
void load()throws Exception {
File input = new File("lena.png");
image = ImageIO.read(input);
}
public Dimension getImageSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
public int[] getImagePixels() {
int [] dummy = null;
int wid, hgt;
// compute size of the array
wid = image.getWidth();
hgt = image.getHeight();
// start getting the pixels
Raster pixelData;
pixelData = image.getData();
return pixelData.getPixels(0, 0, wid, hgt, dummy);
}
}
主班
public static void main(String[] args) throws IOException, Exception {
LoadImage l = new LoadImage();
l.load();
int pixel[];
pixel= l.getImagePixels();
}
好的,问题出在传递File对象时,是ImageIO.read中的格式问题。 尝试以下方法:
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LoadImage {
BufferedImage image;
void load() throws Exception {
image = ImageIO.read(getClass().getResourceAsStream("lena.png"));
}
public Dimension getImageSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
public int[] getImagePixels() {
int [] dummy = null;
int wid, hgt;
// compute size of the array
wid = image.getWidth();
hgt = image.getHeight();
// start getting the pixels
Raster pixelData;
pixelData = image.getData();
System.out.println("wid:"+ wid);
System.out.println("hgt:"+ hgt);
System.out.println("Channels:"+pixelData.getNumDataElements());
return pixelData.getPixels(0, 0, wid, hgt, dummy);
}
public static void main(String[] args) throws IOException, Exception {
LoadImage l = new LoadImage();
l.load();
int[] pixel;
pixel= l.getImagePixels();
System.out.println("length:"+pixel.length);
int height = 482;
int width = 372;
int channels = 3;
int color = 0;
BufferedImage red = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
BufferedImage green = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
BufferedImage blue = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
blue.setRGB(x, y, pixel[color * channels]);
green.setRGB(x, y, pixel[color * channels + 1] << 8);
red.setRGB(x, y, pixel[color * channels + 2] << 16);
color++;
}
}
ImageIO.write(red, "png", new File("red.png"));
ImageIO.write(green, "png", new File("green.png"));
ImageIO.write(blue, "png", new File("blue.png"));
}
}
当我通过372x482(带有24位(3通道)颜色)的PNG时,我得到
wid:372
hgt:482
Channels:3
length:537912
并使用更新的代码,这是您可以采用它返回的数组并将每个通道保存回文件的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.