如何使用C编程中的代码将彩色图像转换为灰度图像?

时间:2019-01-24 10:44:06

标签: c

我正在编写一个C代码,用于将彩色位图图像转换为黑白位图图像。该代码可以编译并运行,没有任何错误,但是它不显示图像。 该代码不计算RGB值,而是使用阈值。

#include <stdio.h>
#define THRESHOLD 128
#define WHITE 255
#define BLACK 0

int main(){

FILE *fIn = fopen("lena_color.bmp","r");                //Input File name
FILE *fOut = fopen("b_w.bmp","w+");                 //Output File name

int i;
unsigned char byte[54];                             //to get the image header
unsigned char colorTable[1024];                     //to get the colortable

if(fIn==NULL)                                       // check if the input file has not been opened succesfully.
{                                       
    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 bitDepth from imageHeader 
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;                              //calculate image size

if(bitDepth<=8)                                     //if ColorTable present, extract it.
{
    fread(colorTable,sizeof(unsigned char),1024,fIn);
    fwrite(colorTable,sizeof(unsigned char),1024,fOut);
}

unsigned char buffer[size];                         //to store the image data

fread(buffer,sizeof(unsigned char),size,fIn);       //read image data

for(i=0;i<size;i++)                                 //store 0(black) and 255(white) values to buffer 
    {
        buffer[i] = (buffer[i] > THRESHOLD) ? 0 : 255;
    }

fwrite(buffer,sizeof(unsigned char),size,fOut);     //write back to the output image

fclose(fIn);
fclose(fOut);

return 0;
}

0 个答案:

没有答案