Image Compression Basics with MATLAB Code
Advertisement
This section covers the basics of image compression algorithms and provides image compression MATLAB source codes.
Here is a simple image compression MATLAB code using Discrete Cosine Transform (DCT), which is a common technique similar to JPEG compression.
MATLAB Source code
clc;
clear;
close all;
% Read image
img = imread('peppers.png'); % You can change this to your image file
img = im2double(rgb2gray(img)); % Convert to grayscale and double
% Set block size (8x8 is standard in JPEG)
blockSize = 8;
% Define DCT and inverse DCT function handles
dctFunc = @(block_struct) dct2(block_struct.data);
idctFunc = @(block_struct) idct2(block_struct.data);
% Apply DCT block-wise
dct_blocks = blockproc(img, [blockSize blockSize], dctFunc);
% Compression: keep only top-left NxN coefficients (simulate quantization)
N = 4; % Keep top-left NxN (you can try N=2, 4, 6 for different quality)
compressed_blocks = blockproc(dct_blocks, [blockSize blockSize], ...
@(block_struct) compressBlock(block_struct.data, N));
% Apply inverse DCT
reconstructed_img = blockproc(compressed_blocks, [blockSize blockSize], idctFunc);
% Display results
figure;
subplot(1,3,1); imshow(img); title('Original Image');
subplot(1,3,2); imshow(log(abs(dct_blocks)+1), []); title('DCT Coefficients');
subplot(1,3,3); imshow(reconstructed_img); title('Reconstructed Image');
% Compression Ratio Estimate
original_size = numel(img);
compressed_size = (N^2) * (size(img,1)/blockSize) * (size(img,2)/blockSize);
compression_ratio = original_size / compressed_size;
fprintf('Estimated Compression Ratio: %.2f:1\n', compression_ratio);
% Helper function to zero out high-frequency components
function out = compressBlock(block, N)
temp = zeros(size(block));
temp(1:N, 1:N) = block(1:N, 1:N); % keep only top-left NxN
out = temp;
end
Algorithm
Following steps summarize the DCT algorithm for image compression.
- Divides the image into 8x8 blocks.
- Applies 2D DCT to each block.
- Zeros out the higher frequency DCT coefficients beyond NxN.
- Reconstructs the image using inverse DCT.
- Displays the original and compressed images.
Advertisement