[英]C++ how to parse a ppm file?
I'm trying to parse a ppm file.我正在尝试解析 ppm 文件。
The spec is this: http://netpbm.sourceforge.net/doc/ppm.html规范是这样的: http : //netpbm.sourceforge.net/doc/ppm.html
Example:例子:
P3
# feep.ppm
4 4
15
0 0 0 0 0 0 0 0 0 15 0 15
0 0 0 0 15 7 0 0 0 0 0 0
0 0 0 0 0 0 0 15 7 0 0 0
15 0 15 0 0 0 0 0 0 0 0 0
The stuff after the "15" are the rgb values of all pixels in the give image. “15”之后的东西是给定图像中所有像素的 rgb 值。
I have tried this so far:到目前为止我已经尝试过这个:
void read_and_draw_ppm_file() {
ifstream infile;
infile.open(TEXTURE_FILE.c_str());
string line;
int count = 0;
while (getline(infile, line) && count < 4) {
count++;
}
char c;
int red = -1, green = -1, blue = -1;
int rgb_count = 0;
for (int i = 0; i < TEXTURE_WIDTH; i++) {
for (int j = 0; j < TEXTURE_HEIGHT; j++) {
infile >> c;
if (rgb_count == 0) {
if (red != -1 && blue != -1 && green != -1) {
cout << red<<endl;
cout << green<<endl;
cout << blue<<endl;
uint32_t colour = (255 << 24) + (int(red) << 16) + (int(green) << 8) + int(blue);
window.setPixelColour(i, j, colour);
red = -1;
blue = -1;
green = -1;
}
red = (int) (unsigned char) c;
rgb_count++;
} else if (rgb_count == 1) {
green = (int) (unsigned char) c;
rgb_count++;
} else if (rgb_count == 2) {
blue = (int) (unsigned char) c;
rgb_count = 0;
}
}
}
infile.close();
}
The idea is to basically extract triplets of 3 bytes, then convert each to rgb respectively.这个想法基本上是提取 3 个字节的三元组,然后分别将每个转换为 rgb。
Problem is, when I display the image into the screen, the image isn't quite the same as it's supposed to be.问题是,当我将图像显示到屏幕上时,图像与预期的不太一样。
Where am I going wrong?我哪里错了?
The original image:原图:
You read in a value for red
, then increment j
.您读取red
的值,然后增加j
。 Then you read in green
, and increment j
.然后你以green
阅读,并增加j
。 Next you read blue
, store the pixel value, and increment j
.接下来读取blue
,存储像素值,并递增j
。
So you're writing out your values spaced out every 3 rows.所以你要写出每 3 行间隔开的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.