对BMP图像实行二值化处理

#include <stdio.h> 
#include <stdlib.h>
#include <conio.h>
#define ONE 255 
#define ZERO 0 
/*
typedef struct tagBITMAPFILEHEADER { // bmfh 
    WORD    bfType; 
    DWORD   bfSize; 
    WORD    bfReserved1; 
    WORD    bfReserved2; 
    DWORD   bfOffBits; 
} BITMAPFILEHEADER;
typedef struct tagBITMAPINFOHEADER{ // bmih 
    DWORD  biSize; 
    LONG   biWidth; 
    LONG   biHeight; 
    WORD   biPlanes; 
    WORD   biBitCount 
    DWORD  biCompression; 
    DWORD  biSizeImage; 
    LONG   biXPelsPerMeter; 
    LONG   biYPelsPerMeter; 
    DWORD  biClrUsed; 
    DWORD  biClrImportant; 
} BITMAPINFOHEADER;
*/
void main (int argc,char *argv[]) 
{ 
FILE *fi,*fo;//I/O file 
char fin[80],fon[80];//I/O file name 
unsigned char **ri,**ro;
unsigned char buff;
long w,h;
int t; 
int i,j; 
if(argc<3) 
{ 
printf("orginfile name:"); 
scanf("%s",fin); 
printf("resultfile name:"); 
scanf("%s",fon); 
}else{ 
sscanf(argv[1],"%s",fin); 
sscanf(argv[2],"%s",fon); 
} 
if(argc==4) 
sscanf(argv[4],"%d",&t); 
else{ 
printf("theshold [0,255]:"); 
scanf("%d",&t); 
} 

if (((fi=fopen(fin,"rb"))==NULL)||((fo=fopen(fon,"wb"))==NULL)) 
{ 
puts("\nfile open failed"); 
return; 
} 

fseek(fi,18L,SEEK_SET);
fread(&w,sizeof(long),1,fi);
fread(&h,sizeof(long),1,fi);

fseek(fi,0L,SEEK_SET);

ri=(unsigned char **)malloc(sizeof(unsigned *)*h);
for (i=0;i<h;i++)
*(ri+i)=(unsigned char *)malloc(sizeof(unsigned)*w);

ro=(unsigned char **)malloc(sizeof(unsigned *)*h);
for (i=0;i<h;i++)
*(ro+i)=(unsigned char *)malloc(sizeof(unsigned)*w);
//分配失败后果自负!

for (i=0;i<32;i++){
fread(&buff,sizeof(buff),1,fi);
fwrite(&buff,sizeof(buff),1,fo);}
for (i=0;i<h;i++) 
for (j=0;j<w;j++)
fread(*(ri+i)+j,sizeof(unsigned char),1,fi);

for (i=0;i<h;i++) 
for (j=0;j<w;j++) 
*(*(ro+i)+j)=((*(*(ri+i)+j)<=t)?ZERO:ONE);
for (i=0;i<h;i++) 
for (j=0;j<w;j++) 
fwrite(*(ro+i)+j,sizeof(unsigned char),1,fo);
fclose(fo); 
原文地址:https://www.cnblogs.com/djcsch2001/p/1960150.html