【发布时间】:2014-12-19 13:45:48
【问题描述】:
我必须为我的机器学习课程准备一个训练集,其中对于给定的面部图像,它会给你一个代表头部侧面的答案(直、左、右、上)
为此,我需要在 java 中读取 .pgm 图像文件并将其像素存储在矩阵 X 的一行中,然后将该图像的适当正确答案存储在 y 向量中。最后我会将这两个数组保存在一个 .mat 文件中。
问题是当尝试从 (P2 .pgm) 图像中读取像素值并将它们打印到控制台时,它们不会与 matlab 矩阵查看器给出相同的值。会有什么问题?
这是我的代码:
try{
InputStream f = Main.class.getResourceAsStream("an2i_left_angry_open.pgm");
BufferedReader d = new BufferedReader(new InputStreamReader(f));
String magic = d.readLine(); // first line contains P2 or P5
String line = d.readLine(); // second line contains height and width
while (line.startsWith("#")) { // ignoring comment lines
line = d.readLine();
}
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();
for(int i=0;i<30;i++) /* printing first 30 values from the image including spaces*/
System.out.println((byte)d.read());
} catch (EOFException eof) {
eof.printStackTrace(System.out) ;
}
这些是我得到的值: 50 49 32 50 32 49 32 48 32 50 32 49 56 32 53 57
虽然这张照片确实是来自 MATLAB Viewer 的图像: (对不起,由于缺乏声誉,我无法发布图片)
这就是您通过 notepad++ 打开 .pgm 文件时发现的内容
【问题讨论】:
-
您的 java 实现正在打印文本字节“21 2 1”等的 ASCII 值。一些 PGM 文件使用文本标题,但像素本身的二进制表示。这些在开头用不同的魔术字符串标记。看起来 java 代码正在读取文件,就好像它有二进制像素一样。
-
谢谢@Peter 我现在明白了。但是你能不能给我一个替代方法来读取整个整数并忽略空格。所以我可以在我的控制台上输出记事本++
-
@AliSmart - 只需查找 ASCII 码 32。如果您读到数字 32,请跳过并继续。