很久之前看过一篇关于色彩平衡文章,在该文章中介绍了一种非常简单高效的
色彩平衡算法。下图是算法的演示效果(左边为处理后的图像,右边为处理前的图像)。
从图中可以看出算法有效的改善的图像的色彩,使得色彩更加的真实。
下面是实现代码
#include "stdafx.h"
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#pragma comment(lib, "cv.lib")
#pragma comment(lib, "cxcore.lib")
#pragma comment(lib, "highgui.lib")
void color_balance(IplImage *img)
{
int histo[256] = {0};
int num_of_pixels = img->width*img->height;
for(int y = 0; y < img->height; ++y)
{
uchar *data = (uchar*)(img->imageData + y*img->widthStep);
for(int x = 0; x < img->width; ++x)
{
histo[data[x]] += 1;
}
}
for(int i = 1; i < 256; ++i)
histo[i] = histo[i] + histo[i-1];
double s = 0.1;
int vmin = 0;
while (histo[vmin + 1] <= cvRound(num_of_pixels*s/2))
vmin = vmin + 1;
int vmax = 255 - 1;
while( histo[vmax - 1] > cvRound(num_of_pixels*(1 - s/2)))
{
vmax = vmax - 1;
}
if (vmax < 255 - 1)
vmax = vmax + 1;
for(int y = 0; y < img->height; ++y)
{
uchar *data = (uchar*)(img->imageData + y*img->widthStep);
for(int x = 0; x < img->width; ++x)
{
if(data[x] < vmin)
data[x] = vmin;
if(data[x] > vmax)
data[x] = vmax;
}
}
for(int y = 0; y < img->height; ++y)
{
uchar *data = (uchar*)(img->imageData + y*img->widthStep);
for(int x = 0; x < img->width; ++x)
{
data[x] = cvRound((data[x] - vmin)*255.0/(vmax - vmin));
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
IplImage *srcImg = cvLoadImage("D:\\colorbalance.jpg");
IplImage *dstImg = cvCreateImage(cvGetSize(srcImg), 8, 3);
IplImage *redCh = cvCreateImage(cvGetSize(srcImg), 8, 1);
IplImage *greenCh = cvCreateImage(cvGetSize(srcImg), 8, 1);
IplImage *blueCh = cvCreateImage(cvGetSize(srcImg), 8, 1);
cvSplit(srcImg, blueCh, greenCh, redCh, NULL);
color_balance(redCh);
color_balance(greenCh);
color_balance(blueCh);
cvMerge(blueCh, greenCh, redCh, NULL, dstImg);
cvNamedWindow("src", CV_WINDOW_AUTOSIZE);
cvShowImage("src", srcImg);
cvNamedWindow("dst", CV_WINDOW_AUTOSIZE);
cvShowImage("dst", dstImg);
cvWaitKey(0);
return 0;
}
本文转自博客园知识天地的博客,原文链接:一种简单的色彩平衡算法的OPENCV实现,如需转载请自行联系原博主。