Algorithm Search⌘K

Algorithmcore

Reinhard tone mapping operator

Also called photographic tone reproduction, Reinhard operator.

Scale luminance so that the log average maps to a key such as 0.18, then compress it with L/(1+L) or a white point curve. An optional local step adds dodging and burning.

Time
Θ(p) globalΘ(p s) local
Space
Θ(p r) extra
Where
p = the number of pixels; r = the number of scales of the local operator; s = the largest scale in pixels
Properties
deterministicnot in placeofflineiterative
Origin
Erik Reinhard, Michael Stark, Peter Shirley, James Ferwerda, 2002

The Reinhard operator maps the luminance of a high dynamic range image to display values in [0,1][0, 1]. It first sets the exposure so that the log average luminance of the image maps to a mid gray value, the key aa, which is 0.180.18 by default. Then it compresses each scaled luminance LL with the curve L/(1+L)L / (1 + L), which is close to linear for dark values and squeezes bright values toward 1, or with a variant that maps a chosen white point to exactly 1. An optional local step divides by a blurred luminance in place of LL, with a blur size picked per pixel, which copies the dodging and burning of a photographic print. Reinhard, Stark, Shirley and Ferwerda published it in 2002. It is one method for the tone mapping problem, and its global form is one of the most used tone curves in games and renderers.

In plain words

A rendered or photographed scene can be millions of times brighter in the sun than in the shadows, but a screen shows only a small range. The method works like a photographer. First it measures the typical brightness of the image and scales the whole image so that this typical brightness becomes a middle gray. Then it bends the brightness scale. Dark and middle values stay almost as they are, and very bright values are pushed together just below white, so they never clip hard.

The optional second part looks at the neighborhood of each pixel. It finds the largest area around each pixel where the brightness is nearly even, and uses the average of that area to set the compression. A pixel that is darker than its surroundings gets a little darker, and one that is brighter gets a little brighter, so edges and details stay visible.

The problem

The input is an image of pp pixels with world luminances Lw(i)≥0L_w(i) \ge 0 in linear units, and a key a>0a > 0. The output is a display luminance Ld(i)∈[0,1]L_d(i) \in [0, 1] per pixel, in linear values, which a later step encodes for the display (see gamma correction). A color image is first reduced to luminance. The paper uses Lw=0.27R+0.67G+0.06BL_w = 0.27 R + 0.67 G + 0.06 B; the Rec. 709 weights 0.2126,0.7152,0.07220.2126, 0.7152, 0.0722 are a common choice in other code. A common way to carry the result back to color scales each linear color by Ld/LwL_d / L_w, which keeps the ratios of the channels; this step is not part of the paper.

The method has two parts with different status. The log average, the scaling and the compression curve are exact formulas, and their properties below are proved. The choice of the key a=0.18a = 0.18, the curve itself, the constants of the local step and the claim that the result looks like a good print are a visual heuristic and tuning, taken from film photography.

The algorithm

Lines L1 to L5 are the global operator. WW is the white point: the smallest scaled luminance that maps to 1. W=∞W = \infty gives the plain curve L/(1+L)L / (1 + L). Lines L6 to L14 are the local operator. BkB_k is the scaled image blurred by a Gaussian of width α1sk\alpha_1 s_k, where sk=1.6ks_k = 1.6^k is the scale in pixels and α1=1/(22)≈0.35\alpha_1 = 1 / (2 \sqrt 2) \approx 0.35. The surround of scale kk has the width α2sk\alpha_2 s_k with α2=1.6 α1\alpha_2 = 1.6\, \alpha_1, which is the center of scale k+1k + 1, so the method needs only r+1r + 1 blurs for rr scales. δ\delta is a small constant, for example 10−610^{-6}, that keeps log⁡0\log 0 out of black pixels.

  1. REINHARD-GLOBAL(Lw[1..p], a, W)
  2. 1Lbar ← exp((1/p) · Σi log(δ + Lw[i])) ▷ the log average
  3. 2for each pixel i
  4. 3L ← (a / Lbar) · Lw[i] ▷ the exposure
  5. 4Ld[i] ← L · (1 + L / W²) / (1 + L) ▷ L / (1 + L) when W = ∞
  6. 5return Ld
  7. REINHARD-LOCAL(Lw[1..p], a, φ, ε, r)
  8. 6compute Lbar as in L1; L[i] ← (a / Lbar) · Lw[i] for each pixel i
  9. 7for k ← 0 to r: Bk ← L blurred by a Gaussian of width α1 · 1.6^k
  10. 8for each pixel i
  11. 9m ← 0
  12. 10for k ← 0 to r - 1
  13. 11V ← (Bk[i] - Bk+1[i]) / (a · 2^φ / sk² + Bk[i])
  14. 12if |V| ≥ ε then leave the loop of L10, else m ← k
  15. 13Ld[i] ← min(1, L[i] / (1 + Bm[i]))
  16. 14return Ld

Line L1 is the geometric mean of δ+Lw\delta + L_w. Line L3 maps a pixel with the log average luminance to aa. Line L4 is the curve of the paper with the white point; the paper sets WW by default to the largest value of LL in the image, so that the brightest pixel maps to exactly 1.

Line L7 uses the Gaussian R(x,y,s)=e−(x2+y2)/(αs)2/(π(αs)2)R(x, y, s) = e^{-(x^2 + y^2) / (\alpha s)^2} / (\pi (\alpha s)^2) of the paper. It is separable, so each blur is a row pass and a column pass of a 1D kernel (see separable filter and Gaussian filter). Line L11 is the normalized center-surround difference, a difference of Gaussians. The division by BkB_k makes the test independent of the absolute luminance. The term a 2φ/sk2a\, 2^\varphi / s_k^2 keeps VV from growing large when BkB_k is near 0; it is large at small scales, so the first scales almost always pass. Line L12 goes up from the smallest scale while the center and the surround agree to within ε\varepsilon, and keeps the last scale that passes: the largest area around the pixel with no large change of contrast. Line L13 is the global curve with BmB_m in place of LL in the denominator. It can exceed 1 at very bright pixels, so the paper clips it.

The paper uses φ=8\varphi = 8, ε=0.05\varepsilon = 0.05 and 8 scales that grow by a factor of 1.6, and gives their range as 1 to 43 pixels. It also gives a list of keys for low key and high key scenes: 0.0450.045, 0.090.09, 0.180.18, 0.360.36 and 0.720.72. All of these are tuning.

Example

The global operator. The image has five pixels with Lw=0.01,0.1,1,10,100L_w = 0.01, 0.1, 1, 10, 100. With δ=0\delta = 0 the log average is Lˉ=(0.01⋅0.1⋅1⋅10⋅100)1/5=1\bar L = (0.01 \cdot 0.1 \cdot 1 \cdot 10 \cdot 100)^{1/5} = 1, so with a=0.18a = 0.18 the scaled values are L=0.18LwL = 0.18 L_w.

LwL_w LL L/(1+L)L / (1 + L) white point W=18W = 18
0.01 0.0018 0.00180 0.00180
0.1 0.018 0.01768 0.01768
1 0.18 0.15254 0.15263
10 1.8 0.64286 0.64643
100 18 0.94737 1.00000

Four orders of magnitude of input fit in [0,1)[0, 1). The two darkest pixels are nearly unchanged, because L/(1+L)≈LL / (1 + L) \approx L for small LL. The check values of the plain curve: L=1L = 1 maps to 0.50.5 and L=3L = 3 maps to 0.750.75. The last column sets WW to the largest LL, the default of the paper: the brightest pixel maps to exactly 1, and the change from the plain curve is small for the other pixels. With δ=10−6\delta = 10^{-6} the log average becomes 1.0000221.000022 and the values change by less than 10−510^{-5}.

The local operator. The image is 32 by 32 pixels. The left half (columns 0 to 15) has Lw=0.05L_w = 0.05 and the right half has Lw=5L_w = 5. The log average is 0.50.5 (with δ=10−6\delta = 10^{-6}, 0.5000050.500005), so the scaled values are 0.0180.018 and 1.81.8, and the global operator gives 0.01770.0177 and 0.64290.6429. For the pixel in row 16 and column 19, three pixels right of the step, lines L10 to L12 compute:

kk sks_k width α1sk\alpha_1 s_k BkB_k Bk+1B_{k+1} a 2φ/sk2a\,2^\varphi / s_k^2 VV result
0 1 0.354 1.8000 1.8000 46.08 0.0000 pass, m=0m = 0
1 1.6 0.566 1.8000 1.8000 18.00 0.0000 pass, m=1m = 1
2 2.56 0.905 1.8000 1.7996 7.031 0.0000 pass, m=2m = 2
3 4.096 1.448 1.7996 1.7732 2.747 0.0058 pass, m=3m = 3
4 6.554 2.317 1.7732 1.6403 1.073 0.0467 pass, m=4m = 4
5 10.49 3.707 1.6403 1.4410 0.419 0.0968 stop

The surround of scale 5 reaches across the step, so VV goes above ε=0.05\varepsilon = 0.05 and the pixel keeps m=4m = 4. Line L13 gives Ld=1.8/(1+1.7732)=0.6491L_d = 1.8 / (1 + 1.7732) = 0.6491, a little brighter than the global 0.64290.6429, because the neighborhood includes some dark pixels. Right at the step, the dark pixel in column 15 maps to 0.00970.0097 in place of 0.01770.0177, and the bright pixel in column 16 to 0.91740.9174 in place of 0.64290.6429. Far from the step the result is close to the global one: the pixel in column 31 gives 0.64290.6429. The operator raises the contrast across the edge, which is the dodging and burning effect.

Correctness

The proofs are in the proofs folder. The global operator has these proved properties, in exact arithmetic:

  • Lˉ\bar L is the geometric mean of δ+Lw\delta + L_w, and a constant image maps every pixel to aa before the curve.
  • With δ=0\delta = 0, multiplying all inputs by any c>0c > 0 does not change the output. The operator removes the exposure of the input.
  • The curve g(L)=L(1+L/W2)/(1+L)g(L) = L (1 + L / W^2) / (1 + L) is strictly increasing, with g(0)=0g(0) = 0 and g(W)=1g(W) = 1. For W=∞W = \infty it stays below 1. So the operator keeps the order of the pixels, and with WW equal to the largest LL no output exceeds 1. For L>WL > W the curve goes above 1, so a smaller WW needs a clip.

For the local operator: the two 1D passes give exactly the 2D convolution with the truncated and normalized Gaussian, the selected index is the largest kk such that all tests up to kk pass, the output is in [0,1][0, 1], and on a constant image every VV is 0 and the result equals the global operator. A pixel with Bm>LB_m > L maps below the global value and a pixel with Bm<LB_m < L above it, before the clip.

None of this proves that the image looks right. That part is the heuristic of the paper, judged by viewing.

Proof: Properties of the Reinhard operatorfull

Setting. The input is an image of pp pixels with world luminances Lw(i)≥0L_w(i) \ge 0, a constant δ≥0\delta \ge 0 with δ+Lw(i)>0\delta + L_w(i) > 0 for every ii, and a key a>0a > 0. Lines L1 to L5 compute

Lˉ=exp⁡(1p∑ilog⁡(δ+Lw(i))),L(i)=aLˉLw(i),Ld(i)=g(L(i)),\bar L = \exp\Big(\frac1p \sum_i \log(\delta + L_w(i))\Big), \qquad L(i) = \frac{a}{\bar L} L_w(i), \qquad L_d(i) = g(L(i)),

with g(L)=L(1+L/W2)/(1+L)g(L) = L (1 + L / W^2) / (1 + L) for a white point W>0W > 0, or g(L)=L/(1+L)g(L) = L / (1 + L) for W=∞W = \infty. Lines L6 to L14 compute the local operator. The claims are about this computation in exact arithmetic. They do not claim that the output matches what a person sees: that part of the method is a visual heuristic.

Claim 1 (the log average). Lˉ\bar L is the geometric mean of the values δ+Lw(i)\delta + L_w(i). If δ=0\delta = 0 and all Lw(i)=c>0L_w(i) = c > 0, then Lˉ=c\bar L = c and every L(i)=aL(i) = a.

Proof. exp⁡(1p∑log⁡xi)=(∏xi)1/p\exp(\frac1p \sum \log x_i) = (\prod x_i)^{1/p}, because exp⁡\exp turns the sum of logarithms into a product. For a constant image the product is cpc^p, so Lˉ=c\bar L = c and L(i)=ac/c=aL(i) = a c / c = a. □\square

Claim 2 (exposure invariance). If δ=0\delta = 0 and all Lw(i)>0L_w(i) > 0, then the global operator gives the same output for the inputs LwL_w and cLwc L_w, for every c>0c > 0.

Proof. The geometric mean of cLw(i)c L_w(i) is cLˉc \bar L, so L(i)=a cLw(i)/(cLˉ)L(i) = a\, c L_w(i) / (c \bar L) is the same value as before, and so is g(L(i))g(L(i)). □\square

For δ>0\delta > 0 the claim holds only up to the change of δ\delta relative to the luminances. The paper adds δ\delta only to avoid log⁡0\log 0 at black pixels.

Claim 3 (the curve). For W=∞W = \infty, gg is strictly increasing on [0,∞)[0, \infty), g(0)=0g(0) = 0 and g(L)<1g(L) < 1 for every LL. For W<∞W < \infty, gg is strictly increasing on [0,∞)[0, \infty), g(W)=1g(W) = 1, g(L)<1g(L) < 1 for L<WL < W and g(L)>1g(L) > 1 for L>WL > W. For every fixed L≥0L \ge 0, gg with white point WW tends to L/(1+L)L / (1 + L) as W→∞W \to \infty.

Proof. L/(1+L)=1−1/(1+L)L / (1 + L) = 1 - 1 / (1 + L) is strictly increasing and is below 1. The factor 1+L/W21 + L / W^2 is positive and increasing, so the product of the two factors is strictly increasing on [0,∞)[0, \infty), where both are not negative and the first is strictly increasing. At L=WL = W,

g(W)=W(1+1/W)1+W=W+11+W=1.g(W) = \frac{W (1 + 1 / W)}{1 + W} = \frac{W + 1}{1 + W} = 1.

Strict monotonicity then gives the two inequalities. The limit holds because L/W2→0L / W^2 \to 0. □\square

So the global operator keeps the order of the pixels: Lw(i)<Lw(j)L_w(i) < L_w(j) implies Ld(i)<Ld(j)L_d(i) < L_d(j), because LL is a positive multiple of LwL_w and gg is strictly increasing. With WW set to the largest value of LL, the brightest pixel maps to exactly 1 and no pixel goes above 1.

Claim 4 (the separable blur). Let K(x,y)=c e−(x2+y2)/w2K(x, y) = c\, e^{-(x^2 + y^2) / w^2} on the square ∣x∣,∣y∣≤R|x|, |y| \le R, scaled to sum to 1, and let the image be extended by clamping at the border. Then two 1D passes with the 1D kernel k(t)=e−t2/w2/∑∣u∣≤Re−u2/w2k(t) = e^{-t^2 / w^2} / \sum_{|u| \le R} e^{-u^2 / w^2}, first along the rows and then along the columns, give the 2D convolution with KK.

Proof. e−(x2+y2)/w2=e−x2/w2e−y2/w2e^{-(x^2 + y^2) / w^2} = e^{-x^2 / w^2} e^{-y^2 / w^2}, and the sum over the square is the product of the two 1D sums, so K(x,y)=k(x)k(y)K(x, y) = k(x) k(y). Clamping is done separately in xx and in yy: the pixel at (x+dx,y+dy)(x + d_x, y + d_y) after clamping is the pixel at the clamped column and the clamped row. Then

∑dyk(dy)∑dxk(dx) I(clx(x+dx),cly(y+dy))=∑dx,dyK(dx,dy) I(clx(x+dx),cly(y+dy)).\sum_{d_y} k(d_y) \sum_{d_x} k(d_x)\, I(\mathrm{cl}_x(x + d_x), \mathrm{cl}_y(y + d_y)) = \sum_{d_x, d_y} K(d_x, d_y)\, I(\mathrm{cl}_x(x + d_x), \mathrm{cl}_y(y + d_y)).

The inner sum is the row pass and the outer sum is the column pass. □\square

Equation 5 of the paper has the factor 1/(π(αs)2)1 / (\pi (\alpha s)^2), which makes the kernel integrate to 1 over the plane. On a pixel grid and after the cut at radius RR the discrete sum is not exactly 1, so the code divides by the sum. Then a constant image stays constant, which Claim 5 uses.

Claim 5 (the local operator). (a) The scale index mm that lines L9 to L12 select is in {0,…,r−1}\{0, \dots, r - 1\}, and it is the largest kk such that ∣Vj∣<ε|V_j| < \varepsilon for all j≤kj \le k, or 0 if ∣V0∣≥ε|V_0| \ge \varepsilon. (b) The output is in [0,1][0, 1]. (c) If Bm(i)>L(i)B_m(i) > L(i), then Ld(i)<L(i)/(1+L(i))L_d(i) < L(i) / (1 + L(i)), and if Bm(i)<L(i)B_m(i) < L(i), then Ld(i)>L(i)/(1+L(i))L_d(i) > L(i) / (1 + L(i)), before the clip to 1. (d) On a constant image every VkV_k is 0, m=r−1m = r - 1, and the local operator equals the global operator with W=∞W = \infty.

Proof. (a) mm starts at 0, and line L12 sets m←km \leftarrow k only while every earlier test passed, because the loop stops at the first failure. (b) Each BkB_k is a weighted average of values L≥0L \ge 0 with weights that are not negative, so Bk≥0B_k \ge 0, and L/(1+Bm)≥0L / (1 + B_m) \ge 0; the clip gives at most 1. (c) x↦L/(1+x)x \mapsto L / (1 + x) is strictly decreasing for L>0L > 0. (d) By Claim 4 and the normalization, each blur of the constant LL is LL, so Vk=0<εV_k = 0 < \varepsilon for every kk, the loop never stops early, m=r−1m = r - 1, and Ld=L/(1+L)L_d = L / (1 + L), which is below 1, so the clip does nothing. □\square

Part (c) is the dodging and burning of the paper: a pixel darker than its neighborhood is pushed down and a pixel brighter than its neighborhood is pushed up, so local contrast increases. Which neighborhood is "right" is a visual heuristic of the paper, with ε\varepsilon and φ\varphi as tuning.

Cost. Lines L1 to L5 take Θ(p)\Theta(p) time and Θ(p)\Theta(p) space for the output. In the local operator, the scale loop of lines L8 to L12 does at most rr tests per pixel, O(pr)O(p r) in total. The r+1r + 1 blurs dominate. The separable blur of width ww costs Θ(pw)\Theta(p w), so the direct method costs Θ(p∑k1.6k)=Θ(p smax⁡)\Theta(p \sum_k 1.6^k) = \Theta(p\, s_{\max}), where smax⁡s_{\max} is the largest scale. With an FFT each blur costs O(plog⁡p)O(p \log p), for O(rplog⁡p)O(r p \log p) in total. With a blur of constant cost per pixel, for example a recursive filter or a pyramid, the total is O(pr)O(p r). The memory is Θ(pr)\Theta(p r) if all blurs are kept, or Θ(p)\Theta(p) if the scales are processed one after the other and each pixel keeps its current state.

Complexity

The model is the real RAM, with pp pixels and rr scales. The global operator reads each pixel twice: Θ(p)\Theta(p) time and Θ(p)\Theta(p) space for the output, or O(1)O(1) extra space if it writes in place. On a GPU the log average is a reduction, often done with a chain of smaller and smaller images (see mipmap).

In the local operator, the scale tests of lines L8 to L12 cost O(pr)O(p r). The blurs of line L7 dominate, and their cost depends on how they are computed. A direct separable blur of width ww costs Θ(pw)\Theta(p w), so all r+1r + 1 blurs cost Θ(p∑k1.6k)=Θ(ps)\Theta(p \sum_k 1.6^k) = \Theta(p s), where ss is the largest scale: the widths grow geometrically, so the largest one dominates the sum. The paper computes the blurs with an FFT, at O(plog⁡p)O(p \log p) each, for O(rplog⁡p)O(r p \log p). A blur of constant cost per pixel, for example a recursive Gaussian filter or an image pyramid, gives Θ(pr)\Theta(p r) in total. The memory is Θ(pr)\Theta(p r) to keep all blurs, or Θ(p)\Theta(p) if the scales are done in order and each pixel keeps its current state.

Properties

  • Global form is a fixed curve. After the exposure, every pixel uses the same curve, so the operator is cheap, monotone and has no halos.
  • Exposure invariant. The output depends only on the ratios of the luminances to their log average.
  • Soft shoulder. L/(1+L)L / (1 + L) has slope 1 at 0 and slope 1/(1+L)21 / (1 + L)^2 at LL, so contrast in bright areas drops fast. Very bright regions lose detail, and the white point form helps only near WW.
  • Local form raises local contrast. The local step keeps detail near edges, at the cost of r+1r + 1 blurs and with the risk of dark rings around bright areas if the selected scales are too large.
  • Luminance only. The operator maps luminance. How color is restored is a separate choice.

Variants and improvements

  • Per channel. Many real-time renderers apply x/(1+x)x / (1 + x) to each of R, G and B after the exposure. It is simpler, but it changes the hue and makes bright colors go toward white, while the luminance form keeps the channel ratios.
  • White point on luminance. The form of line L4 with a fixed WW is often called extended Reinhard. A WW below the largest LL clips the brightest areas on purpose.
  • Fixed or slowly changing exposure. In real time the log average of the last frames is smoothed over time to imitate the adaptation of the eye. The rate is tuning.
  • Other local operators. The bilateral filter operator of Durand and Dorsey, from the same year, splits the log luminance into a base and a detail layer with a bilateral filter. Pyramid methods work on a Laplacian pyramid.
  • Filmic curves. Games often replace L/(1+L)L / (1 + L) by fitted curves with a toe and a shoulder, such as the Hable curve and fits of the ACES curve. These are tuning, see tone mapping.

When to use it

Use the global form as a simple, monotone and stable default for real-time and offline images, and when the output must keep the order of brightness. Choose the key for the scene: lower for dark scenes, higher for bright ones. Use the white point form when the brightest areas must reach white. Use the local form for still images with a very high dynamic range, such as interiors with windows, when detail in both the dark and the bright parts matters more than speed. For a film look, use a filmic curve in place of the plain curve.

Pitfalls

  • Tone mapping in sRGB values. The operator needs linear luminance. Apply it before the encoding for the display, and do not apply it to values that are already gamma encoded.
  • No δ\delta. One black pixel makes log⁡0\log 0 undefined and the log average 0. Add a small δ\delta or skip black pixels.
  • Outliers in the log average. A large black border or a few very bright pixels move the exposure of the whole image. Mask the border or clamp the values that enter line L1.
  • Values above WW. For L>WL > W, line L4 gives values above 1. Clip, or set WW to the largest LL.
  • Color shifts. Scaling each channel by Ld/LwL_d / L_w can push one channel above 1 for saturated bright colors. Clip each channel or desaturate toward white.
  • Normalizing the kernel. The paper's Gaussian integrates to 1 on the plane, but its sum on a pixel grid with a cut radius does not. Divide by the sum, or a constant image does not stay constant and the scale test is biased.
  • The order of the scale test. The paper states the rule as taking the first scale, from the lowest, where ∣V∣<ε|V| < \varepsilon. Read literally, this almost always takes the smallest scale, because the term a 2φ/s2a\, 2^\varphi / s^2 makes VV small there, and the local operator then reduces to the global one. The code of this page goes up while the test passes and keep the last scale that passes, which matches the stated aim of the largest even area.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

reinhard_tone_mapping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reinhard-tone-mapping/. The authors are listed in prov/FX4QEZ.jsonl.

"""The photographic tone reproduction operator of Reinhard, Stark, Shirley and Ferwerda (2002).

An image is a list of rows of world luminances Lw >= 0. The global operator
scales the image so that its log average luminance maps to the key a, and
then compresses each scaled value L with L (1 + L / Lwhite^2) / (1 + L).
The local operator replaces L in the denominator by a Gaussian average of L
over a neighborhood. It selects the size of the neighborhood per pixel from
a set of center-surround differences of Gaussians.

Constants of the paper: luminance 0.27 R + 0.67 G + 0.06 B, the key 0.18,
phi = 8, epsilon = 0.05, alpha1 = 1 / (2 sqrt 2), a ratio of 1.6 between
scales, and 8 scales. The key, phi and epsilon are tuning, not physics.
"""

import math

ALPHA1 = 1.0 / (2.0 * math.sqrt(2.0))
RATIO = 1.6


def luminance(rgb: tuple[float, float, float]) -> float:
    """The luminance weights that the paper uses."""
    r, g, b = rgb
    return 0.27 * r + 0.67 * g + 0.06 * b


def log_average(lw: list[list[float]], delta: float = 1e-6) -> float:
    """Equation 1: exp of the mean of log(delta + Lw) over all pixels."""
    total = 0.0
    count = 0
    for row in lw:
        for x in row:
            total += math.log(delta + x)
            count += 1
    return math.exp(total / count)


def compress(l: float, l_white: float | None = None) -> float:
    """Equation 4, or Equation 3 when l_white is None (an infinite Lwhite)."""
    if l_white is None:
        return l / (1.0 + l)
    return l * (1.0 + l / (l_white * l_white)) / (1.0 + l)


def scale_image(lw: list[list[float]], key: float, delta: float) -> list[list[float]]:
    """Equation 2: L = (a / Lbar) Lw."""
    lbar = log_average(lw, delta)
    return [[key * x / lbar for x in row] for row in lw]


def reinhard_global(
    lw: list[list[float]],
    key: float = 0.18,
    l_white: float | str | None = None,
    delta: float = 1e-6,
) -> list[list[float]]:
    """The global operator. l_white is a number, None (Equation 3) or "max".

    With "max", Lwhite is the largest scaled luminance of the image, the
    default of the paper, so the brightest pixel maps to exactly 1.
    """
    lbar = log_average(lw, delta)  # @line L1
    scaled = []
    for row in lw:  # @line L2
        scaled.append([key * x / lbar for x in row])  # @line L3
    if l_white == "max":
        l_white = max(max(row) for row in scaled)
    if l_white is not None and l_white <= 0.0:
        l_white = None
    out = [[compress(l, l_white) for l in row] for row in scaled]  # @line L4
    return out  # @line L5


def gaussian_kernel(width: float) -> list[float]:
    """The 1D factor of Equation 5, sampled at integer offsets and normalized.

    R(x, y, s) = exp(-(x^2 + y^2) / (alpha s)^2) / (pi (alpha s)^2) is the
    product of two 1D Gaussians. The kernel is cut at 3 alpha s and scaled
    to sum to 1, so a constant image stays constant.
    """
    radius = max(1, math.ceil(3.0 * width))
    taps = [math.exp(-(t * t) / (width * width)) for t in range(-radius, radius + 1)]
    total = sum(taps)
    return [w / total for w in taps]


def blur(img: list[list[float]], width: float) -> list[list[float]]:
    """Equation 6 as two 1D passes, rows then columns, with clamped borders."""
    k = gaussian_kernel(width)
    radius = len(k) // 2
    h = len(img)
    w = len(img[0])
    tmp = [[0.0] * w for _ in range(h)]
    for y in range(h):
        row = img[y]
        for x in range(w):
            acc = 0.0
            for t in range(-radius, radius + 1):
                xx = min(w - 1, max(0, x + t))
                acc += k[t + radius] * row[xx]
            tmp[y][x] = acc
    out = [[0.0] * w for _ in range(h)]
    for y in range(h):
        for x in range(w):
            acc = 0.0
            for t in range(-radius, radius + 1):
                yy = min(h - 1, max(0, y + t))
                acc += k[t + radius] * tmp[yy][x]
            out[y][x] = acc
    return out


def scales(r: int) -> list[float]:
    """The scales s_k = 1.6^k for k = 0 .. r - 1, in pixels."""
    return [RATIO ** k for k in range(r)]


def reinhard_local(
    lw: list[list[float]],
    key: float = 0.18,
    phi: float = 8.0,
    eps: float = 0.05,
    r: int = 8,
    delta: float = 1e-6,
    return_scales: bool = False,
):
    """The local dodging-and-burning operator, Equations 5 to 9.

    B[k] is the image blurred with the width alpha1 1.6^k. The center of
    scale k is B[k] and its surround is B[k + 1], because alpha2 = 1.6
    alpha1. For each pixel the loop goes up from the smallest scale while
    |V| < eps, and keeps the last scale that passed. If |V| >= eps already
    at the smallest scale, it keeps the smallest scale.
    """
    lbar = log_average(lw, delta)  # @line L6
    lum = [[key * x / lbar for x in row] for row in lw]
    s = scales(r)
    b = [blur(lum, ALPHA1 * RATIO ** k) for k in range(r + 1)]  # @line L7
    h = len(lw)
    w = len(lw[0])
    out = [[0.0] * w for _ in range(h)]
    chosen = [[0] * w for _ in range(h)]
    for y in range(h):  # @line L8
        for x in range(w):
            m = 0  # @line L9
            for k in range(r):  # @line L10
                c = b[k][y][x]
                v = (c - b[k + 1][y][x]) / (key * 2.0 ** phi / (s[k] * s[k]) + c)  # @line L11
                if abs(v) >= eps:  # @line L12
                    break
                m = k
            out[y][x] = min(1.0, lum[y][x] / (1.0 + b[m][y][x]))  # @line L13
            chosen[y][x] = m
    if return_scales:
        return out, chosen
    return out  # @line L14


def tone_map_rgb(
    rgb: list[list[tuple[float, float, float]]], ld: list[list[float]]
) -> list[list[tuple[float, float, float]]]:
    """Scale each color by Ld / Lw, a common way to carry the result to RGB."""
    out = []
    for y, row in enumerate(rgb):
        new = []
        for x, c in enumerate(row):
            lw = luminance(c)
            f = ld[y][x] / lw if lw > 0.0 else 0.0
            new.append((c[0] * f, c[1] * f, c[2] * f))
        out.append(new)
    return out
test_reinhard_tone_mapping.py 222 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reinhard-tone-mapping/. The authors are listed in prov/FX4QEZ.jsonl.

"""Tests of the Reinhard operator against closed forms and brute force.

The global operator is checked on the check values of Equation 3, on the
white point of Equation 4, for monotonicity and for invariance to the
exposure of the input. The separable blur of the local operator is checked
against a direct 2D convolution, and the local operator against the global
one on a constant image and against a direct per-pixel scale search.
"""

import math
import random

from reinhard_tone_mapping import (
    ALPHA1,
    blur,
    compress,
    gaussian_kernel,
    log_average,
    luminance,
    reinhard_global,
    reinhard_local,
    scales,
    tone_map_rgb,
)


def random_image(rng: random.Random, w: int, h: int) -> list[list[float]]:
    """Luminances spread over six orders of magnitude, log uniform."""
    return [[10.0 ** rng.uniform(-3.0, 3.0) for _ in range(w)] for _ in range(h)]


def test_check_values() -> None:
    assert compress(1.0) == 0.5
    assert compress(3.0) == 0.75
    assert compress(0.0) == 0.0


def test_white_point() -> None:
    for white in (0.5, 1.0, 2.0, 7.5, 100.0):
        assert abs(compress(white, white) - 1.0) < 1e-12
    # A large Lwhite gives Equation 3.
    for l in (0.01, 0.5, 2.0, 30.0):
        assert abs(compress(l, 1e9) - compress(l)) < 1e-12


def test_log_average_is_geometric_mean() -> None:
    rng = random.Random(1)
    img = random_image(rng, 8, 8)
    flat = [x for row in img for x in row]
    direct = math.prod(x ** (1.0 / len(flat)) for x in flat)
    assert abs(log_average(img, 0.0) - direct) < 1e-9 * direct


def test_key_maps_log_average() -> None:
    # A constant image c has log average c, so every pixel scales to the key.
    for c in (0.001, 1.0, 250.0):
        out = reinhard_global([[c] * 4 for _ in range(3)], key=0.18, delta=0.0)
        for row in out:
            for v in row:
                assert abs(v - 0.18 / 1.18) < 1e-12


def test_page_example() -> None:
    img = [[0.01, 0.1, 1.0, 10.0, 100.0]]
    simple = reinhard_global(img, delta=0.0)[0]
    white = reinhard_global(img, l_white="max", delta=0.0)[0]
    want_simple = [0.0018, 0.01768, 0.15254, 0.64286, 0.94737]
    want_white = [0.0018, 0.01768, 0.15263, 0.64643, 1.0]
    for got, want in zip(simple, want_simple):
        assert abs(got - want) < 5e-6
    for got, want in zip(white, want_white):
        assert abs(got - want) < 5e-6


def test_monotone_and_range() -> None:
    rng = random.Random(2)
    img = random_image(rng, 16, 16)
    flat = sorted(x for row in img for x in row)
    for l_white in (None, "max", 3.0):
        out = reinhard_global([flat], l_white=l_white)[0]
        assert all(a < b for a, b in zip(out, out[1:]))
        assert out[0] > 0.0
        if l_white is None:
            assert out[-1] < 1.0
        if l_white == "max":
            assert abs(out[-1] - 1.0) < 1e-12


def test_exposure_invariance() -> None:
    # With delta = 0, scaling every input by c > 0 leaves the output unchanged.
    rng = random.Random(3)
    img = random_image(rng, 6, 5)
    base = reinhard_global(img, delta=0.0)
    for c in (1e-3, 0.5, 40.0):
        out = reinhard_global([[c * x for x in row] for row in img], delta=0.0)
        for ra, rb in zip(base, out):
            for a, b in zip(ra, rb):
                assert abs(a - b) < 1e-12


def brute_blur(img: list[list[float]], width: float) -> list[list[float]]:
    """Direct 2D convolution with the truncated kernel of Equation 5."""
    radius = len(gaussian_kernel(width)) // 2
    h, w = len(img), len(img[0])
    weights = {}
    total = 0.0
    for dy in range(-radius, radius + 1):
        for dx in range(-radius, radius + 1):
            r2 = dx * dx + dy * dy
            wt = math.exp(-r2 / (width * width)) / (math.pi * width * width)
            weights[(dx, dy)] = wt
            total += wt
    out = [[0.0] * w for _ in range(h)]
    for y in range(h):
        for x in range(w):
            acc = 0.0
            for (dx, dy), wt in weights.items():
                xx = min(w - 1, max(0, x + dx))
                yy = min(h - 1, max(0, y + dy))
                acc += wt * img[yy][xx]
            out[y][x] = acc / total
    return out


def test_blur_against_direct_convolution() -> None:
    rng = random.Random(4)
    img = random_image(rng, 12, 10)
    for k in range(5):
        width = ALPHA1 * 1.6 ** k
        fast = blur(img, width)
        slow = brute_blur(img, width)
        for ra, rb in zip(fast, slow):
            for a, b in zip(ra, rb):
                assert abs(a - b) < 1e-9 * max(1.0, abs(b))


def test_local_on_constant_image() -> None:
    # Every blur of a constant image is the same constant, so V = 0, the
    # largest scale is chosen, and the result equals the global operator.
    img = [[3.0] * 32 for _ in range(32)]
    out, chosen = reinhard_local(img, return_scales=True)
    glob = reinhard_global(img)
    for y in range(32):
        for x in range(32):
            assert chosen[y][x] == 7
            assert abs(out[y][x] - glob[y][x]) < 1e-12


def direct_local(img, key=0.18, phi=8.0, eps=0.05, r=8, delta=1e-6):
    """The local operator with the scale search written per pixel.

    For each pixel and scale it computes the center and the surround by
    direct 2D convolution, independent of the separable blur.
    """
    lbar = log_average(img, delta)
    lum = [[key * x / lbar for x in row] for row in img]
    blurs = [brute_blur(lum, ALPHA1 * 1.6 ** k) for k in range(r + 1)]
    s = scales(r)
    h, w = len(img), len(img[0])
    out = [[0.0] * w for _ in range(h)]
    for y in range(h):
        for x in range(w):
            passed = [
                abs((blurs[k][y][x] - blurs[k + 1][y][x]) / (key * 2.0 ** phi / s[k] ** 2 + blurs[k][y][x])) < eps
                for k in range(r)
            ]
            m = 0
            while m + 1 < r and passed[m] and passed[m + 1]:
                m += 1
            out[y][x] = min(1.0, lum[y][x] / (1.0 + blurs[m][y][x]))
    return out


def test_local_against_direct() -> None:
    rng = random.Random(5)
    img = random_image(rng, 10, 9)
    fast = reinhard_local(img, r=4)
    slow = direct_local(img, r=4)
    for ra, rb in zip(fast, slow):
        for a, b in zip(ra, rb):
            assert abs(a - b) < 1e-9


def test_local_step_image() -> None:
    w = 32
    img = [[0.05 if x < 16 else 5.0 for x in range(w)] for _ in range(w)]
    out, chosen = reinhard_local(img, return_scales=True)
    glob = reinhard_global(img)
    # The trace on the page: pixel 19 of row 16 keeps scale 4.
    assert chosen[16][19] == 4
    assert abs(out[16][19] - 0.6491) < 5e-5
    # Next to the step, the dark side gets darker and the bright side
    # brighter than with the global operator: local contrast goes up.
    assert out[16][15] < glob[16][15]
    assert out[16][16] > glob[16][16]
    for row in out:
        for v in row:
            assert 0.0 <= v <= 1.0


def test_local_range_random() -> None:
    rng = random.Random(6)
    img = random_image(rng, 32, 32)
    out, chosen = reinhard_local(img, return_scales=True)
    for ro, rc in zip(out, chosen):
        for v, m in zip(ro, rc):
            assert 0.0 <= v <= 1.0
            assert 0 <= m < 8


def test_rgb_keeps_ratios() -> None:
    rgb = [[(2.0, 1.0, 0.5), (0.1, 0.2, 0.4)]]
    lw = [[luminance(c) for c in row] for row in rgb]
    ld = reinhard_global(lw)
    out = tone_map_rgb(rgb, ld)
    for row_in, row_out, row_ld in zip(rgb, out, ld):
        for c, d, l in zip(row_in, row_out, row_ld):
            assert abs(luminance(d) - l) < 1e-12
            assert abs(d[0] * c[1] - d[1] * c[0]) < 1e-12

History

The paper of Reinhard, Stark, Shirley and Ferwerda (2002) took its ideas from photography. The Zone System of Ansel Adams maps the luminance of a scene to print zones, with the middle gray of an 18 percent reflectance card as the anchor, which became the key a=0.18a = 0.18. Dodging and burning, where the printer holds back or adds light to parts of a print, became the local operator. Its center-surround test follows the local contrast measure of Blommaert and Martens, with changes. Earlier work on tone reproduction in graphics, for example by Tumblin and Rushmeier (1993), had aimed at matching the brightness that a viewer perceives. Reinhard's global curve became a standard tone curve in real-time rendering, and the later book on high dynamic range imaging by Reinhard, Ward, Pattanaik and Debevec (2005) put it among many other operators.

References

  1. Erik Reinhard, Michael Stark, Peter Shirley and James Ferwerda, Photographic tone reproduction for digital images, ACM Transactions on Graphics 21(3) (SIGGRAPH 2002), 267 to 276, the initial luminance mapping (log average, key, the curve L/(1+L) and the white point form) and the automatic dodging and burning with the center-surround scale selection
  2. Erik Reinhard, Michael Stark, Peter Shirley and James Ferwerda, Photographic tone reproduction for digital images, University of Utah technical report UUCS-02-001, 2002, Section 3.1 Initial luminance mapping (Equations 1 to 4) and Section 3.2 Automatic dodging-and-burning (Equations 5 to 9, the parameters phi = 8, epsilon = 0.05, alpha1 = 0.35 and the ratio 1.6)
  3. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 8, Light and Color (the part on tone mapping)
  4. Erik Reinhard, Greg Ward, Sumanta Pattanaik and Paul Debevec, High Dynamic Range Imaging, Acquisition, Display, and Image-Based Lighting, Morgan Kaufmann, 2005, the chapters on tone reproduction (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.global
  • a full proof of time.local
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example