C语言实现24位彩色图像二值化

2022-07-21,,,

本文实例为大家分享了c语言实现24位彩色图像二值化的具体代码,供大家参考,具体内容如下

// huiduhua.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include<stdio.h>
#include<windows.h>
 
int _tmain(int argc, _tchar* argv[])
{
 
 bitmapfileheader bfhead;
 bitmapinfoheader bihead;
 rgbquad *pcolortable;
 unsigned char *pbmpbuf;
 file *fp1=fopen("鼠.bmp","rb");
 if(fp1==0)
  return 0;
 fread(&bfhead,14,1,fp1);   //将文件头读入内存
 fread(&bihead,40,1,fp1);   //将信息头读入内存
 int linebyte=(bihead.biwidth*24/8+3)/4*4; //保证每行字节数为4的整数倍
 
 pbmpbuf=new unsigned char[linebyte*bihead.biheight]; //为数据区分配内存空间
 fread(pbmpbuf,linebyte*bihead.biheight,1,fp1);       //将bmp数据区读入内存
 fclose(fp1); 
 
 printf("width:%d, height: %d,bibitcount:%d\n",bihead.biwidth,bihead.biheight,bihead.bibitcount);
 
 
 //现将真彩图灰度化
 int linebyte1=(bihead.biwidth*8/8+3)/4*4;  //由于灰度化后每像素位数变为8,所以每行字节数发生改变,但仍要求为4的整数倍
 file *fp2=fopen("鼠2.bmp","wb");
 if(fp2==0)
  return 0;
 //更改文件头,并将其保存
 bfhead.bfsize=14+40+sizeof(rgbquad)*256+linebyte1*bihead.biheight;   //更改文件大小
 bfhead.bfoffbits=14+40+sizeof(rgbquad)*256;   //更改偏移值
 fwrite(&bfhead,14,1,fp2);
 
 //更改信息头并将其保存
 bihead.bibitcount=8;    //更改每像素位数
 bihead.bisizeimage=linebyte1*bihead.biheight;  //更改数据区大小
 fwrite(&bihead,40,1,fp2);
 
 //因为灰度化图像有颜色表,所以创建颜色表并保存
 pcolortable=new rgbquad[256];
 for(int i=0;i<256;i++)
  pcolortable[i].rgbred = pcolortable[i].rgbgreen = pcolortable[i].rgbblue = i;//使颜色表中每种颜色的r,g,b分量相等且等于索引值
 fwrite(pcolortable,sizeof(rgbquad),256,fp2);
 
 //改变数据区
 unsigned char *pbmpbuf1;
 pbmpbuf1=new unsigned char[linebyte1*bihead.biheight];
 for(int i=0;i<bihead.biheight;i++)
  for(int j=0;j<bihead.biwidth;j++)
  {
   unsigned char *pb1,*pb2;
   pb1=pbmpbuf+i*linebyte+j*3;
   int y=*(pb1)*0.299+*(pb1+1)*0.587+*(pb1+2)*0.114;
   pb2=pbmpbuf1+i*linebyte1+j;
   *pb2=y;
  }
  //二值化方法一:阈值设为127,灰度值小于127的置零,其他的置为255;
 
 //for(int i=0;i<bihead.biheight;i++)
 // for(int j=0;j<bihead.biwidth;j++)
 // {
 //  unsigned char *pb;
 //  pb=pbmpbuf1+i*linebyte1+j;
 //  if(*pb<127)   //将每个像素值与127比较
 //   *pb=0;
 //  else
 //   *pb=255;
 // }
 //方法二:计算像素的平均值k,扫描图像的每个像素值如像素值大于k像素值设为255(白色),值小于等于k像素值设为0(黑色)
 int y=0;//像素和
 int k=0;//像素个数
 for(int i=0;i<bihead.biheight;i++)
  for(int j=0;j<bihead.biwidth;j++)
  {
   unsigned char *pb;
   pb=pbmpbuf1+i*linebyte1+j;
   y=y+*pb;  //计算所有像素灰度值之和
   k++;      //统计像素个数
  }
 y=y/k; //求像素平均值
 for(int i=0;i<bihead.biheight;i++)
  for(int j=0;j<bihead.biwidth;j++)
  {
   unsigned char *pb1;
   pb1=pbmpbuf1+i*linebyte1+j;
   if(*pb1<y)         //将每个像素值与平均值作比较
    *pb1=0;
   else
    *pb1=255;
  }

 fwrite(pbmpbuf1,linebyte1*bihead.biheight,1,fp2);
 fclose(fp2);

 system("pause");
 return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《C语言实现24位彩色图像二值化.doc》

下载本文的Word格式文档,以方便收藏与打印。