The earlier posts in this series, Quadtrees: background and Quadtrees: implementation in Python, describe the quadtree that stores points. The region quadtree applies the same recursive division into quadrants to an image: each node covers a rectangular block of pixels, and a block is divided into four until each is close enough to a single colour. Klinger and Dyer used it to represent pictures (doi:10.1016/S0146-664X(76)80006-8), and Hunter and Steiglitz showed how to operate on images in this form (doi:10.1109/TPAMI.1979.4766900). The leaves of a region quadtree, each filled with a single colour, approximate the image, and the approximation can be stored as the structure of the tree and one colour for each leaf. This is a simple form of lossy image compression: smooth areas need few leaves, and only detailed areas need many.
Error
The colour that best represents a block of \(n\) pixels, in the sense of least squares, is its mean colour, and the error of this representation is the sum of the squared differences between the pixels' values and the mean, over the pixels and the three colour channels:
where \(v_{ic}\) is the value of channel \(c\) (red, green or blue) of pixel \(i\) and \(\bar{v}_c\) is the mean of channel \(c\) over the block. The second form needs only the sums of the values and of their squares, and these can be found for any rectangular block, in a time independent of its size, from a summed-area table (Crow, doi:10.1145/800031.808600), also called an integral image. This is the array of the sums of the values above and to the left of each position,
from which the sum over the block of rows \(y_0 \le y < y_1\) and columns \(x_0 \le x < x_1\) is \(S_{y_1 x_1} - S_{y_0 x_1} - S_{y_1 x_0} + S_{y_0 x_0}\). NumPy calculates the table with two cumulative sums, one along each axis, and BlockStats keeps one table for the values and one for their squares, in 64-bit integers, so that the sums are exact.
import heapq
import itertools
import struct
import numpy as np
class BlockStats:
"""Sums over rectangular blocks of an image, each found from summed-area
tables in a time independent of the block's size. A block is a tuple
(y0, x0, y1, x1): the rows y0 <= y < y1 and the columns x0 <= x < x1."""
def __init__(self, image):
a = np.atleast_3d(image).astype(np.int64)
h, w, c = a.shape
# S[y, x] is the sum of the values in the rows above row y and the
# columns left of column x, in each channel; S2 is that of their
# squares.
self.S = np.zeros((h + 1, w + 1, c), np.int64)
self.S2 = np.zeros((h + 1, w + 1, c), np.int64)
self.S[1:, 1:] = a.cumsum(axis=0).cumsum(axis=1)
self.S2[1:, 1:] = (a * a).cumsum(axis=0).cumsum(axis=1)
@staticmethod
def block_sum(table, block):
y0, x0, y1, x1 = block
return table[y1, x1] - table[y0, x1] - table[y1, x0] + table[y0, x0]
def mean(self, block):
"""The mean colour of the block."""
y0, x0, y1, x1 = block
return self.block_sum(self.S, block) / ((y1 - y0) * (x1 - x0))
def error(self, block):
"""The sum of the squared differences between the values in the
block and its mean colour, over its pixels and channels."""
y0, x0, y1, x1 = block
n = (y1 - y0) * (x1 - x0)
s = self.block_sum(self.S, block)
return float(np.sum(self.block_sum(self.S2, block) - s * s / n))
The quality of an approximation is usually measured by its peak signal-to-noise ratio,
where 255 is the largest value of an 8-bit channel and \(\mathrm{MSE}\) is the mean squared error of the whole image: the sum of \(E\) over its blocks divided by the number of values, three for each pixel. A higher PSNR is better, and each halving of the mean squared error adds 3 dB.
Splitting
A region quadtree is usually built by splitting every block whose error exceeds some threshold. Here, the blocks are split one at a time instead, in order of the reduction that splitting them brings to the total error,
which is never negative. A priority queue holds the blocks that can be split, ordered by \(\Delta E\), as the nearest-neighbour search of the previous post held nodes ordered by their distance: at each step, the block with the largest \(\Delta E\) is split, and its quadrants join the queue. Splitting every block down to single pixels records the order of all the splits once. The approximation with any number of leaves is then given by the splits at the start of that order, and the error after each split is the error before it less its \(\Delta E\). A block is split at its middle row and column, rounded down, so the blocks of an image whose sides are not powers of two are not all the same size; a block one pixel high or wide is split into two halves, so that the tree can reach every pixel.
def children(block):
"""The quadrants of a block, split at its middle row and column (rounded
down), in the order nw, ne, sw, se, leaving out any that are empty: four,
or two for a block one pixel high or wide, or none for a single pixel."""
y0, x0, y1, x1 = block
if y1 - y0 == 1 and x1 - x0 == 1:
return []
ym, xm = (y0 + y1) // 2, (x0 + x1) // 2
quadrants = ((y0, x0, ym, xm), (y0, xm, ym, x1),
(ym, x0, y1, xm), (ym, xm, y1, x1))
return [q for q in quadrants if q[0] < q[2] and q[1] < q[3]]
def split_order(image):
"""Split the image into blocks, splitting at each step the block whose
division most reduces the error, until every block is a single pixel.
Return the blocks in the order in which they were split, and arrays of
the number of leaves and of the error before the first split and after
each split."""
stats = BlockStats(image)
root = (0, 0, *image.shape[:2])
count = itertools.count() # to break ties without comparing blocks
heap = []
def push(block):
kids = children(block)
if kids:
gain = stats.error(block) - sum(map(stats.error, kids))
heapq.heappush(heap, (-gain, next(count), block, len(kids)))
push(root)
splits, n_leaves, errors = [], [1], [stats.error(root)]
while heap:
neg_gain, _, block, n_kids = heapq.heappop(heap)
splits.append(block)
n_leaves.append(n_leaves[-1] + n_kids - 1)
errors.append(errors[-1] + neg_gain)
for kid in children(block):
push(kid)
return splits, np.array(n_leaves), np.array(errors)
This greedy choice is not always the best one. A block whose four quadrants have the same mean colour gains nothing from being split, however much its quadrants would gain from being split in turn, so it is split later than it should be.
Approximations
The photograph below, of the launch of the Deep Space Climate Observatory (DSCOVR) on a Falcon 9 rocket, is one of scikit-image's sample images, skimage.data.rocket(). It is 640 × 427 pixels, and its 819 840 bytes of pixel values are split down to its 273 280 single pixels by 142 037 splits.
With 300 leaves, the approximation shows little more than the sky, the rocket and the lights; with 3000, the rocket is clear, but the lattice towers have almost gone. The towers are thin, so the error that they contribute is small compared with that of the sky's gradient, which blocks of uniform colour can follow only in steps. With 30 000 leaves, the approximation is close to the original.
Encoding
The approximation is stored as a header of five bytes (the height and the width, two bytes each, and the number of channels), then the structure of the tree, as one bit for each block that could be split, 1 if it was, in depth-first order, then the mean colour of each leaf, one byte for each channel, in the same order. A decoder that follows the same depth-first order knows which blocks can be split, and so can read the bits, and then the colours, without any other information. Each split into four adds three leaves, so a tree with \(L\) leaves has \((L - 1)/3\) nodes that have been split and \((4L - 1)/3\) nodes in all: if every node could be split, its structure takes about \(4L/3\) bits, or \(L/6\) bytes, against \(3L\) bytes for the colours. The approximation by 1000 leaves, for example, takes \(5 + 167 + 3000 = 3172\) bytes.
HEADER = struct.Struct(">HHB") # the height, width and number of channels
def encode(image, split):
"""Encode the approximation of the image by the leaves of the quadtree
in which the blocks in the set split have been split: a header, then one
bit for each block that could be split, 1 if it was, then the mean colour
of each leaf, one byte for each channel, both in depth-first order."""
stats = BlockStats(image)
h, w, c = stats.S.shape[0] - 1, stats.S.shape[1] - 1, stats.S.shape[2]
bits, colours = [], []
stack = [(0, 0, h, w)]
while stack:
block = stack.pop()
kids = children(block)
if kids:
bits.append(block in split)
if block in split:
stack.extend(reversed(kids))
else:
colours.append(stats.mean(block))
colours = np.clip(np.round(colours), 0, 255).astype(np.uint8)
return (HEADER.pack(h, w, c) + np.packbits(bits).tobytes()
+ colours.tobytes())
def decode(data):
"""Decode bytes made by encode into an image."""
h, w, c = HEADER.unpack_from(data)
bits = np.unpackbits(np.frombuffer(data, np.uint8, offset=HEADER.size))
leaves, n_bits = [], 0
stack = [(0, 0, h, w)]
while stack:
block = stack.pop()
kids = children(block)
if kids:
n_bits += 1
if bits[n_bits - 1]:
stack.extend(reversed(kids))
continue
leaves.append(block)
offset = HEADER.size + (n_bits + 7) // 8
colours = np.frombuffer(data, np.uint8, len(leaves) * c, offset)
image = np.empty((h, w, c), np.uint8)
for (y0, x0, y1, x1), colour in zip(leaves, colours.reshape(-1, c)):
image[y0:y1, x0:x1] = colour
return image if c > 1 else image[..., 0]
Splitting every block down to single pixels reproduces the photograph exactly, in 837 600 bytes, 2 per cent more than its pixel values, so the format is useful only for lossy compression. Compressing the encoded bytes further with Python's zlib module saves only 3 to 9 per cent for the approximations by 1000 to 30 000 leaves, since zlib looks for repeated strings of bytes, and the colours of neighbouring leaves, though similar, are rarely identical.
The program rocket_example.py compresses the photograph to several numbers of leaves and compares each with a JPEG image no larger than it, saved by Pillow at the highest quality setting that allows; Pillow's documentation advises against qualities above 95.
"""Compress a photograph with a region quadtree to several numbers of leaves,
and compare each result with a JPEG image of the same size."""
import io
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from skimage import data
from region_quadtree import decode, encode, split_order
def psnr(image, reference):
"""The peak signal-to-noise ratio of image with respect to reference,
in dB, for 8-bit values."""
mse = np.mean((image.astype(float) - reference.astype(float))**2)
return 10 * np.log10(255**2 / mse)
def compress(image, splits, n_leaves, leaves):
"""The encoding of the image's approximation by the first quadtree in
the split order with at least the given number of leaves."""
k = np.searchsorted(n_leaves, leaves)
return encode(image, set(splits[:k]))
def jpeg(image, max_bytes):
"""The JPEG encoding of the image, with the highest quality setting that
makes it no larger than max_bytes, and that quality; None if even the
lowest quality is too large."""
best = None
# Pillow's documentation advises against qualities above 95.
for quality in range(1, 96):
buffer = io.BytesIO()
Image.fromarray(image).save(buffer, "JPEG", quality=quality,
optimize=True)
if buffer.tell() > max_bytes:
break
best = buffer.getvalue(), quality
return best
def read_jpeg(jpeg_bytes):
return np.asarray(Image.open(io.BytesIO(jpeg_bytes)).convert("RGB"))
if __name__ == "__main__":
image = data.rocket()
splits, n_leaves, errors = split_order(image)
h, w, c = image.shape
print(f"{w} × {h} pixels, {image.nbytes} bytes uncompressed")
print(" Leaves Bytes PSNR/dB JPEG quality Bytes PSNR/dB")
for leaves in (100, 300, 1000, 3000, 10000, 30000):
code = compress(image, splits, n_leaves, leaves)
approx = decode(code)
line = f"{leaves:7d} {len(code):7d} {psnr(approx, image):8.2f}"
result = jpeg(image, len(code))
if result:
jpeg_bytes, quality = result
line += (f" {quality:12d} {len(jpeg_bytes):6d}"
f" {psnr(read_jpeg(jpeg_bytes), image):8.2f}")
print(line)
code = compress(image, splits, n_leaves, 3000)
jpeg_bytes, quality = jpeg(image, len(code))
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), layout="constrained")
axes[0].imshow(decode(code))
axes[0].set_title(f"Quadtree, 3000 leaves, {len(code)} bytes")
axes[1].imshow(read_jpeg(jpeg_bytes))
axes[1].set_title(f"JPEG, quality {quality}, {len(jpeg_bytes)} bytes")
for ax in axes:
ax.set_axis_off()
plt.show()
Comparison
The figure compares the quadtree with two other approximations. Uniform blocks divide the image into squares of the same size, each filled with its mean colour and stored in the same format as the quadtree's leaves, but without the bits of the tree's structure. With the same number of blocks, the quadtree's adaptive blocks are better by an amount that grows with their number: by 0.5 dB with 70 blocks, 1.6 dB with 4320 and 3.6 dB with 17 120, and by 14.5 dB with 68 480, the number of squares of 2 × 2 pixels. JPEG images (doi:10.1109/30.125072) are shown with Pillow's default chroma subsampling (4:2:0), which stores the colour, as distinct from the brightness, at half the resolution in each direction, and without it (4:4:4).
JPEG cannot make this photograph smaller than 2.4 kB, even at its lowest quality, and below about 3.6 kB the quadtree is the better of the two: it is better than JPEG without subsampling up to about 5.8 kB. Above these sizes, JPEG is far better: at 9.4 kB, its PSNR is 28.9 dB, against 26.7 dB for the quadtree at 9.5 kB, and it keeps the towers. JPEG divides the image into blocks of 8 × 8 pixels and represents each by the coefficients of its discrete cosine transform, so that a smooth gradient takes a few coefficients rather than many uniform blocks; it quantises most coarsely the high spatial frequencies, to which the eye is least sensitive, and entropy-codes the result. With subsampling, its PSNR levels off at about 35 dB, since the colour detail that it discards is lost at any quality, though the eye barely notices it.
A short warning: the photograph was itself stored as a JPEG image, which flatters JPEG at its highest qualities, when its quantisation can coincide with that of the original; this is one reason to stop at quality 95.
A single colour for each leaf is the simplest model of its contents. Fitting each leaf with a linear gradient, a plane in each channel, would follow a smooth gradient such as the sky's with fewer leaves, and a transform of each leaf's contents, as in JPEG, would go further. Modern video coding combines the two ideas: the HEVC (H.265) standard divides each frame into blocks of up to 64 × 64 pixels and splits each block, by a quadtree, into smaller blocks whose contents are predicted and transform-coded; the encoder usually chooses the splits by weighing their cost in bits against their error (Sullivan et al., doi:10.1109/TCSVT.2012.2221191). Region quadtrees are also used to divide images into regions of similar pixels, as in the split-and-merge method of Horowitz and Pavlidis (doi:10.1145/321941.321956), which first splits blocks that are not uniform and then merges neighbouring blocks that are similar.