function imgout = Gray_Axis_Alignment(imgin,ratio)
%功能:改程序实现了基于灰度轴调整的彩色图像的自动白平衡方法
%参考文献:基于灰轴调整的彩色图像自动白平衡 天津大学 2010
if nargin == 1
ratio = 0.005;
end
imgin = double(imgin);
[sizex,sizey,sizez] = size(imgin);
if sizez~=3
error('输入图像出现了错误');
end
%取出三通道
Ir = imgin(:,:,1);Ig = imgin(:,:,2);Ib = imgin(:,:,3);
imgout = zeros(sizex,sizey,sizez);
%获取亮度值
Limg = max(Ir,Ig);
Limg = max(Limg,Ib);
pixelvalue = reshape(Limg,1,sizex*sizey);
[~,index] = sort(pixelvalue,'descend');
num = ceil(sizex*sizey*ratio);
points = zeros(num,2);
for i=1:num
points(i,1) = rem(index(i),sizex);
if points(i,1) == 0
points(i,1) = sizex;
end
points(i,2) = ceil(index(i)/sizex);
end
%计算最大值的平均值
Re = 0; Ge = 0; Be = 0;
for i=1:num
Re = Re + Ir(points(i,1),points(i,2));
Ge = Ge + Ig(points(i,1),points(i,2));
Be = Be + Ib(points(i,1),points(i,2));
end
Re = Re/num; Ge = Ge/num;Be = Be/num;
OE = [Re,Ge,Be];
clear points num index
%实现坐标轴的旋转
OP = [255 255 255];
OZ = cross(OE,OP);%向量的叉乘
%第一步旋转
Rz = OZ(1);Gz = OZ(2); Bz = OZ(3);
sinphi = Gz/sqrt(Gz^2+Bz^2);cosphi = Bz/sqrt(Gz^2+Bz^2);
Mr = [1 0 0;0,cosphi,sinphi;0 -sinphi, cosphi];
clear sinphi cosphi
%第二步旋转
cosphi = sqrt(Gz^2+Bz^2)/norm(OZ,2);
sinphi = -Rz/norm(OZ,2);
Mg = [cosphi 0 -sinphi; 0 1 0; sinphi, 0 cosphi];
clear sinphi cosphi
%第三步旋转
cosphi = dot(OE,OP)/(norm(OE,2)*norm(OP,2));
sinphi = norm(OZ,2)/(norm(OE,2)*norm(OP,2));
Mb = [cosphi sinphi 0; -sinphi cosphi 0; 0 0 1];
%得到最后的矩阵
M = Mr*Mg*Mb*Mg'*Mr';
%计算beta
beta = norm(OP,2)/norm(OE,2);
%进行映射
for i = 1:sizex
for j = 1:sizey
temp = [Ir(i,j),Ig(i,j),Ib(i,j)]*M;
imgout(i,j,1) = beta*temp(1);
imgout(i,j,2) = beta*temp(2);
imgout(i,j,3) = beta*temp(3);
end
end
imgout = ceil(imgout);
imgout = uint8(imgout);
end
- 1
- 2
- 3
- 4
- 5
- 6
前往页