假设有一幅图,由于成象时光照不足,使得整幅图偏暗(例如,灰度范围从0到63);或者成象时光照过强,使得整幅图偏亮(例如,灰度范围从200到255),我们称这些情况为低对比度,即灰度都挤在一起,没有拉开。灰度扩展的意思就是把你所感性趣的灰度范围拉开,使得该范围内的象素,亮的越亮,暗的越暗,从而达到了增强对比度的目的。
我们可以用下图来说明对比度扩展(contrast stretching)的原理:
图中的横坐标gold表示原图的灰度值,纵坐标gnew表示gold经过对比度扩展后得到了新的灰度值。a,b,c为三段直线的斜率,因为是对比度扩展,所以斜率b>1。g1old和g2old表示原图中要进行对比度扩展的范围,g1new和g2new表示对应的新值。用公式表示为:
实现代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma pack(1) //全紧凑模式
typedef struct {
unsigned char bfType[2];
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
}bitmapFileHeader;
typedef struct {
unsigned int biSize;
unsigned int biWidth;
unsigned int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
unsigned int biXPixPerMeter;
unsigned int biYPixPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
}bitmapInfoHeader;
typedef struct{
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
unsigned char rgbReserved;
}rgbQUAD;
typedef struct{
bitmapFileHeader bfHeader;
bitmapInfoHeader biHeader;
rgbQUAD palette[256];
unsigned char *imgData;
}bmp;
int main(){
FILE *fp;
if((fp=fopen("d:\Temp\\test_gray.bmp","rb"))==NULL){
perror("can not open file!");
return -1;
}
//读入彩色bmp图像文件头,信息头和图像数据
bitmapFileHeader bfHeader;
fread(&bfHeader,14,1,fp);
bitmapInfoHeader biHeader;
fread(&biHeader,40,1,fp);
int imSize=biHeader.biSizeImage;
int width=biHeader.biWidth;
int height=biHeader.biHeight;
int bitCount=biHeader.biBitCount;
int lineBytes=(width*bitCount+31)/32*4;
fseek(fp,bfHeader.bfOffBits,SEEK_SET);
unsigned char*imageData=(unsigned char*)malloc(imSize*sizeof(unsigned char));
fread(imageData,imSize*sizeof(unsigned char),1,fp);
fclose(fp);
bmp b;
memcpy(&(b.bfHeader),&bfHeader,sizeof(bfHeader));
memcpy(&(b.biHeader),&biHeader,sizeof(biHeader));
b.imgData=(unsigned char*)malloc(sizeof(unsigned char)*imSize);
memset(b.imgData,0,sizeof(unsigned char)*imSize);
for(int i=0;i<256;i++){
b.palette[i].rgbBlue=i;
b.palette[i].rgbGreen=i;
b.palette[i].rgbRed=i;
}
int i,j,temp;
double m=1.5,g1=100.0,g2=200.0; //m在这里对应斜率b,因为“b”这个符号被bmp图像结构名占了
double a=(255.0-m*(g2-g1))/(255.0-(g2-g1));
for(i=0;i<height;i++){
for(j=0;j<width;j++){
temp=imageData[lineBytes*i+j];
if(temp<g1)
b.imgData[lineBytes*i+j]=(unsigned char)(a*temp);
else if(temp<g2)
b.imgData[lineBytes*i+j]=(unsigned char)(g1+m*(temp-g1));
else
b.imgData[lineBytes*i+j]=(unsigned char)(g2+a*(temp-g2));
}
}
char savePath[]="D:\Temp\\save_test.bmp";
FILE *f_save=fopen(savePath,"wb");
if(f_save==NULL){
perror("can not open file!");
return -2;
}
fwrite(&b.bfHeader,sizeof(bitmapFileHeader),1,f_save);
fwrite(&b.biHeader,sizeof(bitmapInfoHeader),1,f_save);
fwrite(&b.palette,1024,1,f_save);
fwrite(b.imgData,sizeof(unsigned char)*b.biHeader.biSizeImage,1,f_save);
fclose(f_save);
free(imageData);
free(b.imgData);
getchar();
return 0;
}
代码效果:
原图像:
灰度(100-200)扩展图像: