算法原理
完美反射理論假設圖像中最亮的點就是白點,並以此白點爲參考對圖像進行自動白平衡,最亮點定義爲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
參考文獻
自動白平衡
: