Image Encoding

Image encoding assigns a codeword to each grey level. Codeword lengths decide how many bits per pixel the coded image needs.

The average codeword length LavgL_\text{avg}, its lower bound BavgB_\text{avg} and the coding redundancy RcodingR_\text{coding} are defined in entropy. LavgL_\text{avg} is the average number of bits per pixel of the coded image.

The smallest LavgL_\text{avg} is achieved by assigning the shortest codeword to the most probable grey level.

Decodability

Code

A code assigns a codeword to each grey level. A codeword is a finite sequence of bits.

  • Encoded stream
    Concatenation of the codewords of all pixels in order, with no separators.
  • Codebook
    The mapping between grey levels and codewords.

Unique Decodability

A code is uniquely decodable iff every encoded stream corresponds to exactly 1 sequence of grey levels.

  • Two different sequences of grey levels never produce the same encoded stream
  • The decoder can split the stream into codewords in only 1 way

A code that is not uniquely decodable has an ambiguous stream. With a→0a \to 0, b→01b \to 01 and c→10c \to 10, the stream 010 decodes as acac or as baba.

A uniquely decodable code can still need lookahead. With a→0a \to 0, b→01b \to 01 and c→011c \to 011, the codeword 0 is a prefix of 01, so the decoder must read further bits before it knows where a codeword ends.

Sardinas-Patterson Test

If a codeword uu is a proper prefix of a codeword v=uwv = uw, the non-empty remainder ww is a dangling suffix.

  1. Let S0S_0 be the set of codewords
  2. Let S1S_1 be the dangling suffixes of all codeword pairs in S0S_0
  3. Let Sn+1S_{n+1} be the non-empty remainders when a codeword in S0S_0 is a prefix of some w∈Snw \in S_n, or some w∈Snw \in S_n is a prefix of a codeword in S0S_0
  4. If any SnS_n contains a codeword, the code is not uniquely decodable
  5. If SnS_n is empty or repeats an earlier SkS_k with k≥1k \geq 1, the code is uniquely decodable
  6. Otherwise repeat from step 3

Prefix Code

A code is a prefix code iff no codeword is a prefix of another codeword.

  • Codewords sit only at the leaves of the code tree
  • A codeword is recognised as soon as its last bit is read, with no lookahead
  • Every prefix code is uniquely decodable
  • Huffman codes are prefix codes

A prefix code with codeword lengths l(0),…,l(L−1)l(0), \dots, l(L-1) exists iff the lengths satisfy the Kraft inequality:

∑k=0L−12−l(k)≤1\sum_{k=0}^{L-1} 2^{-l(k)} \le 1
  • The sum equals 1 iff the code tree is full, with no unused leaf
  • Every uniquely decodable code satisfies the same inequality

Decoding a prefix code:

  • Read bits until they match a codeword
  • Output the grey level and clear the bits read
  • Repeat from the next bit

Fixed Length Coding

All grey levels are assigned codewords of the same length.

l(k)=⌈log⁡2L⌉l(k) = \lceil \log_2 L \rceil
Here:
LL
number of grey levels
l(k)l(k)
codeword length of grey level kk

Easy to encode and decode. Allows random access to any pixel. Always uniquely decodable.

Lavg=∑k=0L−1l(k) P(k)=⌈log⁡2L⌉∑k=0L−1P(k)=⌈log⁡2L⌉L_\text{avg} = \sum_{k=0}^{L-1} l(k)\, P(k) = \lceil \log_2 L \rceil \sum_{k=0}^{L-1} P(k) = \lceil \log_2 L \rceil

LavgL_\text{avg} is the same for every image, regardless of the grey level probabilities. For an NN-pixel image, the coded size is b=N⌈log⁡2L⌉b = N \lceil \log_2 L \rceil bits.

Coding redundancy shows up when gray levels are not equiprobable. Otherwise, when LL is a power of 2, Lavg=BavgL_\text{avg} = B_\text{avg}.

Variable Length Coding

Grey levels are assigned codewords of different lengths. More probable grey levels get shorter codewords. Must remain uniquely decodable.

Achieves LavgL_\text{avg} close to the entropy BavgB_\text{avg}, with Lavg=BavgL_\text{avg} = B_\text{avg} only when every P(k)P(k) is a power of 12\frac{1}{2}.

Uniquely decodable iff every bit stream can be split into codewords in exactly 1 way.

The ideal length of grey level kk is its information content. Real codewords have integer lengths, so the ideal length is reached only when P(k)P(k) is a power of 12\frac{1}{2}.

lideal(k)=−log⁡2P(k)l(k)=⌈−log⁡2P(k)⌉l_\text{ideal}(k) = -\log_2 P(k) \qquad l(k) = \lceil -\log_2 P(k) \rceil

Satisfies the Kraft inequality.

Bavg≤Lavg<Bavg+1B_\text{avg} \le L_\text{avg} < B_\text{avg} + 1

Compared with a fixed length code:

CR=⌈log⁡2L⌉LavgCR = \frac{\lceil \log_2 L \rceil}{L_\text{avg}}

Huffman Coding

Produces the optimal variable length codeword allocation while preserving decodability. Reduces the source by merging the least probable grey levels, then assigns codes back through the reductions.

The code is optimal among prefix codes. Its average length satisfies:

Bavg≤LavgHuffman<Bavg+1B_\text{avg} \le L_\text{avg}^\text{Huffman} < B_\text{avg} + 1

Steps:

  1. List grey levels in descending order of probability
  2. Add the 2 lowest probabilities into 1 and re-sort the list
  3. Repeat until 2 probabilities remain
  4. Assign 0 and 1 to the last 2 probabilities
  5. Working backwards, append 0 and 1 to the code of every merged probability, one bit for each of the 2 probabilities it came from

Interpixel Redundancy

Correlated or repeating pixel patterns, such as texture or constant regions, can be represented more compactly than as independent pixel values.

Delta Coding

Transforms pixels into differences from a neighbour:

D(x,y)=I(x+1,y)−I(x,y)D(x,y) = I(x+1,y) - I(x,y)
Here:
I(x,y)I(x,y)
grey level at column xx and row yy
D(x,y)D(x,y)
difference between a pixel and its right neighbour

The first pixel of each row has no left neighbour, so it is stored unchanged. The decoder rebuilds the row by accumulating the differences:

I(x,y)=I(0,y)+∑i=0x−1D(i,y)I(x,y) = I(0,y) + \sum_{i=0}^{x-1} D(i,y)
  • Differences are typically small integers, since local pixels are correlated
  • The difference histogram peaks sharply at 0, so its entropy is lower than the entropy of the raw grey levels
  • Reduces correlation among pixel values, increasing coding efficiency
  • Lossless, since the accumulation recovers every pixel exactly

Image Pyramid Coding

Each layer stores the difference from the layer above, upscaled to match resolution. Removes correlation relative to the previous layer.

The image is repeatedly filtered with a Gaussian low-pass filter and downsampled to build layers of decreasing resolution:

G0=I,Gk+1=reduce(Gk)G_0 = I, \qquad G_{k+1} = \text{reduce}(G_k)

Each layer is predicted by upscaling the next coarser layer. Only the prediction error is stored:

Lk=Gk−expand(Gk+1)L_k = G_k - \text{expand}(G_{k+1})

The coarsest layer GKG_K is stored as is. The decoder starts there and works down to full resolution:

Gk=Lk+expand(Gk+1)G_k = L_k + \text{expand}(G_{k+1})
Here:
II
original image
GkG_k
image at level kk, with G0G_0 the full-resolution image
KK
index of the coarsest level
reduce\text{reduce}

Gaussian low-pass filtering followed by downsampling by 2 in each dimension

expand\text{expand}

upsampling by 2 in each dimension with interpolation

LkL_k
difference layer at level kk

Difference layers are mostly near 0 in smooth regions, so they have low entropy. The total number of samples is about 43\frac{4}{3} of the image size, since each level has 14\frac{1}{4} the samples of the one below. Compression comes from the lower entropy per sample.

Used for progressive image transmission, updating the receiver incrementally. The receiver shows GKG_K first, then sharpens it as each LkL_k arrives.

Run-Length Coding

Encodes a run of identical pixel values as (value,#times to repeat)(\text{value}, \#\text{times to repeat}) pairs rather than storing each pixel separately. Pixels are scanned row by row, and a run normally ends at the end of a row.

A run of rr pixels, with bvb_v bits per value and bcb_c bits per count, saves space iff:

r bv>bv+bc  ⟺  r>1+bcbvr\, b_v > b_v + b_c \iff r > 1 + \frac{b_c}{b_v}

For a row with nrunsn_\text{runs} runs and nn pixels:

bRLE=nruns (bv+bc)CR=n bvnruns (bv+bc)b_\text{RLE} = n_\text{runs}\,(b_v + b_c) \qquad CR = \frac{n\, b_v}{n_\text{runs}\,(b_v + b_c)}
  • Short runs can take more space than the raw pixels, so isolated pixels are a worst case
  • More effective on binary images, which more often contain large regions of constant value
  • In a binary image, runs alternate between 0 and 1. Only the first value and the run lengths need to be stored.

Bit-Plane Coding

Separates an mm-bit grey level image into mm binary bit-planes:

I(x,y)=∑k=0m−1ak(x,y) 2kI(x,y) = \sum_{k=0}^{m-1} a_k(x,y)\, 2^k
Here:
ak(x,y)a_k(x,y)

bit kk of the pixel at (x,y)(x,y), with k=0k = 0 the least significant bit

Plane kk is the binary image formed by aka_k over all pixels.

  • Lower order planes capture minor grey level changes
  • Higher order planes capture larger changes, and hold larger regions of constant value
  • Higher order planes compress better with schemes such as run-length coding

A small grey level change can flip many bits in the natural binary code, e.g. 127=01111111127 = 01111111 and 128=10000000128 = 10000000 differ in all 8 bits. This breaks runs in every plane. Gray code representation avoids it, since consecutive grey levels differ in exactly 1 bit:

gm−1=am−1,gk=ak⊕ak+1(0≤k<m−1)g_{m-1} = a_{m-1}, \qquad g_k = a_k \oplus a_{k+1} \quad (0 \le k < m-1)

The decoder recovers the original bits from the top plane downwards:

am−1=gm−1,ak=gk⊕ak+1a_{m-1} = g_{m-1}, \qquad a_k = g_k \oplus a_{k+1}
Here:
gkg_k
bit kk of the Gray coded pixel
⊕\oplus
exclusive OR

Psychovisual Redundancy

Not all image detail is equally perceivable. Removing imperceptible detail doesn’t affect apparent quality, but always loses information.

  • Re-quantizing with lower grey level depth
  • Gaussian filtering to remove noise and minor variations before coding

Re-quantizing an mm-bit image to m′m' bits keeps the top m′m' bits of each pixel:

I′(x,y)=⌊I(x,y)2m−m′⌋2m−m′0≤I(x,y)−I′(x,y)<2m−m′I'(x,y) = \left\lfloor \frac{I(x,y)}{2^{m-m'}} \right\rfloor 2^{m-m'} \qquad 0 \le I(x,y) - I'(x,y) < 2^{m-m'} CR=mm′CR = \frac{m}{m'}

Gaussian filtering replaces each pixel with a weighted average of its neighbourhood:

I′(x,y)=∑i,jh(i,j) I(x+i,y+j)∑i,jh(i,j)=1I'(x,y) = \sum_{i,j} h(i,j)\, I(x+i, y+j) \qquad \sum_{i,j} h(i,j) = 1
Here:
m,m′m, m'
bits per pixel before and after re-quantizing
I′(x,y)I'(x,y)
pixel value after the operation
h(i,j)h(i,j)
Gaussian weight at offset (i,j)(i,j)

Worked Examples

Fixed Length Code Sizes

Find the codeword length of a fixed length code for an 8bpp image (L=256L = 256) and for an image with 3 grey levels.

Solution Reveal Hide
l(k)=⌈log⁡2256⌉=8 bitsl(k) = \lceil \log_2 256 \rceil = 8 \text{ bits}l(k)=⌈log⁡23⌉=2 bitsl(k) = \lceil \log_2 3 \rceil = 2 \text{ bits}

For the 3 grey level image, log⁡23≈1.58\log_2 3 \approx 1.58, so the code wastes about 0.420.42 bits per pixel.

Fixed vs Variable Length Code

For the 3 grey level image in the entropy worked example, compare a fixed length code with a variable length code, using the codes below.

Grey levelP(k)P(k)Fixed codeVariable code
White0.5000
Grey0.250110
Black0.251011
Solution Reveal Hide

Fixed length code:

Lavg=2 bitsL_\text{avg} = 2 \text{ bits}

Variable length code:

Lavg=1(0.5)+2(0.25)+2(0.25)=1.5 bitsL_\text{avg} = 1(0.5) + 2(0.25) + 2(0.25) = 1.5 \text{ bits}CR=21.5≈1.33CR = \frac{2}{1.5} \approx 1.33

The variable length LavgL_\text{avg} equals BavgB_\text{avg}, so no coding redundancy remains.

Huffman Code

An image has 4 grey levels with probabilities 0.4, 0.3, 0.2, 0.1. Build a Huffman code and find its LavgL_\text{avg}.

Solution Reveal Hide
1 / 6
Original source Symbol Prob. Source reduction 1 2 a1a2a3a4 0.4 1 0.3 00 0.2 010 0.1 011 0.4 1 0.3 00 0.3 01 0.6 0 0.4 1
List the sources in descending order of probability. The last 2 have the lowest probabilities and are merged first.
Add the 2 lowest probabilities, 0.2 and 0.1, into 0.3. Place 0.3 in column 1 so the column stays in descending order. The other sources carry over.
Add the 2 lowest probabilities, 0.3 and 0.3, into 0.6. Place 0.6 in column 2 so the column stays in descending order. The other sources carry over. 2 sources remain, so the reduction stops.
Start from the last column. Assign 0 to the upper source and 1 to the lower source.
In column 1, the 0.6 source with code 0 splits into 0.3 and 0.3. Append 0 to the code of the upper source and 1 to the lower source. The other sources keep their codes.
In column 0, the 0.3 source with code 01 splits into 0.2 and 0.1. Append 0 to the code of the upper source and 1 to the lower source. The other sources keep their codes. These are the final codewords. Average length is 1.9 bits per pixel.

Codewords:

Grey levelPPCodewordll
a1a_10.411
a2a_20.3002
a3a_30.20103
a4a_40.10113
Lavg=0.4(1)+0.3(2)+0.2(3)+0.1(3)=1.9 bitsL_\text{avg} = 0.4(1) + 0.3(2) + 0.2(3) + 0.1(3) = 1.9 \text{ bits}Bavg=−0.4log⁡20.4−0.3log⁡20.3−0.2log⁡20.2−0.1log⁡20.1≈1.85 bitsB_\text{avg} = -0.4\log_2 0.4 - 0.3\log_2 0.3 - 0.2\log_2 0.2 - 0.1\log_2 0.1 \approx 1.85 \text{ bits}∑k2−l(k)=2−1+2−2+2−3+2−3=1\sum_k 2^{-l(k)} = 2^{-1} + 2^{-2} + 2^{-3} + 2^{-3} = 1Rcoding=Lavg−Bavg≈1.9−1.85=0.05 bitsR_\text{coding} = L_\text{avg} - B_\text{avg} \approx 1.9 - 1.85 = 0.05 \text{ bits}CR=21.9≈1.05CR = \frac{2}{1.9} \approx 1.05

A fixed length code needs 2 bits per pixel for 4 grey levels.

Checking Unique Decodability

Use the Sardinas-Patterson test on the code {1,011,01110,1110,10011}\{1, 011, 01110, 1110, 10011\}.

Solution Reveal Hide

S0={1,011,01110,1110,10011}S_0 = \{1, 011, 01110, 1110, 10011\}

S1S_1 comes from the codeword pairs where one is a prefix of the other.

  • 11 is a prefix of 11101110, with remainder 110110
  • 11 is a prefix of 1001110011, with remainder 00110011
  • 011011 is a prefix of 0111001110, with remainder 1010
S1={10,110,0011}S_1 = \{10, 110, 0011\}

No element of S1S_1 is a codeword. S2S_2 comes from S0S_0 and S1S_1.

  • 11 is a prefix of 1010, with remainder 00
  • 11 is a prefix of 110110, with remainder 1010
  • 1010 is a prefix of 1001110011, with remainder 011011
  • No other pair has a prefix relation
S2={0,10,011}S_2 = \{0, 10, 011\}

011011 is a codeword, so the code is not uniquely decodable. The stream 1110011 decodes as 11101110 followed by 011011, or as 11, 11, 1001110011.

Delta Coding of a Row

Delta code the row 100,102,101,101,105100, 102, 101, 101, 105, then decode it.

Solution Reveal Hide

The first pixel is stored unchanged. Every other value is the difference from its predecessor.

100, 102−100, 101−102, 101−101, 105−101=100, 2, −1, 0, 4100,\ 102 - 100,\ 101 - 102,\ 101 - 101,\ 105 - 101 = 100,\ 2,\ -1,\ 0,\ 4

The decoder accumulates the differences.

100, 100+2, 102−1, 101+0, 101+4=100, 102, 101, 101, 105100,\ 100 + 2,\ 102 - 1,\ 101 + 0,\ 101 + 4 = 100,\ 102,\ 101,\ 101,\ 105

Run-Length Coding of a Row

Run-length code the binary row 00011110010001111001.

Solution Reveal Hide

The row has 4 runs.

(0,3), (1,4), (0,2), (1,1)(0,3),\ (1,4),\ (0,2),\ (1,1)

With bv=1b_v = 1 and bc=3b_c = 3, the coded row takes 4×(1+3)=164 \times (1 + 3) = 16 bits against 1010 bits raw.

CR=10×14×(1+3)=0.625CR = \frac{10 \times 1}{4 \times (1 + 3)} = 0.625

The runs are too short, so the coded row is larger than the raw row.

Written by November 3, 2026 10 min read
Was this helpful?