使用C++编写一个函数ImageLoader来读取P3格式的PPM文件的内容



我在尝试读取PPM文件时完全不知所措。我了解如何打开文件,以及如何访问幻数、宽度和高度以及最大颜色值。我很难理解从PPM文件中读取像素数据,并将其分配给先前定义的专用变量/矩阵图像[MAX_WIDTH[MAX_HEIGHT][3]背后的过程。此函数的目标是将PPM文件数据加载到图像阵列中,以便稍后在稍后的函数中绘制现有文件。我习惯于用python编写,所以我的c++真的很生疏。

P3
720 540
255
123 125 124 
124 126 125 127 129 128 129 131 130 128 130 129 126 128 127 
132 134 133 132 135 134 135 140 139 137 143 141 136 142 140 135 143 140 
134 144 140 135 147 142 138 145 143 139 143 142 138 142 141 137 141 140 
139 144 143 139 143 142 139 143 142 140 143 141 143 142 140 140 140 137 
enum COLOR { RED, GREEN, BLUE }; // this is in a header file
// everything below is in a cpp file
void Image::ImageLoader(string filename) {
int max_color;
ifstream infile; // image variable used to read from a file
infile.open(filename); // open the file, and associate image with it
if(infile.fail()){ // true if filename doesn't exist
throw "File failed to open";
}
string magic_num;
infile >> magic_num >> width >> height >> max_color;

if (max_color != MAX_COLOR){
throw "Max color range not 255";
}
if (magic_num != "P3"){
throw "Bad magic number";
}
if (width > MAX_WIDTH || width < 0)
throw "Width out of bounds";
if (height > MAX_HEIGHT || height < 0)
throw "Height out of bounds";

// This is where i'm stuck. I think I'm lacking some fundamental knowledge in c++ that's making this part harder. 
// my goal with these loops is to parse through the file infile value by value, and assign these values to my image matrix. 
// I don't really get what's happening with the array image[MAX_WIDTH][MAX_HEIGHT][3]. I know it's a 3d array, but how does the use of enum play into iterating through the array?
// Am I supposed to increment the third index while iterating, or do I iterate all three colors at once? 
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
if (0 > x || x > 255 || 0 > y || y > 255){
throw "Color value invalid";
}
infile >> image[x][y][RED];
infile >> image[x][y][GREEN];
infile >> image[x][y][BLUE];

}
}
}

来自规范:

每个PPM图像由以下部分组成:

高度行的光栅,按从上到下的顺序排列
每一行都由宽度像素组成,按从左到右的顺序排列
每个像素都是红色、绿色和蓝色样本的三元组,按顺序排列。

这自然转化为嵌套循环:

for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
unsigned int red, green, blue;
infile >> red >> green >> blue;
if (!infile) {
std::cerr << "Error reading from file around (" << y << "," << x << ")" << std::endl;
return;
}
// TODO: Check the values of red, green, blue against the interval [0,255] 
image[y][x][0] = red;
image[y][x][1] = green;
image[y][x][2] = blue;
}
}

最后,您定义了一个enum COLOR { RED, GREEN, BLUE }。C++将为这三个枚举值赋值,如下所示:RED=0, GREEN=1, BLUE=2

因此,在上面的代码中使用这些枚举值来代替0,1,2是很好的。

最新更新