Skip to content
scipython.com

Quadtrees: image compression

Posted on

A region quadtree represents an image by dividing it recursively into quadrants until each block is close to a single colour, so that a large, uniform area is stored as a single leaf. This post builds region quadtrees for a photograph with NumPy, splitting first the blocks whose division most reduces the error, encodes them in a few bytes per leaf, and compares the result with uniform blocks and with JPEG compression.

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.

region_quadtree.py
The region quadtree module

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:

\[E = \sum_{i=1}^{n} \sum_{c} \left(v_{ic} - \bar{v}_c\right)^2 = \sum_{c} \left[\sum_{i=1}^{n} v_{ic}^2 - \frac{1}{n} \left(\sum_{i=1}^{n} v_{ic}\right)^2\right],\]

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,

\[S_{yx} = \sum_{y' < y} \sum_{x' < x} v_{y'x'},\]

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.

python
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,

\[\mathrm{PSNR} = 10 \log_{10} \frac{255^2}{\mathrm{MSE}}\ \mathrm{dB},\]

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,

\[\Delta E = E_\text{block} - \sum_\text{quadrants} E_\text{quadrant},\]

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.

python
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.

Four panels in a two-by-two grid. Top left: the original photograph of a white rocket on a launch pad at dusk, between lattice towers, under a sky that shades from light to dark blue, with bright lights along the ground. Top right: 300 leaves, a coarse mosaic of blue squares in which only the rocket and the lights can be made out. Bottom left: 3000 leaves, in which the rocket is clear but the towers are faint and blocky. Bottom right: 30 000 leaves, close to the original.
The photograph (SpaceX, public domain, via scikit-image) and its approximations by the leaves of quadtrees with 300, 3000 and 30 000 leaves, with their sizes, encoded as described below, and their PSNR.

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.

The approximation by 3000 leaves, with the edges of its leaves drawn as thin white lines. The leaves are large squares in the sky, smaller towards the horizon, and very small around the rocket, the lights and the edges of the towers.
The leaves of the approximation by 3000 leaves: small around the rocket, the lights and the edges of the towers, and large in the sky, whose gradient they follow in steps.
An animation of the approximation as its blocks are split. It starts as a single dark blue rectangle, which divides into quadrants and then into smaller and smaller blocks, concentrated first on the rocket and the lights and later on the towers, until the photograph emerges, criss-crossed by the faint lines of the blocks' edges.
The approximation as its blocks are split, from one leaf to 20 000, with the edges of the leaves lightened.

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.

python
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.

rocket_example.py
"""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

A plot of PSNR against size, with a logarithmic size axis from 200 bytes to 600 kB. The quadtree's line rises slowly, from 22 dB at 200 bytes to 27 dB at 10 kB, then steeply to 50 dB at 300 kB. The line for uniform blocks lies below it throughout, reaching 30 dB at 200 kB. The two JPEG lines start at 2.4 kB and 4 kB, below the quadtree's line, cross it at about 3.6 kB and 5.8 kB, and then lie above it, the line for JPEG with 4:4:4 sampling rising to 46 dB at 112 kB.
The PSNR of the approximations against their size, for the quadtree, for uniform square blocks of 64, 32, 16, 8, 4 and 2 pixels, and for JPEG images saved by Pillow at qualities from 1 to 95, with and without chroma subsampling.

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.

Four crops of the area around the top of the rocket, at full resolution, in a two-by-two grid. Top left: the quadtree with 1000 leaves, 3.2 kB, made of soft blue blocks. Top right: JPEG at quality 4, 2.9 kB, with flat purple and teal bands in the sky and green and grey blocks on the rocket. Bottom left: the quadtree with 3000 leaves, 9.5 kB, in which the towers are faint. Bottom right: JPEG at quality 22, 9.4 kB, in which the towers' lattices are clear.
Crops of the quadtree's approximations (left) and of JPEG images of about the same size (right), at full resolution. At about 3 kB, JPEG's blocks and coarsely quantised colours are worse than the quadtree's leaves; at about 9.5 kB, JPEG keeps the towers that the quadtree loses.

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.

Comments

Leave a comment

Optional, and never shown: only the moderator sees it.

Comments are written in Markdown (code between ``` lines) and appear once approved. Your name and comment are published; your email address, if you give one, is seen only by the moderator.