Decorrelation stretch (DStretch) of an image
This is a simplified implementation of DStretch, an algorithm that enhances faded details like rock art.
The key idea is to convert an image into a matrix , and calculate its covariance matrix . The dimensions are then de-correlated (or whitened).
Why it decorrelates
Let and .
A lot of optimizations are possible to get better results: using uniform scaling for all channels, clipping values, finding better color spaces etc.
import base64, io
from functools import lru_cache
import numpy as np
from PIL import Image
SIZE = 360 # the longer side of the image, in pixels
@lru_cache(maxsize=2)
def decode(url):
"""The image in data URL `url`, scaled so its longer side is SIZE, as an array of shape (height, width, 3)
in [0, 1]. Transparent parts become white."""
image = Image.open(io.BytesIO(base64.b64decode(url.split(',', 1)[1]))).convert('RGBA')
image = Image.alpha_composite(Image.new('RGBA', image.size, 'white'), image).convert('RGB')
scale = SIZE / max(image.size)
image = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))))
return np.asarray(image) / 255
def encode(X):
"""X, an array of shape (height, width, 3), as a BMP data URL. Values are clipped to [0, 1]."""
buffer = io.BytesIO()
Image.fromarray((np.clip(X, 0, 1) * 255).round().astype(np.uint8)).save(buffer, format='BMP')
return 'data:image/bmp;base64,' + base64.b64encode(buffer.getvalue()).decode()
# Color spaces: each turns an array of RGB pixels into its own 3 channels, and back.
YUV = np.array([[0.299, 0.587, 0.114], [-0.14713, -0.28886, 0.436], [0.615, -0.51499, -0.10001]])
XYZ = np.array([[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]])
WHITE = XYZ.sum(axis=1) # XYZ of white (D65)
D = 6 / 29
def rgb_to_lab(X):
linear = np.where(X <= 0.04045, X / 12.92, ((X + 0.055) / 1.055) ** 2.4)
t = linear @ XYZ.T / WHITE
fx, fy, fz = np.moveaxis(np.where(t > D ** 3, np.cbrt(t), t / (3 * D ** 2) + 4 / 29), -1, 0)
return np.stack([116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)], axis=-1)
def lab_to_rgb(X):
fy = (X[..., 0] + 16) / 116
f = np.stack([fy + X[..., 1] / 500, fy, fy - X[..., 2] / 200], axis=-1)
t = np.where(f > D, f ** 3, 3 * D ** 2 * (f - 4 / 29))
linear = np.clip((t * WHITE) @ np.linalg.inv(XYZ).T, 0, 1)
return np.where(linear <= 0.0031308, 12.92 * linear, 1.055 * linear ** (1 / 2.4) - 0.055)
SPACES = {
'LAB': (rgb_to_lab, lab_to_rgb),
'YUV': (lambda X: X @ YUV.T, lambda X: X @ np.linalg.inv(YUV).T),
'RGB': (lambda X: X, lambda X: X),
}
def dstretch(X, space, s):
"""The decorrelation stretch of image X in color space `space`, with stretch s."""
to_space, from_space = SPACES[space]
P = to_space(X).reshape(-1, 3) # one row per pixel
mu = P.mean(axis=0) # the mean pixel
sigma = P.std(axis=0) # each channel's spread
C = np.cov(P, rowvar=False) # 3×3 covariance of the channels
lam, V = np.linalg.eigh(C) # C = V Λ Vᵀ
lam = np.maximum(lam, 1e-12) # a channel with no spread, e.g. a gray image's colors
T = V @ np.diag(1 / np.sqrt(lam)) @ V.T @ np.diag(s * sigma) # rotate, stretch each direction, rotate back
Q = (P - mu) @ T + mu
return from_space(Q.reshape(X.shape))
def original(img):
"""The image as the stretch sees it: scaled to SIZE."""
return encode(decode(img)) if img else ''
def stretched(img, space, s):
"""The image after the decorrelation stretch."""
return encode(dstretch(decode(img), space, s)) if img else ''
img = pie.text('', out='img') # the image as a data URL, filled by the upload UI
space = pie.text('LAB', out='space')
s = pie.scalar(1.5, out='s')
# The lifts are made before the upload UI shows, since it writes `img` as soon as it loads its image.
shown = [pie.lift(original, pie.Text)(img), pie.lift(stretched, pie.Text)(img, space, s)]
pie.ui.image_upload(img, src='/blog/plane.jpg')
pie.ui.dropdown(space, options=list(SPACES), label='Color space')
pie.ui.slider(s, min=0.25, max=10, step=0.05, label='Stretch s')
pie.ui.images(*shown, captions=['Original', 'Decorrelation stretch'])