# 色调映射

## Photographic 演算法[6]

### 步驟一　整個場景的亮度改變

${\displaystyle {\overline {L_{w}}}=\exp {({\frac {(\sum _{x,y}\log {(\delta +L_{w}(x,y))}}{N}})}}$

${\displaystyle \delta }$: 一個極小值，避免在算黑色像素的時候會遇到${\displaystyle \log =0}$的情況 算出場景中的關鍵值後，我們要將此關鍵值重新調整到中間值${\displaystyle \alpha }$，調整方法為

${\displaystyle L(x,y)={\frac {\alpha }{\overline {L_{w}}}}L_{w}(x,y)}$

${\displaystyle L_{d}(x,y)={\frac {L(x,y)(1+{\frac {L(x,y)}{{L_{white}}^{2}}})}{1+L(x,y)}}}$

### 步驟二 　局部區塊的亮度

${\displaystyle V_{i}(x,y,s)=L(x,y,)\otimes R_{i}(x,y,s)}$
${\displaystyle R_{i}(x,y,s)={\frac {1}{\pi (\alpha _{i}s)^{2}}}\exp {-{\frac {x^{2}+y^{2}}{(\alpha _{i}s)^{2}}}}}$

${\displaystyle V(x,y,s)={\frac {V_{1}(x,y,s)-V_{2}(x,y,s)}{2^{\phi }a/s^{2}+V_{1}(x,y,s)}}}$

${\displaystyle L_{d}(x,y)={\frac {L(x,y)}{1+V_{1}(x,y,s_{m}(x,y))}}}$

## 實作Photographic 演算法

function rgb = tonemap_p( hdr )
% HDR need be double format
%步驟1,調整整個場景的亮度
a = 0.6;%關鍵值設定
epsilon = 0.05;

%利用rgb計算照片亮度
lum_w = 0.27 * hdr(:,:,1) + 0.67 * hdr(:,:,2) + 0.06 * hdr(:,:,3);
image_size = size( hdr );
[height, width, channel] = size(hdr)
%計算L_w_bar(x,y)
sum_all = sum(sum(log(0.00000001+ lum_w)));

N = height * width;
lum_white = 1e20;
lum_w_bar = double( exp (sum_all / N) );

%計算L_d(x,y)
lum = a / lum_w_bar * lum_w;

lum_add1 = 1 + lum;
luma_d_1 = lum .* (1 + lum ./ lum_white ./ lum_white) ./lum_add1;

%步驟二：加亮與加深(Dodging & Burning)
phi = 8;
%計算兩個不同變異數大小的高斯函數
for i = 1: height
for j = 1: width
for k = 1: 8
s = 1 * 1.6 ^ k;
alpha1 = 0.35;
R1(i, j, k) = exp( -( i ^ 2 + j ^ 2) / ( alpha1 ) ^ 2 ) / ( pi * ( alpha1 * s ) ^ 2 );
alpha2 = 0.35 * 1.6;
R2(i, j, k) = exp( -( i ^ 2 + j ^ 2) / ( alpha2 ) ^ 2 ) / ( pi * ( alpha2 * s ) ^ 2 );
end
end
end
%將亮度與高斯函數做卷積
for k = 1: 8
V1(:,:,k) = conv2( lum_w, R1(:,:,k));
V2(:,:,k) = conv2( lum_w, R2(:,:,k));
end

%計算函數V(x, y, s)
for i = 1: height
for j = 1: width
for k = 1:8
V(i, j, k) = ( V1(i, j, k) - V2(i, j, k)) / (2 ^ phi * a / (k ^ 2) + V1(i, j, k));
end
end
end

%找尋符合V小於臨界值epsilon的scale
for i = 1: height
for j = 1: width
for k = 1:8
if abs(V(i, j, k)) < epsilon
V1_new(i, j) = V(i, j, k);
end
end
end
end

%計算新的亮度
for i = 1: height
for j = 1: width
lum_d2(i, j) = lum_w(i, j) / (1 + V1_new(i, j));
end
end

%將rgb影像轉到hsv的系統後,改變亮度大小,最後輸出成色調映射後的結果
hsv = rgb2hsv( hdr );
new_img = cat(3,hsv(:,:,1),hsv(:,:,2),lum_d2);
rgb = hsv2rgb( new_img);
end


## 参考文献

1. ^ Kate Devlin, Alan Chalmers, Alexander Wilkie, Werner Purgathofer. "STAR Report on Tone Reproduction and Physically Based Spectral Rendering" in Eurographics 2002. DOI: 10.1145/1073204.1073242
2. ^ Raanan Fattal, Dani Lischinski, Michael Werman. "梯度域高动态范围压缩"
3. ^ Rafal Mantiuk, Karol Myszkowski, Hans-Peter Seidel. "高动态范围图像对比度处理的感知架构"
4. ^ Alan Gilchrist. "An Anchoring Theory of Lightness Perception".
5. ^ Grzegorz Krawczyk, Karol Myszkowski, Hans-Peter Seidel. "高动态范围图像色调重现中的亮度感知"
6. ^ Reinhard, Erik, et al. "Photographic tone reproduction for digital images." ACM transactions on graphics (TOG) 21.3 (2002): 267-276.