gpt4 book ai didi

C++读/写PPM图像文件变灰图像

转载 作者:行者123 更新时间:2023-11-28 05:16:33 26 4
gpt4 key购买 nike

我正在尝试编写一个程序来读取 ppm 图像,将它们存储为对象,然后再次将它们写出。理想情况下,我想将像素存储为 int 类型对象,但我什至只能使用字符获得相似的图像。不幸的是,即使使用 char 对象也会导致图像变灰。我不确定为什么更改存储类型会导致如此大的变化,或者为什么在保留形状时图像颜色会丢失。

我已经尝试浏览这里的无数其他 ppm 程序问题,但我无法确定他们答案的正反面(或者他们是否相关)。我对这种语言非常陌生,不知道会发生什么。

如果有人能解释我做错了什么,以及我可能用来以 int 格式而不是 char 格式存储数据的策略,我将不胜感激。

下面是我的 ppm 类的文件读取和文件写入代码,我的主要函数只是初始化一个 ppm 对象,调用 readfile(),然后调用 writefile()。其中某处无法保留图像。

void PPM::readFile(std::string filename)
{
std::ifstream file;
std::string stuff;
char junk;
file.open(filename, std::ios::binary);
file >> stuff >> width >> height >> maxCol;
file >> std::noskipws >> junk;
int i = 0;
char r, g, b;
std::cout << width*height;
while (i < width*height)
{
file.read(&r, 1);
file.read(&g, 1);
file.read(&b, 1);
red.push_back(b);
grn.push_back(b);
blu.push_back(b);
i++;
std::cout << i << std::endl;
}
}

void PPM::writeFile(std::string filename) const
{
std::ofstream file;
file.open(filename, std::ios::binary);
file << "P6 " << width << " " << height << " " << maxCol << std::endl;
int i = 0;
std::cout << width << " " << height;
while (i < width*height)
{
file.write(&red[i], sizeof(red[i]));
file.write(&grn[i], sizeof(grn[i]));
file.write(&blu[i], sizeof(blu[i]));
std::cout << "iteration " << i << std::endl;
i++;
}
}

再次感谢您提供的任何帮助

最佳答案

red.push_back(b);
grn.push_back(b);
blu.push_back(b);

这是错误。您需要分别推回 r、g 和 b。同时将 char 更改为 int,如以下评论中所指出的那样更安全。

关于C++读/写PPM图像文件变灰图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42524821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com