我必须阅读,修改和编写PPM图像。我试图通过尝试将其写入新文件来检查我的数组中是否获得了PPM图像的所有数据。但我得到的图像看起来像一个破碎的电视:a pattern of this:
我不知道我做错了什么,我想知道至少一种检查可能出错的方法。这些是我的代码: 主要: 图像实例;
string filename = "Image03.ppm";
string format = "ppm";
bool fileWritten = false;
if (instance.load(filename, format)) {
cout << "The file has been successfully loaded" << endl;
cout << "The dimensions of the image are:" << endl;
cout << instance.getWidth() << "x" << instance.getHeight() << endl;
...
bool imaging::Image::load(const string & filename, const string & format){
string extension = filename.substr(filename.find_last_of(".") + 1);
bool flag = false; // to stop the loop when a different letter is found.
bool result = false; // stores the return value
unsigned int sz = extension.size();
for (unsigned int i = 0; i < sz; ++i) {
if (tolower(extension[i]) != tolower(format[i]) && !flag) {
cout << "The extension of the file does not match the required format." << endl;
flag = true;
}
}
if (!flag) {
string filename1 = filename;
const char *cstr = filename1.c_str();
int pw = 0;
int ph = 0;
float* buff = ReadPPM(cstr, &pw, &ph);
width = pw;
height = ph;
bool h = WritePPM(buff, width, height, "kokoo.ppm");
...
bool WritePPM(const float * data, int w, int h, const char * filename) {
ofstream myfile;
myfile.open(filename, ios::out | ios::binary);
myfile << "P6\n" << w << "\n" << h << "\n255\n";
for (int i = 0; i < w*h; i++) {
myfile.write((char*)&data[i], sizeof(float));
}
myfile.close();
return 0;
}
...
float * ReadPPM(const char * filename, int* w, int* h) {
ifstream myfile;
myfile.open(filename, ios::binary);
if (myfile.is_open())
{
int i = 0;
string letter;
cout << "File successfully open" << endl;
myfile.ignore(2, ' ');
int width;
int height;
myfile >> width;
myfile >> height;
myfile.ignore(4, ' ');
*w = width;
*h = height;
int size = width*height * 3;
int k = myfile.peek();
while (k == 32) { //32 is ascii for whitespace.
myfile.ignore(256,' ');
k = myfile.peek();
}
unsigned char * temp = new unsigned char[size];
myfile.read((char*)temp, size);
float * buff = new float[size];
while (i < size) {
buff[i] = (float)temp[i]/255;
i++;
cout << "before" << buff[i] << endl;
cin.get();
}
delete[] temp;
return buff;
myfile.close();
}
else
{
cout << "Error opening file";
cin.get();
return 0;
}
}
即使我的代码看起来很傻,这也是我对这种语言不熟悉的原因,除非我做了一些非常错误的事情,我喜欢它看起来如何,无论如何它都是一项任务。 / p>
答案 0 :(得分:1)
如果你真的需要转换为浮点数组,那么你错了:
WritePPM
中的循环完全错误。你忘记了3,你忘了通过乘以255来缩小,你不能将浮点值写入PPM。它应该是这样的:
for (int i = 0; i < 3*w*h; i++) {
unsigned char c = (unsigned char) (255.0f * data[i] + 0.5f);
myfile.write((char*) &c, sizeof(c));
}
我没有检查所有其他代码,但您肯定还有其他一些错误,例如在ReadPPM
中的return语句后关闭文件。