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;
}


  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值