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.
- Solves
- Tone mapping
- 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
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 . It first sets the exposure so that the log average luminance of the image maps to a mid gray value, the key , which is by default. Then it compresses each scaled luminance with the curve , 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 , 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 pixels with world luminances in linear units, and a key . The output is a display luminance 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 ; the Rec. 709 weights are a common choice in other code. A common way to carry the result back to color scales each linear color by , 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 , 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. is the white point: the smallest scaled luminance that maps to 1. gives the plain curve . Lines L6 to L14 are the local operator. is the scaled image blurred by a Gaussian of width , where is the scale in pixels and . The surround of scale has the width with , which is the center of scale , so the method needs only blurs for scales. is a small constant, for example , that keeps out of black pixels.
REINHARD-GLOBAL(Lw[1..p], a, W)- 1
Lbar ← exp((1/p) · Σi log(δ + Lw[i])) ▷ the log average - 2
for each pixel i - 3
L ← (a / Lbar) · Lw[i] ▷ the exposure - 4
Ld[i] ← L · (1 + L / W²) / (1 + L) ▷ L / (1 + L) when W = ∞ - 5
return Ld REINHARD-LOCAL(Lw[1..p], a, φ, ε, r)- 6
compute Lbar as in L1; L[i] ← (a / Lbar) · Lw[i] for each pixel i - 7
for k ← 0 to r: Bk ← L blurred by a Gaussian of width α1 · 1.6^k - 8
for each pixel i - 9
m ← 0 - 10
for k ← 0 to r - 1 - 11
V ← (Bk[i] - Bk+1[i]) / (a · 2^φ / sk² + Bk[i]) - 12
if |V| ≥ ε then leave the loop of L10, else m ← k - 13
Ld[i] ← min(1, L[i] / (1 + Bm[i])) - 14
return Ld
Line L1 is the geometric mean of . Line L3 maps a pixel with the log average luminance to . Line L4 is the curve of the paper with the white point; the paper sets by default to the largest value of in the image, so that the brightest pixel maps to exactly 1.
Line L7 uses the Gaussian 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 makes the test independent of the absolute luminance. The term keeps from growing large when 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 , 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 in place of in the denominator. It can exceed 1 at very bright pixels, so the paper clips it.
The paper uses , 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: , , , and . All of these are tuning.
Example
The global operator. The image has five pixels with . With the log average is , so with the scaled values are .
| white point | |||
|---|---|---|---|
| 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 . The two darkest pixels are nearly unchanged, because for small . The check values of the plain curve: maps to and maps to . The last column sets to the largest , 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 the log average becomes and the values change by less than .
The local operator. The image is 32 by 32 pixels. The left half (columns 0 to 15) has and the right half has . The log average is (with , ), so the scaled values are and , and the global operator gives and . For the pixel in row 16 and column 19, three pixels right of the step, lines L10 to L12 compute:
| width | result | ||||||
|---|---|---|---|---|---|---|---|
| 0 | 1 | 0.354 | 1.8000 | 1.8000 | 46.08 | 0.0000 | pass, |
| 1 | 1.6 | 0.566 | 1.8000 | 1.8000 | 18.00 | 0.0000 | pass, |
| 2 | 2.56 | 0.905 | 1.8000 | 1.7996 | 7.031 | 0.0000 | pass, |
| 3 | 4.096 | 1.448 | 1.7996 | 1.7732 | 2.747 | 0.0058 | pass, |
| 4 | 6.554 | 2.317 | 1.7732 | 1.6403 | 1.073 | 0.0467 | pass, |
| 5 | 10.49 | 3.707 | 1.6403 | 1.4410 | 0.419 | 0.0968 | stop |
The surround of scale 5 reaches across the step, so goes above and the pixel keeps . Line L13 gives , a little brighter than the global , because the neighborhood includes some dark pixels. Right at the step, the dark pixel in column 15 maps to in place of , and the bright pixel in column 16 to in place of . Far from the step the result is close to the global one: the pixel in column 31 gives . 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:
- is the geometric mean of , and a constant image maps every pixel to before the curve.
- With , multiplying all inputs by any does not change the output. The operator removes the exposure of the input.
- The curve is strictly increasing, with and . For it stays below 1. So the operator keeps the order of the pixels, and with equal to the largest no output exceeds 1. For the curve goes above 1, so a smaller 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 such that all tests up to pass, the output is in , and on a constant image every is 0 and the result equals the global operator. A pixel with maps below the global value and a pixel with 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 pixels with world luminances , a constant with for every , and a key . Lines L1 to L5 compute
with for a white point , or for . 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). is the geometric mean of the values . If and all , then and every .
Proof. , because turns the sum of logarithms into a product. For a constant image the product is , so and .
Claim 2 (exposure invariance). If and all , then the global operator gives the same output for the inputs and , for every .
Proof. The geometric mean of is , so is the same value as before, and so is .
For the claim holds only up to the change of relative to the luminances. The paper adds only to avoid at black pixels.
Claim 3 (the curve). For , is strictly increasing on , and for every . For , is strictly increasing on , , for and for . For every fixed , with white point tends to as .
Proof. is strictly increasing and is below 1. The factor is positive and increasing, so the product of the two factors is strictly increasing on , where both are not negative and the first is strictly increasing. At ,
Strict monotonicity then gives the two inequalities. The limit holds because .
So the global operator keeps the order of the pixels: implies , because is a positive multiple of and is strictly increasing. With set to the largest value of , the brightest pixel maps to exactly 1 and no pixel goes above 1.
Claim 4 (the separable blur). Let on the square , scaled to sum to 1, and let the image be extended by clamping at the border. Then two 1D passes with the 1D kernel , first along the rows and then along the columns, give the 2D convolution with .
Proof. , and the sum over the square is the product of the two 1D sums, so . Clamping is done separately in and in : the pixel at after clamping is the pixel at the clamped column and the clamped row. Then
The inner sum is the row pass and the outer sum is the column pass.
Equation 5 of the paper has the factor , which makes the kernel integrate to 1 over the plane. On a pixel grid and after the cut at radius 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 that lines L9 to L12 select is in , and it is the largest such that for all , or 0 if . (b) The output is in . (c) If , then , and if , then , before the clip to 1. (d) On a constant image every is 0, , and the local operator equals the global operator with .
Proof. (a) starts at 0, and line L12 sets only while every earlier test passed, because the loop stops at the first failure. (b) Each is a weighted average of values with weights that are not negative, so , and ; the clip gives at most 1. (c) is strictly decreasing for . (d) By Claim 4 and the normalization, each blur of the constant is , so for every , the loop never stops early, , and , which is below 1, so the clip does nothing.
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 and as tuning.
Cost. Lines L1 to L5 take time and space for the output. In the local operator, the scale loop of lines L8 to L12 does at most tests per pixel, in total. The blurs dominate. The separable blur of width costs , so the direct method costs , where is the largest scale. With an FFT each blur costs , for in total. With a blur of constant cost per pixel, for example a recursive filter or a pyramid, the total is . The memory is if all blurs are kept, or if the scales are processed one after the other and each pixel keeps its current state.
Complexity
The model is the real RAM, with pixels and scales. The global operator reads each pixel twice: time and space for the output, or 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 . The blurs of line L7 dominate, and their cost depends on how they are computed. A direct separable blur of width costs , so all blurs cost , where is the largest scale: the widths grow geometrically, so the largest one dominates the sum. The paper computes the blurs with an FFT, at each, for . A blur of constant cost per pixel, for example a recursive Gaussian filter or an image pyramid, gives in total. The memory is to keep all blurs, or 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. has slope 1 at 0 and slope at , so contrast in bright areas drops fast. Very bright regions lose detail, and the white point form helps only near .
- Local form raises local contrast. The local step keeps detail near edges, at the cost of 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 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 is often called extended Reinhard. A below the largest 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 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 . One black pixel makes undefined and the log average 0. Add a small 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 . For , line L4 gives values above 1. Clip, or set to the largest .
- Color shifts. Scaling each channel by 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 . Read literally, this almost always takes the smallest scale, because the term makes 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.
# 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 . 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
- 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag FX4QEZ Edit this page History Report an error Markdown