理方法中也十分有用,比如图像压缩和分割。
基本的原理:
Ni = 255*(N0 + N1 + N2 +……Ni)/(width*height)
程序流程:
1、统计各个像素值的个数
2、建立映射表
3、赋予新值
处理后图像:
源代码:
#include<cv.h> #include<highgui.h> int main(){ IplImage * image; image = cvLoadImage("E:\\image\\pollen.jpg",0); cvNamedWindow("image",CV_WINDOW_AUTOSIZE); //cvSaveImage("E:\\image\\pollen.jpg",image,0); cvShowImage("image",image); cvWaitKey(0); unsigned char * ptr; int count[256] = {0};//灰度值的个数 int map[256];//灰度映射表 int temp; if(image->nChannels == 3){ return 0; } else if(image->nChannels == 1){ //统计各个灰度值的个数 for(int i = 0 ; i < image->height;i++){ for(int j = 0; j< image->width;j++){ ptr = (unsigned char *)image->imageData + i*image->widthStep + j; count[*ptr]++; } } //建立映射表 for(int m = 0 ; m< 256 ; m++){ temp = 0; for(int n = 0 ; n<= m ;n++){ temp += count[n]; } map[m] = (unsigned char)(temp * 255/image->width/image->height); } //给图片赋予新值 for(int i = 0 ; i < image->height;i++){ for(int j = 0; j< image->width;j++){ ptr = (unsigned char *)image->imageData + i*image->widthStep +j; *ptr = map[*ptr]; } } } cvShowImage("image",image); cvWaitKey(0); cvSaveImage("E:\\image\\pollen2.jpg",image,0); return 0; }