我需要读取一个 pgm 文件并将其中包含的值数组存储在一个二维数组中。在 PGM 格式中,每个像素由 0 到 MaxVal 之间的灰度值指定。前三行给出了与图像相关的信息:幻数、高度、宽度和 maxVal。该文件还包括空格。以# 开头的行是注释。这是我写到现在的。
public class PGM{
public static void main(String args[]) throws Exception {
FileInputStream f = new FileInputStream("C:\\......\\brain_001.pgm");
DataInputStream d = new DataInputStream(f);
d.readLine();//first line contains P5
String line = d.readLine();//second line contains height and width
Scanner s = new Scanner(line);
int width = s.nextInt();
int height = s.nextInt();
line = d.readLine();//third line contains maxVal
s = new Scanner(line);
int maxVal = s.nextInt();
byte[][] im = new byte[height][width];
for (int i = 0; i < 258; i++) {
for (int j = 0; j < 258; j++) {
im[i][j] = -1;
}
}
int count = 0;
byte b;
try {
while (true) {
b = (byte) (d.readUnsignedByte());
if (b == '\n') { //do nothing if new line encountered
} else if (b == '#') {
d.readLine();
} else if (Character.isWhitespace(b)) { // do nothing if whitespace encountered
} else {
im[count / width][count % width] = b;
count++;
}
}
} catch (EOFException e) {
}
System.out.println("Height=" + height);
System.out.println("Width=" + height);
System.out.println("Required elemnts=" + (height * width));
System.out.println("Obtained elemnets=" + count);
}
}
当程序运行时,我得到以下输出:
Height=258
Width=258
Required elemnts=66564
Obtained elemnets=43513
元素的数量(每个对应一个灰度值)少于所需的数量。当我用 PGM 查看器打开文件时,一切都正确显示。此外,当我打印数组的内容时,我看到很多负值。但它们都必须大于或等于零。我哪里出错了?