基于动态阈值的白平衡算法 照片校色

话不多说,原理见上一篇博客,结果耶很好,直接贴代码:


/*这个是基于动态阈值的自动白平衡算法做的照片颜色校正的程序*/
/*Automatic White Balance Method*/
/*输入包含照片名字的txt文本,输出加前缀的较色后的照片*/
/*时间:2015.8.24*/
#include   
#include   
#include 
#include 
#include 
#include   
#include   
#include   
using namespace std;
using namespace cv;
double baidianave(Mat frame,int n)
{  
	int a[256];
	for (int i=0;i<256;i++)
	{
		a[i]=0;
	}
	double sum=0;
	double ave;
	for (int i=0;i(0,i);
		a[d]++;
	}
	int n0=255;
	for (int k=255;k>0;k--)
	{
		sum+=a[k];
		if (sum>frame.rows*frame.cols/10)
		{
			break;
		}
		n0--;
	}
	sum=0;
	for (int i=n0;i<256;i++)
	{
		sum+=a[i]*i;
	}
	ave=sum/(frame.rows*frame.cols/10);
	return ave;
}
double baidianave(Mat frame)
{ 
	int a[256];
//cvZero(a);
	for (int i=0;i<256;i++)
	{
		a[i]=0;
	}
	double sum=0;
	double ave;
	for (int i=0;i(i,j);
			a[d]++;
		}
	}

	int n0=255;
	for (int k=255;k>0;k--)
	{
		sum+=a[k];
		if (sum>frame.rows*frame.cols/10)
		{
			break;
		}
		n0--;
	}
	sum=0;
	for (int i=n0;i<256;i++)
	{
		sum+=a[i]*i;
	}
	ave=sum/(frame.rows*frame.cols/10);
	return ave;

}


int main(int argc, char* argv[])
{
	if (2 != argc) 
	{
	cout << "Please enter the image list!" <  file_names;
	FILE *file_list =  fopen(argv[1],"r");
	char buf[255];
	memset(&buf,0,sizeof(buf));

	while(fgets(buf,255,file_list))
	{
	if(buf[strlen(buf)-1] == '\n') 
	    buf[strlen(buf)-1] = '\0';
	file_names.push_back(string(buf));

	}

	fclose(file_list);
	int count = file_names.size();
	for(int  i=0; iybr(imageYCrCb.channels());
		split(imageYCrCb,ybr);

		Mat imageb=Mat::zeros(frame.size(), CV_8UC1);
		Mat imagec=Mat::zeros(frame.size(), CV_8UC1);
		ybr[1].copyTo(imageb);
		ybr[2].copyTo(imagec);
		Mat  savg,sfangcha;//全局scalar 变量用来放平均值和方差
		meanStdDev(ybr[2],savg,sfangcha);
		Mb=savg.at(0);
		Db=sfangcha.at(0);//求出第一部分cb的均值和均方差
		meanStdDev(ybr[1],savg,sfangcha);
		Mr=savg.at(0);
		// cout<<"Mr:  "<(0);;//求出第一部分cr的均值和均方差
		// cout<<"Dr:  "<(i,j)-b)<(1.5*Db))&&((ybr[1].at(i,j)-c)<(1.5*Dr)))
				{
		 	
					double d1=frame.at(i,j)[0];
					Bbaidian.at(0,n1)=d1;
					
					double d2=frame.at(i,j)[1];
					Gbaidian.at(0,n1)=d2;
				
					double d3=frame.at(i,j)[2];
					Rbaidian.at(0,n1)=d3;
					n1++;
				}
			}
		}

	
		double Bave1=baidianave(Bbaidian,n1);
		double Gave1=baidianave(Gbaidian,n1);
		double Rave1=baidianave(Rbaidian,n1);
		// cout<<"Bave1:  "<(i,j)[0];
				int tg=Ggain1*frame.at(i,j)[1];
				int tr=Rgain1*frame.at(i,j)[2];
				if (tb>255)
				{
					tb=255;
				}
				if (tg>255)
				{
					tg=255;
				}
				if (tr>255)
				{
					tr=255;
				}				
				frame.at(i,j)[0]=tb;
				frame.at(i,j)[1]=tg;
				frame.at(i,j)[2]=tr;
			}
		}
		imwrite(img_mask.c_str(),frame);		
		cout<<"Finish!"<


你可能感兴趣的:(opencv)