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.

No comments:

Post a Comment