Total Pageviews

Wednesday, December 2, 2026

Run Length Encoding (RLE)

RUN LENGTH ENCODING (RLE)

Digital Image Processing – Image Compression Technique

Lossless Compression | Spatial Redundancy Reduction

RLEImage CompressionWoods Chapter 8

1. Introduction

Run Length Encoding (RLE) is a simple lossless data compression technique. It reduces the size of data by replacing consecutive occurrences of the same symbol or pixel intensity with a pair containing the symbol and the number of times it is repeated.

A sequence of repeated pixel values is called a run. Instead of storing every pixel separately, RLE stores the pixel value and its run length.

RLE pair = (Pixel value, Run length)

Example:

AAAAABBBBCCCCC

RLE representation:

(A,5), (B,4), (C,5)
RLE does not discard image information. The original sequence can be reconstructed exactly from the encoded run-length pairs.

2. Why is RLE used in Digital Image Processing?

Many digital images contain large areas of the same or similar intensity values. For example, a binary image may contain long sequences of black pixels followed by long sequences of white pixels.

Storing every pixel individually requires more data. RLE represents consecutive identical pixels compactly.

Without RLE

0, 0, 0, 0, 0, 0, 1, 1, 1, 1

Ten individual pixel values are stored.

With RLE

(0,6), (1,4)

Only two run-length pairs are stored.

RLE is particularly useful for binary images, scanned documents, diagrams, icons, and images with large uniform regions.

3. Basic Working Principle

The encoder scans the image data in a predefined order, usually from left to right along each row. It counts consecutive pixels having the same intensity.

Step 1: Read

Read the first pixel.

Step 2: Compare

Compare the next pixel with the current pixel.

Step 3: Count

If both are equal, increase the run count.

Step 4: Encode

If the value changes, output the previous value and its count.

Step 5: Continue

Start a new run and continue scanning.

Step 6: Finish

Output the final run.

General example:

Input: A A A A B B C C C D D
Output: (A,4), (B,2), (C,3), (D,2)

4. Mathematical Representation

Let the input pixel sequence be:

X = {x₁, x₂, x₃, ..., xₙ}

For each consecutive group of identical values, RLE produces a pair:

(vᵢ, rᵢ)
  • vᵢ = pixel intensity or symbol value.
  • rᵢ = number of consecutive occurrences.
  • n = total number of input pixels.
  • k = total number of runs.
n = r₁ + r₂ + r₃ + ... + rₖ

For a valid sequence, each run has a positive length and adjacent runs have different values.

Compression Ratio

Compression Ratio (CR) = Original data size / Compressed data size

If CR is greater than 1, compression is achieved. If it is less than 1, the encoded data is larger than the original.

5. Step-by-Step Numerical Example – 1

Consider the following pixel sequence:

5, 5, 5, 5, 2, 2, 8, 8, 8, 1

Step 1: Start with the first pixel, 5.

Step 2: Count consecutive occurrences of 5. There are four occurrences.

Step 3: The next value is 2. Therefore, finish the first run.

Step 4: Count the two occurrences of 2.

Step 5: Count the three occurrences of 8.

Step 6: The final value 1 occurs once.

Pixel valueRun lengthEncoded pair
54(5,4)
22(2,2)
83(8,3)
11(1,1)
Encoded output = (5,4), (2,2), (8,3), (1,1)

Original sequence contains 10 pixel values. The RLE output contains 4 pairs.

For illustration, if every original pixel requires 8 bits and every encoded pair uses 8 bits for the pixel value plus 8 bits for the count, the original requires 80 bits and the encoded sequence requires 64 bits.
CR = 80 / 64 = 1.25

This example assumes an 8-bit count field and excludes file headers and other storage overhead.

6. Step-by-Step Numerical Example – 2 (Binary Image)

Consider a single row of a binary image:

0 0 0 0 0 0 1 1 1 1 0 0 0 0

Here, 0 represents black and 1 represents white.

Run numberPixel valueNumber of pixels
10 (Black)6
21 (White)4
30 (Black)4
RLE = (0,6), (1,4), (0,4)

For binary images, an alternative representation stores only run lengths if the first pixel value and the alternating black/white convention are known.

The decoder must know the starting pixel value and the scan-line convention. Otherwise, run lengths alone are ambiguous.

7. RLE Applied to a 2D Image

Consider a small grayscale image containing three rows:

000255255
00128128128
25525525500

Each row is encoded independently.

RowOriginal pixelsRLE representation
10,0,0,255,255(0,3), (255,2)
20,0,128,128,128(0,2), (128,3)
3255,255,255,0,0(255,3), (0,2)

Important: In two-dimensional image coding, row boundaries must be preserved. A run should not accidentally continue from the end of one row into the beginning of the next row unless the format explicitly defines a continuous scan.

8. RLE Encoding Algorithm

Pseudocode

Algorithm RLE_Encode(input)

1. Initialize an empty output list.
2. Set i = 0.
3. While i is less than the length of input:
      value = input[i]
      count = 1

      While the next element exists
      and input[i + count] = value:
          count = count + 1

      Add (value, count) to output.
      i = i + count

4. Return output.

Python Implementation

def rle_encode(data):
    if not data:
        return []

    encoded = []
    current = data[0]
    count = 1

    for value in data[1:]:
        if value == current:
            count += 1
        else:
            encoded.append((current, count))
            current = value
            count = 1

    encoded.append((current, count))
    return encoded


pixels = [5, 5, 5, 5, 2, 2, 8, 8, 8, 1]

result = rle_encode(pixels)

print("Original:", pixels)
print("Encoded:", result)

Expected output:

Original: [5, 5, 5, 5, 2, 2, 8, 8, 8, 1]
Encoded: [(5, 4), (2, 2), (8, 3), (1, 1)]

9. RLE Decoding Algorithm

The decoder reads each pair and repeats the pixel value according to its run length.

Decoded data = Repeat(value, run length)

Pseudocode

Algorithm RLE_Decode(encoded)

1. Initialize an empty output list.
2. For each pair (value, count):
      Repeat count times:
          Add value to output.
3. Return output.

Python Implementation

def rle_decode(encoded):
    decoded = []

    for value, count in encoded:
        decoded.extend([value] * count)

    return decoded


encoded = [(5, 4), (2, 2), (8, 3), (1, 1)]

original = rle_decode(encoded)

print("Decoded:", original)

Expected output:

Decoded: [5, 5, 5, 5, 2, 2, 8, 8, 8, 1]
RLE is a lossless method: the decoded sequence is identical to the original sequence when the encoded data and its format are preserved correctly.

10. Interactive RLE Encoder and Decoder

Enter pixel values separated by commas. The tool will encode the sequence into run-length pairs and decode it again.

Encoded and decoded results will appear here.

11. Applications of Run Length Encoding

1. Binary Images

Compression of black-and-white images containing large uniform regions.

2. Scanned Documents

Used in document images, text pages and fax-related image coding.

3. BMP Images

BMP supports RLE-based encoding modes for certain indexed and grayscale image formats.

4. Graphics and Icons

Useful for simple graphics with repeated colours or pixel values.

5. Image Compression Standards

Run-length techniques or run-length representations are used in different compression systems and coding stages.

6. Data Storage

Useful for repetitive sequences in certain structured data.

12. Advantages of RLE

  • Simple and easy to implement.
  • Lossless compression technique.
  • Fast encoding and decoding.
  • Requires relatively little computational power.
  • Effective for images with long runs of identical pixel values.
  • Suitable for binary images and simple graphics.
  • Original data can be reconstructed exactly.

13. Disadvantages of RLE

  • Not suitable for photographs containing frequent pixel variations.
  • May increase the size of data when runs are very short.
  • Compression efficiency depends on the distribution of repeated values.
  • Run-length counts require additional storage.
  • Encoding format must preserve row boundaries and run conventions.
  • Long runs may require special handling if the count field has a limited range.

14. Complexity Analysis

OperationTime complexityExplanation
EncodingO(n)Every input element is scanned once.
DecodingO(n)Every reconstructed output element is generated once.
Auxiliary spaceO(k)Encoded output contains k run pairs.

Here, n is the number of input pixels and k is the number of runs. The decoded output itself requires O(n) space when stored in memory.

15. RLE vs Other Compression Techniques

FeatureRLEHuffman CodingLZW
Basic ideaStore repeated values as runsVariable-length codes based on frequencyDictionary-based sequence coding
LosslessYesYesYes
Best suited forLong repeated sequencesUnequal symbol frequenciesRepeated patterns and sequences
ImplementationSimpleModerateModerate
WeaknessShort runs may expand dataNeeds code constructionDictionary management

16. Important Examination Questions

  1. Define Run Length Encoding.
  2. Explain the working principle of RLE with an example.
  3. Write the encoding and decoding algorithms of RLE.
  4. Explain how RLE is used in binary image compression.
  5. Calculate the RLE representation of a given pixel sequence.
  6. Discuss the advantages and disadvantages of RLE.
  7. Why is RLE suitable for images containing large uniform regions?
  8. Explain why RLE may increase the size of some images.
  9. Differentiate between RLE, Huffman coding and LZW coding.
  10. Discuss the time complexity of RLE encoding and decoding.

17. Conclusion

Run Length Encoding is a simple and effective lossless image compression method when an image contains consecutive identical pixel values. It reduces spatial redundancy by replacing repeated pixels with run-length pairs. Its performance depends on the number and length of runs in the image. It is particularly useful for binary images, scanned documents and simple graphics, but is less effective for complex natural photographs.

18. References

  1. Rafael C. Gonzalez and Richard E. Woods, Digital Image Processing, 3rd Edition, Chapter 8 – Image Compression, Section 8.2.5 – Run-Length Coding.
  2. Rafael C. Gonzalez and Richard E. Woods, Digital Image Processing, 4th Edition, Chapter 8 – Image Compression and Watermarking, Section 8.6 – Run-Length Coding.
  3. Gonzalez and Woods – Digital Image Processing, 4th Edition (reference PDF)
  4. Khan Academy – Lossless Image Compression

The numerical examples and interactive demonstration on this page are educational illustrations of the RLE principle.

ENCODER - DECODER MODEL

IMAGE ENCODER AND DECODER MODEL

Image Compression and Reconstruction

Based on Digital Image Processing by Gonzalez and Woods

Image Compression Encoder Decoder Lossless and Lossy

1. Introduction

An Encoder and Decoder Model is an important concept in Digital Image Processing. It is used to reduce the amount of data required to represent an image and reconstruct the image when it is decoded.

A digital image contains a large amount of information. Image compression techniques reduce the data by removing different types of redundancy.

The encoder converts the original image into a compressed representation. The decoder uses the compressed information to reconstruct the image.

Original Image → Encoder → Compressed Data

Compressed Data → Decoder → Reconstructed Image

According to Gonzalez and Woods, a general image compression system consists of three major encoding operations:

  1. Mapper
  2. Quantizer
  3. Symbol Coder

The corresponding decoder contains:

  1. Symbol Decoder
  2. Inverse Mapper
Important: The quantizer is responsible for irreversible information loss in lossy compression. It is omitted in error-free or lossless compression.

2. General Image Compression Model

The general model described by Gonzalez and Woods can be represented as follows.

Encoder Model

Input Image
f(x,y)
→ Mapper → Quantizer → Symbol Coder → Compressed Data

Decoder Model

Compressed Data → Symbol Decoder → Inverse Mapper → Output Image
f̂(x,y)
The encoder removes redundancies and creates a compact representation. The decoder reconstructs the image using the encoded information.

3. Components of an Image Encoder

3.1 Mapper

The mapper converts the original image into a different representation to reduce spatial or interpixel redundancy.

It transforms the image into a format that is more suitable for compression.

Examples:

  • Run-Length Coding (RLC)
  • Differential Pulse Code Modulation (DPCM)
  • Discrete Cosine Transform (DCT)
  • Wavelet Transform
Original Image → Mapper → Transformed Representation
A mapper may be reversible. It can reorganize image data without necessarily reducing the number of bits immediately. For example, a transform can concentrate information into a smaller number of significant coefficients.

3.2 Quantizer

The quantizer reduces the precision of the mapped image values by assigning them to a limited set of representative levels.

It is used to remove psychovisual redundancy by reducing information that is less noticeable to the human visual system.

Example:

Original Value = 127
Quantized Value = 120

The difference between the original and quantized value is the quantization error.

e = Original Value - Quantized Value
e = 127 - 120 = 7
Quantization is generally irreversible. Once information is discarded during quantization, the decoder cannot recover the exact original value.

3.3 Symbol Coder

The symbol coder converts the quantized values into binary codewords for efficient storage or transmission.

It reduces coding redundancy by assigning shorter codewords to frequently occurring symbols.

Examples:

  • Huffman Coding
  • Arithmetic Coding
  • Variable-Length Coding
Quantized Symbols → Binary Codewords
Symbol coding is generally reversible. The original quantized symbols can be recovered from the coded data.

4. Components of an Image Decoder

4.1 Symbol Decoder

The symbol decoder converts the compressed binary codewords back into the corresponding quantized symbols.

It performs the reverse operation of the symbol coder.

Compressed Data → Symbol Decoder → Quantized Symbols

4.2 Inverse Mapper

The inverse mapper converts the decoded representation back into the spatial image domain.

It performs the reverse operation of the mapper. For transform-based compression, it applies the corresponding inverse transform.

Examples:

  • Inverse DCT
  • Inverse Wavelet Transform
  • Inverse Predictive Mapping
  • Reconstruction of image blocks
Decoded Representation → Inverse Mapper → Reconstructed Image
The reconstructed image is represented by f̂(x,y). In lossless compression, it is identical to the original image. In lossy compression, some differences may exist.

5. Channel Encoder and Channel Decoder

In an image transmission system, the compressed data may pass through a communication channel.

To protect the compressed data from transmission errors, additional channel coding can be applied.

Channel Encoder

Adds redundancy to the compressed bitstream to help detect or correct errors during transmission.

Channel

The medium through which the data is transmitted, such as a wireless network, optical fibre or storage link.

Channel Decoder

Uses the added redundancy to detect or correct transmission errors before the image compression decoder processes the compressed data.

Source Encoder → Channel Encoder → Communication Channel → Channel Decoder → Source Decoder
Remember: Source coding performs image compression. Channel coding provides protection against transmission errors. They have different purposes.

6. Lossless and Lossy Compression Models

6.1 Lossless Compression

In lossless compression, the reconstructed image is exactly the same as the original image.

f̂(x,y) = f(x,y)

The quantizer is omitted because no image information should be discarded.

Examples:

  • Huffman Coding
  • Run-Length Coding
  • LZW Coding
Original Image → Reversible Mapper → Symbol Coder → Compressed Data

6.2 Lossy Compression

In lossy compression, some information is discarded during quantization to achieve a higher compression ratio.

f̂(x,y) ≠ f(x,y)

Examples:

  • JPEG compression
  • Transform Coding with Quantization
  • Wavelet-based lossy compression
Original Image → Mapper → Quantizer → Symbol Coder

7. Step-by-Step Numerical Example

Consider a simple grayscale image represented by the following pixel values:

Step 1: Original Image

120125128135
140145150155

Step 2: Mapping Operation

For illustration, consider a simple mapping operation that calculates the difference between consecutive pixel values in a row.

d(i) = f(i) - f(i-1)

For the first row:

120, 125, 128, 135

Mapped Values:
120, 5, 3, 7

For the second row:

140, 145, 150, 155

Mapped Values:
140, 5, 5, 5
120537
140555

The differences are much smaller than many of the original pixel values. This can make subsequent compression more effective.

Step 3: Quantization

Assume a simple quantizer with step size Δ = 4. For this example, quantization is performed using:

q = round(d / 4)

Quantization calculations:

Mapped ValueCalculationQuantized Value
120round(120/4)30
5round(5/4)1
3round(3/4)1
7round(7/4)2
140round(140/4)35
5round(5/4)1
5round(5/4)1
5round(5/4)1

Step 4: Symbol Coding

The quantized symbols can now be represented using binary codewords.

SymbolExample Codeword
10
210
30110
35111

The resulting illustrative compressed bitstream is:

110 | 0 | 0 | 10 | 111 | 0 | 0 | 0
The codewords above are an illustrative prefix code for this small example, not the output of a complete Huffman coding procedure. A real encoder constructs its code according to symbol frequencies.

Step 5: Decoding

The decoder reverses the operations:

  1. Symbol decoder recovers the quantized values.
  2. Inverse quantizer multiplies the values by 4 to obtain reconstructed differences.
  3. Inverse mapper adds the differences cumulatively to reconstruct the pixels.

Step 6: Reconstructed Values

First row:

30 × 4 = 120
1 × 4 = 4
1 × 4 = 4
2 × 4 = 8

Reconstruction:
120, 124, 128, 136

Second row:

35 × 4 = 140
1 × 4 = 4
1 × 4 = 4
1 × 4 = 4

Reconstruction:
140, 144, 148, 152

Original vs Reconstructed Image

Original Reconstructed
120120
125124
128128
135136
140140
145144
150148
155152
The reconstructed image is not exactly equal to the original because quantization has introduced errors. This is an example of lossy image compression.

8. Encoder Algorithm

IMAGE_ENCODER(Original_Image):

1. Read the original image.

2. MAPPED_DATA = MAPPER(Original_Image)

3. QUANTIZED_DATA = QUANTIZER(MAPPED_DATA)

4. COMPRESSED_DATA =
   SYMBOL_ENCODER(QUANTIZED_DATA)

5. Store or transmit COMPRESSED_DATA.

6. END

Decoder Algorithm

IMAGE_DECODER(Compressed_Data):

1. Read compressed data.

2. DECODED_SYMBOLS =
   SYMBOL_DECODER(Compressed_Data)

3. RECONSTRUCTED_IMAGE =
   INVERSE_MAPPER(DECODED_SYMBOLS)

4. Display reconstructed image.

5. END
For lossy compression, the quantization levels must be taken into account during reconstruction. The decoder uses the representative values associated with those quantization levels.

9. Types of Redundancy Removed by Encoder

1. Coding Redundancy

Occurs when more bits are used than necessary to represent the information. Symbol coding reduces this redundancy.

2. Interpixel Redundancy

Neighbouring pixels often have similar intensity values. Mapping operations such as predictive coding help reduce this redundancy.

3. Psychovisual Redundancy

Some image information is less noticeable to human vision. Quantization can remove or reduce this information.

RedundancyOperation
Coding RedundancySymbol Coder
Interpixel RedundancyMapper
Psychovisual RedundancyQuantizer

10. Performance Measurement of Image Compression

Compression Ratio

CR = Original Data Size / Compressed Data Size

For example, if an image requires 800 KB and the compressed image requires 200 KB:

CR = 800 / 200 = 4 : 1

Mean Squared Error (MSE)

MSE = (1/MN) Σ Σ [f(x,y) - f̂(x,y)]²

MSE measures the average squared difference between the original and reconstructed image.

Peak Signal-to-Noise Ratio (PSNR)

PSNR = 10 log10 (MAX² / MSE)

For an 8-bit grayscale image, MAX = 255. A higher PSNR generally indicates lower reconstruction error.

For a perfectly reconstructed image, MSE = 0 and PSNR is theoretically infinite.

11. Advantages of Encoder and Decoder Model

  • Reduced Storage: Compressed images require less storage space.
  • Faster Transmission: Smaller data can be transmitted more efficiently.
  • Flexible Design: Different mapping and coding methods can be combined.
  • Lossless Support: The model can preserve the exact original image.
  • Lossy Support: It can achieve higher compression by controlling image quality.
  • Efficient Processing: Each stage performs a specific operation.
  • Wide Applications: Used in image storage, communication and multimedia systems.

12. Disadvantages of Encoder and Decoder Model

  • Computational Cost: Some transformations and coding operations require significant processing.
  • Quality Loss: Lossy quantization can introduce image distortion.
  • Complexity: Advanced compression methods require more complicated encoding and decoding.
  • Memory Requirements: Intermediate image representations may require additional memory.
  • Encoding Time: Complex coding methods may increase processing time.
  • Compatibility: Encoder and decoder must follow compatible compression formats and parameters.

13. Applications

  • JPEG image compression.
  • Digital photography and image storage.
  • Medical image archiving and transmission.
  • Satellite and remote sensing image transmission.
  • Web image optimization.
  • Video compression systems.
  • Digital multimedia communication.
  • Image databases and cloud storage.

14. Interactive Encoder and Decoder Demonstration

Enter grayscale pixel values and observe the operations of the encoder and decoder. This demonstration uses predictive mapping, scalar quantization and a simple illustrative symbol representation.

Step 1: Input Image Pixel Values

Enter eight grayscale values separated by commas.

Step 2: Select Compression Type

Step 3: Quantization Step Size

The results will appear here after running the model.

15. Conclusion

The Encoder and Decoder Model is the foundation of image compression in Digital Image Processing.

The encoder uses a mapper, quantizer and symbol coder to reduce the amount of data required to represent an image. The decoder uses symbol decoding and inverse mapping to reconstruct the image.

In lossless compression, the reconstructed image is identical to the original. In lossy compression, quantization reduces the data size at the expense of some image quality.

Understanding this model helps students understand JPEG, predictive coding, transform coding and other image compression techniques.

16. References and Study Materials

Primary Textbook:

Rafael C. Gonzalez and Richard E. Woods, Digital Image Processing, 3rd Edition, Prentice Hall, Chapter 8 – Image Compression.

📘 Reference 1: Gonzalez and Woods – Digital Image Processing, 3rd Edition 📗 Reference 2: Chapter 8 – General Image Compression Model 📙 Reference 3: Image Compression – Encoder and Decoder Block Diagram

Bit Plane Coding (Bit Plane Slicing)

BIT PLANE CODING

Bit Plane Slicing and Image Compression

Digital Image Processing

Image Decomposition Binary Images Image Compression

1. Introduction to Bit Plane Coding

Bit Plane Coding is a technique used in Digital Image Processing to reduce image data by separating an image into individual binary bit planes and processing each plane separately.

A digital grayscale image generally contains 8 bits per pixel. Therefore, each pixel can represent an intensity value from 0 to 255.

Each 8-bit pixel can be decomposed into eight individual 1-bit planes. Each plane represents one particular bit position of every pixel in the image.

The higher-order bit planes contain most of the visually significant image information, whereas the lower-order bit planes generally contain finer intensity variations and subtle details.

Important Concept: An 8-bit grayscale image can be divided into eight binary images. These binary images can then be compressed individually using suitable binary coding techniques.

Characteristics

  • It is based on binary representation of pixel values.
  • An 8-bit image produces eight bit planes.
  • Each bit plane is a binary image.
  • Higher-order planes generally contain more visual information.
  • Individual planes can be processed and compressed separately.

2. Basic Concept of Bit Plane Decomposition

Suppose a grayscale image has 8 bits per pixel. Every pixel intensity can be represented in binary form.

8-bit pixel = b7b6b5b4 b3b2b1b0

The eight bits are separated into eight different planes.

Bit Plane Bit Position Weight Description
Plane 7MSB128Highest significance
Plane 6Bit 664High significance
Plane 5Bit 532High significance
Plane 4Bit 416Medium significance
Plane 3Bit 38Lower significance
Plane 2Bit 24Lower significance
Plane 1Bit 12Low significance
Plane 0LSB1Lowest significance
MSB: Most Significant Bit (Bit 7).
LSB: Least Significant Bit (Bit 0).

3. Mathematical Representation

An image pixel intensity can be expressed using binary polynomial representation.

For an 8-bit pixel:

f(x,y) = b727 + b626 + b525 + b424 + b323 + b222 + b121 + b020

Where:

  • f(x,y) = Original pixel intensity.
  • bk = Binary value (0 or 1) at bit position k.
  • k = Bit position from 0 to 7.
  • 2k = Weight of the corresponding bit.

Bit Plane Extraction Formula

Bk(x,y) = ⌊ f(x,y) / 2k ⌋ MOD 2

This formula extracts the kth bit of a pixel. The result is always either 0 or 1.

Image Reconstruction Formula

f(x,y) = Σ Bk(x,y) × 2k
k = 0 to 7

The original pixel value is reconstructed by multiplying each bit plane by its corresponding weight and adding the results.

4. Numerical Example of Bit Plane Decomposition

Consider a pixel having intensity value:

f(x,y) = 220

Step 1: Convert Decimal to Binary

Divide the decimal number by 2 repeatedly and collect the remainders.

DivisionQuotientRemainder
220 ÷ 21100
110 ÷ 2550
55 ÷ 2271
27 ÷ 2131
13 ÷ 261
6 ÷ 230
3 ÷ 211
1 ÷ 201
220 = (11011100)2

Step 2: Identify Individual Bits

Bit Position Bit Value Weight Contribution
71128128
616464
50320
411616
3188
2144
1020
0010

Step 3: Calculate Original Intensity

220 = 128 + 64 + 16 + 8 + 4

Therefore, the pixel value is reconstructed from the eight individual bit values.

Step 4: Final Bit Plane Values

B7 = 1, B6 = 1, B5 = 0, B4 = 1
B3 = 1, B2 = 1, B1 = 0, B0 = 0

5. Bit Plane Decomposition of an Image Matrix

Consider the following 2 × 3 grayscale image matrix:

Original Image Matrix

22015075
45128255

Binary Representation

22015075
110111001001011001001011
45128255
001011011000000011111111

Bit Plane 7 (MSB)

110
011

Bit Plane 6

101
001

Bit Plane 5

000
101

Bit Plane 4

110
001

Bit Plane 3

101
101

Bit Plane 2

110
101

Bit Plane 1

011
001

Bit Plane 0 (LSB)

001
101
Each matrix represents one binary image. All eight matrices together contain the complete information of the original image.

6. Bit Plane Coding Algorithm

Encoding Algorithm

  1. Read the original grayscale image.
  2. Convert each pixel into its binary representation.
  3. Separate the binary representation into individual bit planes.
  4. Generate eight binary images for an 8-bit grayscale image.
  5. Process each binary image separately.
  6. Apply a suitable binary compression method, such as run-length coding or another binary coding technique.
  7. Store or transmit the compressed bit planes along with the necessary coding information.

Pseudocode for Bit Plane Encoding

BIT_PLANE_ENCODING(Image):

1. Read the input grayscale image.

2. FOR k = 0 TO 7:

      Create an empty binary plane.

      FOR every pixel (x,y):

          Bk(x,y) = floor(Image(x,y) / 2^k) MOD 2

      END FOR

      Compress the binary plane.

      Store the compressed plane.

3. END FOR

4. Store required image and coding information.

5. END

Decoding Algorithm

  1. Read the compressed bit-plane data.
  2. Decode each individual binary plane.
  3. Initialize the reconstructed image with zero values.
  4. Multiply each decoded plane by its corresponding bit weight.
  5. Add all weighted planes.
  6. Obtain the reconstructed grayscale image.

Pseudocode for Decoding

BIT_PLANE_DECODING():

1. Initialize reconstructed image = 0.

2. FOR k = 0 TO 7:

      Decode bit plane Bk.

      Reconstructed Image =
      Reconstructed Image + Bk * 2^k

3. END FOR

4. Display reconstructed image.

5. END

7. Bit Plane Coding Flowchart

Original Image ↓ Binary Conversion ↓ Bit Plane Decomposition ↓ Eight Binary Images ↓ Individual Compression ↓ Compressed Bit Planes

Reconstruction Flow

Compressed Data → Decode Planes → Apply Bit Weights → Add Planes → Reconstructed Image

8. Importance of Higher and Lower Bit Planes

Higher-Order Bit Planes

Bit planes 7, 6, 5 and 4 generally contain most of the visually significant information in a grayscale image. They contribute more heavily to the overall intensity and structure of the image.

Lower-Order Bit Planes

Bit planes 3, 2, 1 and 0 generally contain smaller intensity variations and subtle image details. The lowest bit plane contributes only 0 or 1 to the original pixel intensity.

Important: Lower-order planes are not always meaningless noise. They can contain important edges, textures or fine details. The actual information distribution depends on the image.

Reconstruction Using Selected Planes

Suppose we reconstruct an image using only the four highest-order planes (7, 6, 5 and 4).

Ireconstructed = 128B7 + 64B6 + 32B5 + 16B4

The reconstructed intensity is an approximation of the original image. The omitted lower-order planes contribute to the difference.

9. Applications of Bit Plane Coding

1. Digital Image Compression

The individual binary planes can be compressed separately to reduce the amount of data required for image storage.

2. Medical Image Processing

Bit-plane analysis can help study the contribution of different intensity bits in medical images.

3. Image Enhancement

Selected bit planes can be analyzed to understand important structures and intensity variations.

4. Image Analysis

Separating the bit planes helps study the significance of different binary components of image pixels.

5. Digital Watermarking

Selected bit planes, particularly lower-order planes, can be used in certain watermarking techniques.

6. Image Transmission

Bit-plane based progressive transmission can send important image information before less significant details.

10. Advantages of Bit Plane Coding

  • Separate Processing: Each binary plane can be processed independently.
  • Lossless Decomposition: Keeping all planes preserves the original pixel values exactly.
  • Information Analysis: Helps identify which bits contribute most to image appearance.
  • Flexible Compression: Different compression methods can be applied to different planes.
  • Progressive Reconstruction: Important planes can be transmitted first.
  • Reduced Data: Selected planes can be discarded when approximate reconstruction is acceptable.
  • Simple Mathematical Representation: Based on binary representation and powers of two.

11. Disadvantages of Bit Plane Coding

  • Multiple Planes: An 8-bit image produces eight separate binary images.
  • Processing Overhead: Every plane needs separate processing and management.
  • Variable Compression: Some binary planes may not compress effectively.
  • Loss of Information: Discarding planes causes loss of the corresponding pixel information.
  • Complexity: Additional coding and reconstruction procedures are required.
  • Image Dependency: Compression performance depends on the distribution of bits and spatial patterns.
  • Storage Overhead: Separate plane storage and metadata can add overhead.

12. Bit Plane Slicing vs Bit Plane Coding

Feature Bit Plane Slicing Bit Plane Coding
Meaning Separates an image into binary planes. Separates and compresses individual binary planes.
Main Purpose Image analysis and visualization. Image data compression.
Output Binary images. Compressed binary-plane data.
Compression Not necessarily performed. Compression is applied.
Reconstruction Combine all planes using weights. Decode planes and combine using weights.

13. Conclusion

Bit Plane Coding is an important technique in Digital Image Processing. It decomposes a multilevel image into a set of binary images and processes each plane individually.

The higher-order planes generally contain more visually significant information, while lower-order planes contribute to finer intensity details.

By compressing individual bit planes, it is possible to reduce image data and support progressive image transmission. It is also useful for image analysis and understanding the contribution of individual bits to the overall image.

14. Interactive Bit Plane Coding Tool

Upload a grayscale or colour image. This tool converts it to grayscale, extracts all eight bit planes and demonstrates image reconstruction using selected planes.

Instructions: Select an image from your computer. The tool will automatically display the original grayscale image and its eight individual bit planes.

Original Grayscale Image

Please upload an image.

Eight Individual Bit Planes

Image Reconstruction

Select the number of highest-order bit planes to use for reconstruction.

Using bit planes 7 through 0.

Learning observation: Using all eight planes gives an exact reconstruction. Using fewer planes produces an approximation because the omitted lower-order bits are not included.

15. References and Study Materials

The following references provide additional explanations of bit-plane decomposition, mathematical concepts and applications in Digital Image Processing.

📘 Reference 1: NPTEL – Bit Plane Slicing 📗 Reference 2: Digital Image Processing – Bit Plane Slicing Lecture Notes 📙 Reference 3: Digital Image Processing – Bit Plane Coding and Decomposition

LZW CODING

LZW CODING TECHNIQUE

Lempel–Ziv–Welch Algorithm

Lossless Data Compression in Digital Image Processing

Lossless Compression Dictionary Based Image Processing

1. Introduction to LZW Coding

LZW stands for Lempel–Ziv–Welch. It is a dictionary-based, lossless data compression technique developed by Terry Welch in 1984, based on the earlier work of Abraham Lempel and Jacob Ziv.

LZW coding is used to reduce the size of data by identifying frequently occurring patterns or sequences and replacing them with shorter numerical codewords.

Unlike lossy compression techniques, LZW does not remove any original information. The compressed data can be decoded to reconstruct the exact original data.

Important Concept: LZW creates a dictionary of frequently occurring symbol sequences. Whenever a sequence is encountered again, its dictionary code is used instead of storing the complete sequence.

Basic Characteristics

  • It is a lossless compression technique.
  • It uses a dynamically generated dictionary.
  • It does not require prior knowledge of symbol probabilities.
  • It identifies repeated sequences in the input data.
  • It uses the same dictionary-building principle during encoding and decoding.

2. Working Principle of LZW Coding

The basic idea of LZW coding is to replace repeated character sequences with dictionary indices.

The algorithm works in the following way:

  1. Initially, the dictionary contains all individual symbols of the input alphabet.
  2. The encoder reads the input sequence from left to right.
  3. It searches for the longest sequence already available in the dictionary.
  4. The code corresponding to that sequence is generated.
  5. A new dictionary entry is created by combining the current sequence with the next input symbol.
  6. The process continues until the complete input is encoded.

Basic Compression Flow

Original Data → Dictionary Search → Generate Code → Update Dictionary → Compressed Data
Repeated Sequence → Dictionary Code

For example, if the sequence AB appears repeatedly, the algorithm can assign a new dictionary code to AB and use that code whenever the sequence occurs again.

3. Dictionary Initialization

Before compression starts, LZW initializes its dictionary with all possible individual symbols from the input alphabet.

Consider a simple alphabet containing only A and B. The initial dictionary is:

Dictionary Code Symbol / String
0A
1B

The next available dictionary code is 2. New sequences will be added starting from this code.

Example: If the input contains A B A B A B A, new dictionary entries such as AB, BA and ABA can be created.

4. LZW Encoding Algorithm

Step-by-Step Algorithm

  1. Initialize the dictionary with all individual input symbols.
  2. Set the current string W to the first input symbol.
  3. Read the next input symbol K.
  4. Check whether the combined string WK exists in the dictionary.
  5. If WK exists, set W = WK.
  6. Otherwise:
    • Output the dictionary code of W.
    • Add WK to the dictionary with the next available code.
    • Set W = K.
  7. Repeat until all input symbols are processed.
  8. Finally, output the dictionary code of W.

Pseudocode for LZW Encoder

LZW_ENCODING(INPUT):

1. Initialize dictionary with all single symbols.

2. W = first symbol of INPUT

3. FOR each next symbol K in INPUT:

      IF W + K exists in dictionary:

          W = W + K

      ELSE:

          OUTPUT code(W)

          Add W + K to dictionary

          W = K

4. OUTPUT code(W)

5. END
Remember: The encoder adds a new dictionary entry only when the combined sequence is not already present.

5. Numerical Example of LZW Encoding

Consider the following input sequence:

Input = ABABABA

Step 1: Initialize Dictionary

Code Symbol
0A
1B

Next available code = 2.

Step 2: Perform Encoding

Step Current W Next K WK Exists? Output Code New Entry
1 A B No 0 AB = 2
2 B A No 1 BA = 3
3 A B Yes — —
4 AB A No 2 ABA = 4
5 A B Yes — —
6 AB A Yes — —

Step 3: Final Dictionary

Code Sequence Type
0AInitial
1BInitial
2ABNew
3BANew
4ABANew

Step 4: Final Compressed Output

Original Input = ABABABA

Encoded Output = 0, 1, 2, 4
The original seven symbols are represented by four dictionary codes. This illustrates how repeated patterns can be represented more compactly.

Note: This example illustrates the dictionary coding process. Actual compression ratio depends on the bit width of the codes and the size of the original representation.

6. LZW Decoding Algorithm

Decoding is the reverse process of encoding. It reconstructs the original input from the compressed code sequence.

Steps

  1. Initialize the dictionary with the original single symbols.
  2. Read the first compressed code.
  3. Find its corresponding string in the dictionary.
  4. Output that string.
  5. Read the next code and find its corresponding string.
  6. Add a new dictionary entry by joining the previous decoded string with the first character of the current decoded string.
  7. Continue until all codes are decoded.

Pseudocode for LZW Decoder

LZW_DECODING(CODES):

1. Initialize dictionary with all single symbols.

2. Read first code.

3. W = dictionary[first code]

4. OUTPUT W

5. FOR each next code K:

      IF K exists in dictionary:

          ENTRY = dictionary[K]

      ELSE:

          ENTRY = W + first_character(W)

      OUTPUT ENTRY

      Add W + first_character(ENTRY)
      to dictionary

      W = ENTRY

6. END
Special Case: During decoding, a code may occasionally refer to the next dictionary entry that has not yet been created. In that case, the decoder reconstructs the entry as W followed by the first character of W.

7. Applications of LZW Coding

1. GIF Image Format

GIF uses LZW compression to reduce image data size while preserving the original pixel information.

2. TIFF Image Format

LZW is supported as a compression option in TIFF files. It is useful for images containing repeated pixel patterns.

3. PDF Documents

LZW has also been supported as a compression filter in PDF document processing.

4. Text File Compression

Repeated words, characters and sequences can be stored using dictionary codes to reduce data size.

5. General Data Compression

LZW-based methods have been used in general-purpose compression utilities and other data storage systems.

Image Processing Application: In an image, repeated pixel intensity sequences can be replaced with dictionary codes. This helps reduce the amount of data required to represent the image.

8. Advantages of LZW Coding

  • Lossless Compression: The original data can be reconstructed exactly.
  • Simple Algorithm: It is relatively easy to understand and implement.
  • No Probability Calculation: It does not require prior knowledge of symbol probabilities.
  • Fast Processing: It can perform compression efficiently using dictionary lookup.
  • Repeated Pattern Detection: It efficiently represents recurring sequences.
  • Dynamic Dictionary: New patterns are automatically added during encoding.
  • Useful for Images: It is suitable for images containing repeated pixel patterns.

9. Disadvantages of LZW Coding

  • Dictionary Memory: The algorithm requires additional memory to maintain the dictionary.
  • Poor Compression on Random Data: Data without repeated patterns may not compress effectively.
  • Dictionary Growth: The dictionary may become large and require a size limit or reset strategy.
  • Unused Entries: Some dictionary entries may never be used again.
  • Code Size: Fixed-width implementations may require more bits as the dictionary grows.
  • Not Always Efficient: Compression performance depends on the characteristics of the input data.

10. LZW Coding: Important Properties

Property Description
Compression Type Lossless
Approach Dictionary Based
Dictionary Dynamic
Input Text, symbols or image data
Output Dictionary codewords
Probability Information Not required in advance
Common Applications GIF, TIFF and other compression systems

11. Conclusion

LZW coding is an important dictionary-based lossless compression algorithm used in data and image compression.

It works by identifying repeated sequences, storing them in a dynamically constructed dictionary, and replacing those sequences with numerical codes.

Because it preserves all original information and does not require prior probability calculations, LZW is an important technique to study in Digital Image Processing and Data Compression.