【发布时间】:2019-06-07 23:34:06
【问题描述】:
我正在应用 C 中图像处理的基本教程,我在使用该程序将 RGB 转换为灰度时遇到问题,但输出图片以某种方式损坏,尽管代码运行没有错误,但我无法动手问题。代码如下。
FILE *fIn = fopen("tiger.bmp","rb"); //Input File name
FILE *fOut = fopen("tiger_gray.bmp","wb"); //Output File name
int i,j,y;
unsigned char byte[54];
if(fIn==NULL)
{
printf("File does not exist.\n");
}
for(i=0;i<54;i++) //read the 54 byte header from fIn
{
byte[i] = getc(fIn);
}
fwrite(byte,sizeof(unsigned char),54,fOut); //write the header back
// extract image height, width and bit Depth from image Header
int height = *(int*)&byte[18];
int width = *(int*)&byte[22];
int bitDepth = *(int*)&byte[28];
printf("width: %d\n",width);
printf("height: %d\n",height );
int size = height*width;
unsigned char buffer[size][3]; //to store the image data
for(i=0;i<size;i++) //RGB to gray
{
y=0;
buffer[i][2]=getc(fIn); //blue
buffer[i][1]=getc(fIn); //green
buffer[i][0]=getc(fIn); //red
y=(buffer[i][0]*0.3) + (buffer[i][1]*0.59) + (buffer[i][2]*0.11); //conversion formula of rgb to gray
putc(y,fOut);
putc(y,fOut);
putc(y,fOut);
}
fclose(fOut);
fclose(fIn);
【问题讨论】:
-
请将其转换为minimal reproducible example 并解释/显示“不知何故损坏”的含义。
-
getc()我怀疑是从图片中读取二进制数据的合适函数。阅读规范。更喜欢将二进制文件读写到缓冲区中。 -
您确定这是读取标题的正确方法吗?我得到一个带有
jpeg图像的height的负值? -
您没有注意到位图的每一行都必须填充为 4 个字节的倍数。
-
@FrancescoBoi 这是 BMP 特定代码,因此它不适用于 JPG。在 BMP 文件中,负高度表示像素是正面朝上而不是倒置存储的。
标签: c image-processing rgb grayscale