算法原理
完美反射理论假设图像中最亮的点就是白点,并以此白点为参考对图像进行自动白平衡,最亮点定义为R+G+B的最大值。
算法过程
1.计算每个像素R,G,B之后,并保存
2.按照R+G+B的值的大小计算出其前10%或其他Ratio的白色参考点的阈值T
3.遍历图像中的每个点,计算其中R+G+B值大于T的所有点的R\G\B分量的累积和的平均值
4.将每个像素量化到[0, 255]
代码实现
//自动白平衡
int AutoBlance(Mat& src, Mat& dst)
{
int ret = PreDealSource(src, dst);
if (-1 == ret)
return -1;
vector<int>vHistRGB(767, 0);
uchar iMaxVal = 0;
int iSum = 0;
uchar utemp;
int nrows = src.rows;
int ncols = src.cols;
int jMax = ncols*src.channels();
int i = 0;
int j = 0;
for (i = 0; i < nrows; i++)
{
uchar *psrc = src.ptr<uchar>(i);
for (j = 0; j < jMax;)
{
iSum = 0;
utemp = psrc[j++];
iMaxVal = iMaxVal > utemp ? iMaxVal : utemp;
iSum += utemp;
utemp = psrc[j++];
iMaxVal = iMaxVal > utemp ? iMaxVal : utemp;
iSum += utemp;
utemp = psrc[j++];
iMaxVal = iMaxVal > utemp ? iMaxVal : utemp;
iSum += utemp;
vHistRGB[iSum]++;
}
}
iSum = 0;
int nsize = nrows*ncols;
int iThreshLimit = static_cast<int>(nsize*0.1);
int iThreshold = 0;
for (i = 766; i >= 0; i--)
{
iSum += vHistRGB[i];
if (iSum > iThreshLimit)
{
iThreshold = i;
break;
}
}
float AvgB = 0.0f;
float AvgG = 0.0f;
float AvgR = 0.0f;
int cnt = 0;
for (i = 0; i < nrows; i++)
{
uchar *psrc = src.ptr<uchar>(i);
for (j = 0; j < jMax; j+=3)
{
int sumP = static_cast<int>(psrc[j])+ static_cast<int>(psrc[j+1]) + static_cast<int>(psrc[j+2]);
if (sumP > iThreshold)
{
AvgB += static_cast<float>(psrc[j]);
AvgG += static_cast<float>(psrc[j + 1]);
AvgR += static_cast<float>(psrc[j + 2]);
cnt++;
}
}
}
AvgB = cnt*iMaxVal / AvgB;
AvgG = cnt*iMaxVal / AvgG;
AvgR = cnt*iMaxVal / AvgR;
for (i = 0; i < nrows; i++)
{
uchar *psrc = src.ptr<uchar>(i);
uchar *pdst = dst.ptr<uchar>(i);
for (j = 0; j < jMax;)
{
int Blue = static_cast<int>(psrc[j] * AvgB);
Blue = Blue > 255 ? 255 : Blue;
pdst[j] = static_cast<uchar>(Blue);
j++;
int Green = static_cast<int>(psrc[j] * AvgG);
Green = Green > 255 ? 255 : Green;
pdst[j] = static_cast<uchar>(Green);
j++;
int Red = static_cast<int>(psrc[j] * AvgR);
Red = Red > 255 ? 255 : Red;
pdst[j] = static_cast<uchar>(Red);
j++;
}
}
return 0;
}
#include<iostream>
#include <windows.h>
#include"ImageAlgorithm.h"
using namespace std;
/测试程序
void testAutoBalance()
{
Mat src = imread("E:\\AlgorithmImage\\autobalance2.jpg");
Mat dst;
int ret = AutoBlance(src, dst);
/*if (0 == ret)
{
imshow("src", src);
imshow("dst", dst);
waitKey(0);
}*/
}
//主函数
int main()
{
LARGE_INTEGER t1, t2, tc;
QueryPerformanceFrequency(&tc);
QueryPerformanceCounter(&t1);
// testGrayWorld();
testAutoBalance();
QueryPerformanceCounter(&t2);
printf("Use Time:%f\n", (t2.QuadPart - t1.QuadPart)*1.0 / tc.QuadPart);
system("pause");
return 0;
}
仿真条件
Opencv4.3.0
VS2015
CPU:AMD
图像处理效果及时间
Debug:0.152
Release:0.009
Debug:0.154
Release:0.009
参考文献
自动白平衡
: