【发布时间】:2016-07-11 00:09:50
【问题描述】:
int main(){
std::fstream myfile; // file object is created
myfile.open ("green.ppm");
std::string line;
unsigned red,green,blue; //to output values on 0 -255 scale.
int width, height = 0;
if (myfile.is_open())
{
std::getline (myfile,line); //type of file, skip, it will always be for this code p6
std::getline (myfile,line); // width and height of the image
std::stringstream lineStream(line); //extract the width and height;
lineStream >> width;
lineStream >> height;
// std::cout<< width << " " << height <<" \n";
getline (myfile,line); //skip magic number
getline (myfile,line); // reach the matrix of numbers
for (int i = 0; i<(width*height*3) ; i= i+3){
char num = line[i]; uint8_t number = num; red = number;
num = line[i+1]; number = num; green = number;
num = line[i+2]; number = num; blue = number;
std::cout<<"pixel " << i/3 << " is " << red << " " << green << " " << blue << std::endl;
}
//char to uint_8t to unsigned is a basic an inefficient way I found that takes the pixel rgb values in my ppm file and allows me to interpret them from a range of 0-255
}
// cout<<counter<<endl;
myfile.close();
return 0;
}
当我在不同的 ppm 图像上运行此代码时,它实际上确实正确地提取了 rgb 值,但问题是它并没有完全做到这一点。一个基本的 800 x 800 图像有 640000 像素,这段代码读取大约 40800,然后就好像它不再存在一样结束。
我认为这源于对 ppm 格式本身的误解。我认为除了带有类型、宽度和大小以及幻数的文件的标题格式之外,只有一行,没有更多的 '\n' 字符。因此,矩阵可以被读取为一个连续的字符数组。
那么为什么这个程序会停在这么奇怪的地方呢?
【问题讨论】: