Compressing Images using Cosine Transform
Note:Before compression, the file size was 31 MB, and after compression, it reduced to 10 MB.
This is a Python project that demonstrates image compression using the Discrete Cosine Transform (DCT) and quantization. The DCT is applied to 8×8 blocks of the image, and quantization is used to reduce the amount of data required to represent each block. The compressed image is then decompressed to recover the original image.
Prerequisites
Make sure you have the following Python libraries installed:
numpy
PIL
(Pillow)matplotlib
Algorithm Overview
The project performs the following steps:
- Load an input image.
- Separate the image into its RGB color channels.
- Apply scaling by subtracting 127 from each color channel.
- Perform a 2D Discrete Cosine Transform (DCT) on 8×8 blocks of each color channel.
- Quantize the DCT coefficients using a predefined quantization matrix.
- Compress the quantized coefficients by run-length encoding.
- Decompress the run-length encoded data to obtain the quantized coefficients.
- Perform the inverse quantization.
- Apply the inverse DCT to recover the transformed blocks.
- Mix the color channels back together.
- Show the original and reconstructed images.
- Calculate the distance between the original and reconstructed images.
Note
- The compression rate and zeros rate are calculated and displayed as metrics.
- The distance between the original and reconstructed images is calculated using the L2 norm.