# Image Compression Techniques: MATLAB's Solutions for Optimal Assignment Results

July 24, 2023

Sam Torent

Singapore

MATLAB

A highly skilled Image Compression expert specializing in MATLAB, with a strong educational background in Computer Science and extensive experience in the field. Graduated with a Master's degree in Computer Science from a renowned university, this expert possesses a proven track record of providing top-notch MATLAB-based solutions for Image Compression assignments.

To handle large volumes of image data, effective image compression has become essential due to the rising demand for multimedia content in a variety of industries. This blog post will go over some of the fundamental image compression methods that MATLAB offers, from lossless methods that ensure flawless image reconstruction to lossy methods that increase compression ratios by tolerating a certain amount of data loss.

## Lossless Image Compression Techniques

By ensuring that no data is lost during the compression process, lossless image compression techniques enable flawless reconstruction of the original image. These techniques are especially helpful when keeping every piece of information is essential.

### Run-Length Encoding (RLE)

One of the simplest and most user-friendly lossless image compression methods used in MATLAB is run-length encoding (RLE). It makes use of long runs of pixels with the same value, which are frequently found in binary or grayscale images. RLE stores the value and the length of each sequence rather than each individual pixel, which drastically reduces the amount of storage needed for such images.

When dealing with images that have sizable areas of uniform color, such as binary images or images with straightforward line drawings, RLE is particularly effective. The higher the compression achieved by RLE, the longer the uniform regions are. RLE might not be as effective for images with complex and varied content, though.

The following MATLAB code snippet implements RLE:

```
function compressed_image = rle_compress(image)
[m, n] = size(image);
compressed_image = [];
i = 1;
while i <= m
j = 1;
while j <= n
current_pixel = image(i, j);
count = 1;
j = j + 1;
while j <= n && image(i, j) == current_pixel
count = count + 1;
j = j + 1;
end
compressed_image = [compressed_image, current_pixel, count];
end
i = i + 1;
end
end
```

### Huffman Coding

Another popular lossless image compression method offered by MATLAB is Huffman coding. It uses a variable-length encoding technique where shorter codes are given to pixel values that occur more frequently and longer codes are given to those that do not. This allows for compression by using fewer bits to represent the most frequent pixel values.

Building the Huffman tree and producing Huffman codes are the two main components of the Huffman compression algorithm. The two least frequent symbols are repeatedly combined to create the tree until a full binary tree is formed. The codes are then produced by going through the tree from root to leaf node, with "0" standing for a left branch and "1" for a right branch.

When it comes to text data and grayscale images with clearly defined frequency distributions, Huffman coding is particularly helpful. For color images with intricate patterns and varying color distributions, it might not be as effective.

The following MATLAB code snippet implements Huffman compression:

```
function compressed_image = huffman_compress(image)
symbols = unique(image(:));
counts = histcounts(image(:), [symbols; max(symbols)+1]);
% Build Huffman tree
huffman_tree = hufftree(counts);
% Generate Huffman codes
huffman_codes = huffcodes(huffman_tree);
% Replace original pixel values with Huffman codes
compressed_image = huffman_codes(image(:))';
end
```

### Lempel-Ziv-Welch (LZW) Compression

A dictionary-based, lossless image compression method called Lempel-Ziv-Welch (LZW) is accessible in MATLAB. When compressing images with repeating patterns or sequences, it excels. When compressing images, LZW builds a dictionary of the pixel patterns it encounters and swaps out frequently occurring patterns with shorter codes. Considering that this method can produce images with high compression ratios, it is especially helpful for images with a lot of redundancy.

A dictionary is initialized with all potential pixel values as keys and their corresponding indices as values in order to perform the LZW compression algorithm. The image data is then processed, and as repeating patterns are found, they are added to the dictionary. The patterns in the compressed image are then represented by the codes for these patterns.

Several file formats, including the GIF image format, frequently employ LZW. It is a general-purpose compression method appropriate for images with both symmetric and asymmetric patterns.

Although there isn't a built-in LZW function in MATLAB, there are custom implementations available online or in the MATLAB File Exchange.

## Lossy Image Compression Techniques

In contrast to lossless methods, lossy image compression techniques permit some data loss during compression. Lossy compression achieves noticeably higher compression ratios even though it compromises the ability to reconstruct the original image perfectly. It is frequently used in situations where a small amount of image quality loss is acceptable.

### Discrete Cosine Transform (DCT)

Popular image formats like JPEG use the Discrete Cosine Transform (DCT), a widely used lossy image compression technique. It converts an image from the spatial to the frequency domain, where the majority of the energy is contained in a small number of low-frequency coefficients. Higher frequencies can be ignored by quantizing these coefficients, which results in data compression.

The 2D DCT is applied to each block of the image after it has been divided into small segments, typically 8x8 pixels, as part of the DCT-based image compression process. After that, a quantization matrix is divided by the obtained DCT coefficients to achieve quantization. Higher quantization values can be used to achieve higher compression ratios, but doing so also results in a greater loss of image quality.

The trade-off between image quality and compression ratio is greatly influenced by the choice of quantization matrix and quality factor. Higher compression is achieved at the expense of more pronounced image artifacts due to lower quality factors.

DCT's use in image compression is demonstrated by the following MATLAB code:

```
function compressed_image = dct_compress(image, quality_factor)
% Perform 2D DCT on the image
dct_image = dct2(image);
% Quantization step
quantization_matrix = create_quantization_matrix(quality_factor);
quantized_image = round(dct_image ./ quantization_matrix);
% Reconstruct the compressed image
compressed_image = idct2(quantized_image) + 128;
end
function quantization_matrix = create_quantization_matrix(quality_factor)
% Define the quantization matrix
base_quantization_matrix = [
16 11 10 16 24 40 51 61;
12 12 14 19 26 58 60 55;
14 13 16 24 40 57 69 56;
14 17 22 29 51 87 80 62;
18 22 37 56 68 109 103 77;
24 35 55 64 81 104 113 92;
49 64 78 87 103 121 120 101;
72 92 95 98 112 100 103 99
];
% Scale the matrix based on the quality factor
if quality_factor < 1
quality_factor = 1;
elseif quality_factor > 100
quality_factor = 100;
end
quantization_matrix = round(base_quantization_matrix * (100 / quality_factor));
end
```

### Wavelet-based Compression

A versatile lossy image compression method that provides a great balance between compression ratio and image quality is wavelet-based compression. It divides an image into various frequency bands using wavelet transforms. Compression can be achieved by removing high-frequency details by quantizing coefficients in the wavelet domain.

The wavelet transform separates an image into several subbands, including high-frequency subbands that capture noise and fine details and low-frequency subbands that contain crucial structural information. Each sub-band is subjected to a different set of quantization steps during the quantization process, giving users control over the compromise between image quality and compression ratio.

In particular, wavelet-based compression works well for natural images with intricate textures and structures. It is frequently used in image formats like JPEG2000 and is appropriate for uses where a small amount of image quality loss is tolerable.

Researchers and developers can quickly test out various wavelet transforms and quantization techniques thanks to MATLAB's Wavelet Toolbox, which offers thorough support for wavelet-based image compression.

## Hybrid Image Compression Techniques

In order to produce the best results, hybrid image compression techniques combine components of both lossless and lossy methods. They balance the compression ratio and image quality by utilizing the advantages of each approach.

### JPEG2000

JPEG2000 is a cutting-edge hybrid image compression standard that combines wavelet-based techniques for lossless compression with DCT-based quantization for lossy compression. In comparison to JPEG, this combination enables JPEG2000 to achieve higher compression ratios without suffering appreciable image quality loss.

The discrete wavelet transform, which divides an image into various frequency sub-bands, is the central component of the JPEG2000 compression algorithm. Each sub-band is then subjected to the quantization step, with the option of using various quantization matrices for various sub-bands. The adaptive quantization results in more effective compression and improved image quality.

Furthermore, JPEG2000 supports both lossless and lossy regions of interest, enabling lossy compression in some areas while enabling lossless compression in others.

JPEG2000 is a flexible compression standard used in a variety of contexts, such as digital cinema, satellite imagery, and medical imaging.

### WebP

Google created the cutting-edge image format known as WebP, which combines lossless and lossy compression techniques. To achieve high compression ratios and excellent image quality, it combines prediction, transform coding, and variable-length coding.

Predictive coding techniques are used in WebP's lossless mode to encode image data, resulting in compression ratios that are on par with PNG while preserving high-quality images. On the other hand, the lossy mode makes use of the VP8 video codec, which is based on DCT, to produce high compression ratios that are comparable to JPEG but with better visual quality.

WebP's capacity to provide smaller image sizes without sacrificing visual fidelity has helped it gain popularity online. WebP is a compelling option for web developers looking to reduce the time it takes for pages to load because most popular web browsers support it.

### MATLAB's Built-in Functions for Image Compression

A variety of built-in tools and functions in MATLAB make image compression tasks easier. Particularly for putting the above-discussed methods into practice, the Image Processing Toolbox, Signal Processing Toolbox, and Wavelet Toolbox all offer a variety of functions.

For instance, the Image Processing Toolbox has functions for managing image data, using different filtering strategies, and putting the Run-Length Encoding (RLE) technique into practice. The Discrete Cosine Transform (DCT) and other frequency domain transformations are supported by the Signal Processing Toolbox. The Wavelet Toolbox offers functions for wavelet analysis, including wavelet-based image compression.

Additionally, users are able to adapt and combine these functions using MATLAB's robust programming environment to create hybrid compression solutions that are catered to particular use cases.

In conclusion, MATLAB provides a complete range of lossless and lossy image compression methods that are appropriate for a variety of applications and needs. The preferred compression method is determined by the particular requirements, the attributes of the image, and the acceptable trade-off between compression ratio and image quality. Researchers, engineers, and developers can investigate and put into practice the best image compression solutions for their projects and assignments by utilizing the capabilities of MATLAB and its toolboxes