【发布时间】:2012-09-14 18:59:51
【问题描述】:
我正在尝试将 24 位位图图像转换为灰度。
#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
using namespace std;
class pixel{
public:
unsigned char b;
unsigned char g;
unsigned char r;
void display()
{
cout<<r<<" "<<g<<" "<<b<<" ";
}
}p1;
using namespace std;
int main(){
unsigned char avg;
fstream file("image.bmp",ios::binary|ios::in|ios::out);
int start;
file.seekg(10);
file.read((char*)&start,4);
file.seekg(start);
int i=0;
while(!file.eof()){
cout<<file.tellg();//Remove this and the program doesn't work!
file.read((char*)&p1,3);
avg=(p1.b+p1.g+p1.r)/3;
p1.b=avg;
p1.g=avg;
p1.r=avg;
file.seekg(-3,ios::cur);
file.write((char*)&p1,3);
}
file.close();
getch();
return 0;
}
当我删除 cout tellg 语句时,循环只运行两次!
我不明白删除 cout 语句有什么不同?
结果:只有一个像素变为灰度。
我在这里找到了我的问题的一个更简单的版本
Reading and writing to files simultaneously?
但是没有找到解决办法……
【问题讨论】:
-
请记住,人类不善于看到光谱的蓝色端。所以需要为此进行修改。
-
有关颜色问题,请参阅stackoverflow.com/questions/687261/…。但是不能帮助您解决当前的问题。
-
我总是对从我刚刚编写的同一流中的文件中读取文件保持警惕。我会尝试读取所有像素,将它们全部处理,然后将它们全部写入。我也不知道为什么它只会运行两次。
-
这会占用大量内存...接近 3-4 mb.bmp 文件已经太大了...如果您一个一个地处理每个像素,它只需要几个字节.. .
标签: c++ fstream bmp file-handling grayscale