读取/写入PPM图像C ++,新图像被破坏

时间:2015-06-14 12:25:30

标签: c++ image ppm

我在SO上找到了一些用于读/写图像的C ++代码。我想改进它,所以我可以旋转等图像。但是,一开始我有一些问题。当我写图像时,似乎我的读取函数只读取了它的一部分,因为它只写入文件的一部分原始图像。请查看我的代码和输入,输出图像。

    #include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char **argv)
{
    ifstream in;
    in.open("OldImage.ppm", std::ios::binary);

    ofstream out;

    std::string magic_number;
    int width, height, maxColVal, i, j;

    in >> magic_number;
    in >> width >> height >> maxColVal;
    in.get();

    char **image;
    image = new char* [width];

    for(i=0; i<width; i++)
    {
        image[i] = new char [height];

        for(j=0; j<height; j++)
        {
            in >> image[i][j];
        }
    }

    out.open("NewImage.ppm", std::ios::binary);
    out << "P3"     << "\n"
        << width       << " "
        << height      << "\n"
        << maxColVal   << "\n"
        ;

    for(i=0; i<width; i++)
    {
        for(j=0; j<height; j++)
        {
            out << image[i][j];
        }
    }

    in.clear();
    in.close();

    out.clear();
    out.close();

    return 0;
}

输入图片: https://www.dropbox.com/s/c0103eyhxzimk0j/OldImage.ppm?dl=0

输出图片: https://www.dropbox.com/s/429i114c05gb8au/NewImage.ppm?dl=0

2 个答案:

答案 0 :(得分:0)

根据this doc,有两种形式的ppm图像文件:raw和plain。您似乎采用了正常的原始格式,但您使用的是幻数 P3 ,这是纯ppm。尝试 P6

此外,您的高度和宽度循环应该是相反的,但这不会影响结果。据推测,它是旋转图像的代码的一部分。

答案 1 :(得分:0)

ppm个文件每个像素有3个值(R,G和B)。您的代码假定只有1个值(强度?)。尝试阅读和撰写pgm个文件(&#34; magic_number&#34;等于P2)。

或者,读取每个像素的所有3个值:

typedef char (*row_ptr)[3];
// I don't know how to express the following without a typedef
char (**image)[3] = new row_ptr[height];
...
for(i=0; i<height; i++)
{
    image[i] = new char[width][3];

    for(j=0; j<width; j++)
    {
        for(colour=0; colour<3; colour++)
        {
            in >> image[i][j][colour];
        }
    }
}

请注意,我切换了widthheight的位置,因此代码与文件中像素的顺序相匹配。对于坐标使用有意义的名称(如xy)也不错,而不是混淆ij等名称。

相关问题