VISVESVARAYA TECHNOLOGICAL UNIVERSITY
Jnana Sangama, Belagavi, Karnataka - 590 018
MULTIMEDIA COMMUNICATION (BCE613A)
ASSIGNMENT SUBMISSION
BACHELOR OF ENGINEERING
In
Electronics and Telecommunication Engineering
Submitted by:
Aaditya J Krishna (1BI22ET001)
DEPARTMENT OF ELECTRONICS AND TELECOMMUNICATION ENGINEERING
BANGALORE INSTITUTE OF TECHNOLOGY
K.R. Road, V.V.Pura, Bengaluru-560004
Submitted on: 12-05-2025
AADITYA J KRISHNA 2024-2025
QUESTIONS
1. Explain & implement Huffman Coding(dynamic) in MATLAB for data compression.
Simulate the Compression & Decompression of any sample text. Calculate the
compression ratio.
2. Simulate Differential PCM for audio compression in MATLAB, record or load an audio
signal, apply DPCM and reconstruct the signal. Analyze the signal Distortion &
Compression Efficiency.
3. Simulate motion estimation & compensation for video compression in MATLAB. [Load
a video, sequence of frames, compute motion vectors using block matching &
reconstruct the predicted frames].
4. Compare uniform & non-uniform quantization techniques for audio compression using
MATLAB. [Simulate both methods on an audio file & evaluate their impact on audio
quality & bitrate]
5. Implement 2D DCT based intraframe video compression in MATLAB. [Compress each
frame of video using 2D DCT Quantization, and inverse DCT, compare original &
reconstructed frames using PSNR]
6. Compare & contrast lossless & lossy image compression using MATLAB. [Use PNG &
JPEG formats respectively & analyze image quality, file size & compression ratio]
7. Simulate & implement arithmetic coding in MATLAB for text data compression. [Text
is your name]
8. Perform wavelet-based image compression using MATLAB. [Use relevant wavelet
functions in MATLAB & evaluate the quality of compressed image by varying wavelet
families]
Department of Electronics and Telecommunication Engineering 2
AADITYA J KRISHNA 2024-2025
1. Explain & implement Huffman Coding(dynamic) in MATLAB for data compression.
Simulate the Compression & Decompression of any sample text. Calculate the
compression ratio.
SOLUTION:-
MATLAB CODE:-
function Q1
% Huffman Coding Implementation in MATLAB
% Sample text
text = 'Aaditya J Krishna';
fprintf('Original Text: %s\n', text);
% Step 1: Frequency Analysis
freq = containers.Map;
for i = 1:length(text)
char = text(i);
if isKey(freq, char)
freq(char) = freq(char) + 1;
else
freq(char) = 1;
end
end
chars = keys(freq);
freqs = values(freq);
% Step 2: Build Huffman Tree
nodes = cell(length(chars), 1);
for i = 1:length(chars)
nodes{i} = {freqs{i}, chars{i}, [], []}; % {weight, char, left, right}
end
while length(nodes) > 1
[~, idx] = sort(cellfun(@(x) x{1}, nodes));
nodes = nodes(idx);
left = nodes{1};
Department of Electronics and Telecommunication Engineering 3
AADITYA J KRISHNA 2024-2025
right = nodes{2};
parent = {left{1} + right{1}, '', left, right};
nodes = [nodes(3:end); {parent}];
end
root = nodes{1};
% Step 3: Generate Huffman Codes
codes = containers.Map;
traverse(root, '');
% Step 4: Encode
encoded = '';
for i = 1:length(text)
encoded = [encoded codes(text(i))];
end
fprintf('Encoded Text: %s\n', encoded);
% Step 5: Decode
decoded = '';
node = root;
for i = 1:length(encoded)
bit = encoded(i);
if bit == '0'
node = node{3};
else
node = node{4};
end
if isempty(node{3}) && isempty(node{4})
decoded = [decoded node{2}];
node = root;
end
end
fprintf('Decoded Text: %s\n', decoded);
% Step 6: Validation
if strcmp(text, decoded)
fprintf('Decompression Successful: Original and Decoded texts match.\n');
else
Department of Electronics and Telecommunication Engineering 4
AADITYA J KRISHNA 2024-2025
fprintf('Decompression Failed: Texts do not match.\n');
end
% Step 7: Compression Ratio
original_bits = length(text) * 8;
compressed_bits = length(encoded);
compression_ratio = original_bits / compressed_bits;
fprintf('Original Size: %d bits\n', original_bits);
fprintf('Compressed Size: %d bits\n', compressed_bits);
fprintf('Compression Ratio: %.2f\n', compression_ratio);
% --- Nested function for Huffman Code generation ---
function traverse(node, code)
if isempty(node{3}) && isempty(node{4})
codes(node{2}) = code;
else
if ~isempty(node{3})
traverse(node{3}, [code '0']);
end
if ~isempty(node{4})
traverse(node{4}, [code '1']);
end
end
end
end
OUTPUT:-
Department of Electronics and Telecommunication Engineering 5
AADITYA J KRISHNA 2024-2025
2. Simulate Differential PCM for audio compression in MATLAB, record or load an audio
signal, apply DPCM and reconstruct the signal. Analyze the signal Distortion &
Compression Efficiency.
SOLUTION:-
MATLAB CODE:-
% DPCM Audio Compression and Reconstruction for MP3 File
clc;
clear;
% Step 1: Load MP3 audio file
[audio_signal, fs] = audioread('Sample.mp3'); % Replace with your file
% Convert stereo to mono if needed
if size(audio_signal, 2) == 2
audio_signal = mean(audio_signal, 2);
end
% Normalize audio to range [-1, 1]
audio_signal = audio_signal / max(abs(audio_signal));
% Step 2: DPCM Encoding
% Compute difference between adjacent samples
diff_signal = diff(audio_signal); % First-order difference
% Uniform quantization
num_levels = 256; % 8-bit quantization
max_val = max(abs(diff_signal));
step_size = 2 * max_val / (num_levels - 1); % Quantization step
quantized_diff = round(diff_signal / step_size) * step_size; % Quantization
% Step 3: DPCM Decoding (Reconstruction)
reconstructed_signal = zeros(size(audio_signal));
reconstructed_signal(1) = audio_signal(1); % Initial sample
for i = 2:length(audio_signal)
reconstructed_signal(i) = reconstructed_signal(i-1) + quantized_diff(i-1);
end
Department of Electronics and Telecommunication Engineering 6
AADITYA J KRISHNA 2024-2025
% Step 4: Analysis
% Mean Squared Error (Distortion)
mse = mean((audio_signal - reconstructed_signal).^2);
% Compression efficiency
original_bits = length(audio_signal) * 16; % 16-bit PCM original
compressed_bits = length(quantized_diff) * 8; % 8-bit DPCM
compression_ratio = original_bits / compressed_bits;
% Display results
fprintf('--- DPCM Analysis ---\n');
fprintf('Mean Squared Error (MSE): %.6f\n', mse);
fprintf('Compression Ratio: %.2f:1\n', compression_ratio);
% Step 5: Plot comparison
figure;
subplot(2,1,1);
plot(audio_signal(1:1000));
title('Original Audio Signal (First 1000 Samples)');
xlabel('Sample Index');
ylabel('Amplitude');
subplot(2,1,2);
plot(reconstructed_signal(1:1000));
title('Reconstructed Audio Signal (First 1000 Samples)');
xlabel('Sample Index');
ylabel('Amplitude');
% Step 6: Optional - Playback
fprintf('Playing Original Audio...\n');
sound(audio_signal, fs);
pause(length(audio_signal)/fs + 1);
fprintf('Playing Reconstructed Audio...\n');
sound(reconstructed_signal, fs);
Department of Electronics and Telecommunication Engineering 7
AADITYA J KRISHNA 2024-2025
OUTPUT:-
Department of Electronics and Telecommunication Engineering 8
AADITYA J KRISHNA 2024-2025
3. Simulate motion estimation & compensation for video compression in MATLAB. [Load
a video, sequence of frames, compute motion vectors using block matching &
reconstruct the predicted frames].
SOLUTION:-
MATLAB CODE:-
% Parameters
close all;
clear all;
clc;
block_size = 16; % Block size
search_range = 8; % Search range
scale_factor = 0.75; % Downscale to 2880x1620
max_frames = 354; % Intended frames
output_dir = 'C:\Users\aadit\OneDrive\Desktop\MMC Assignment'; % Output directory
output_video_path = fullfile(output_dir, 'Venice_10_output.mp4'); % Changed to avoid
overwrite
% Ensure output directory exists
if ~exist(output_dir, 'dir')
mkdir(output_dir);
end
% Test write permissions
test_file = fullfile(output_dir, 'test_write.txt');
fid = fopen(test_file, 'w');
if fid == -1
error('Cannot write to %s. Permission denied.', output_dir);
end
fclose(fid);
delete(test_file);
% Load the video
video_path = 'C:\Users\aadit\OneDrive\Desktop\MMC Assignment\Venice_10.mp4';
video = VideoReader(video_path);
fprintf('Video loaded: %s\n', video.Name);
% Initialize output video writer
Department of Electronics and Telecommunication Engineering 9
AADITYA J KRISHNA 2024-2025
video_writer = VideoWriter(output_video_path, 'MPEG-4');
video_writer.FrameRate = video.FrameRate;
open(video_writer);
% Read the first frame
reference_frame = readFrame(video);
reference_frame = imresize(reference_frame, scale_factor);
writeVideo(video_writer, reference_frame);
% Initialize arrays for metrics
mse_values = zeros(max_frames-1, 1);
psnr_values = zeros(max_frames-1, 1);
h = fspecial('gaussian', [5 5], 1.5); % Deblocking filter
frame_count = 1;
while hasFrame(video) && frame_count < max_frames
frame_count = frame_count + 1;
current_frame = readFrame(video);
current_frame = imresize(current_frame, scale_factor);
fprintf('Processing frame %d\n', frame_count);
reference_y = rgb2ycbcr(reference_frame); reference_y = reference_y(:,:,1);
current_y = rgb2ycbcr(current_frame); current_y = current_y(:,:,1);
[motion_dx, motion_dy] = compute_motion_vectors(reference_y, current_y,
block_size, search_range);
predicted_frame = motion_compensation(reference_frame, motion_dx, motion_dy,
block_size, search_range);
for c = 1:3
predicted_frame(:,:,c) = imfilter(predicted_frame(:,:,c), h, 'replicate');
end
writeVideo(video_writer, predicted_frame);
residual = double(current_frame) - double(predicted_frame);
mse = mean((double(current_frame(:)) - double(predicted_frame(:))).^2);
psnr = 10 * log10((255^2) / mse);
mse_values(frame_count-1) = mse;
psnr_values(frame_count-1) = psnr;
Department of Electronics and Telecommunication Engineering 10
AADITYA J KRISHNA 2024-2025
fprintf('Frame %d: MSE = %.2f, PSNR = %.2f dB\n', frame_count, mse, psnr);
if frame_count == 2
num_blocks_h = size(motion_dx, 1);
num_blocks_w = size(motion_dx, 2);
[X, Y] = meshgrid((block_size/2):block_size:(num_blocks_w*block_size-
block_size/2), ...
(block_size/2):block_size:(num_blocks_h*block_size-block_size/2));
figure('Name', 'Motion Vectors for Frame 2', 'Visible', 'off');
imshow(reference_y); hold on;
quiver(X, Y, motion_dx, motion_dy, 'r');
title('Motion Vectors for Frame 2 (Luminance)');
saveas(gcf, fullfile(output_dir, 'motion_vectors_frame2.png'));
imwrite(predicted_frame, fullfile(output_dir, 'predicted_frame2.png'));
imwrite(uint8(residual + 128), fullfile(output_dir, 'residual_frame2.png'));
close(gcf);
end
reference_frame = current_frame;
end
close(video_writer);
fprintf('Reconstructed video saved as: %s\n', output_video_path);
fprintf('Average MSE: %.2f\n', mean(mse_values));
fprintf('Average PSNR: %.2f dB\n', mean(psnr_values));
% Compute motion vectors
function [motion_dx, motion_dy] = compute_motion_vectors(reference_frame,
current_frame, block_size, search_range)
[height, width] = size(reference_frame);
num_blocks_h = floor(height / block_size);
num_blocks_w = floor(width / block_size);
motion_dx = zeros(num_blocks_h, num_blocks_w, 'int16');
motion_dy = zeros(num_blocks_h, num_blocks_w, 'int16');
padded_reference = padarray(reference_frame, [search_range, search_range], 'replicate',
'both');
for m = 1:num_blocks_h
for n = 1:num_blocks_w
Department of Electronics and Telecommunication Engineering 11
AADITYA J KRISHNA 2024-2025
i = (m-1)*block_size + 1;
j = (n-1)*block_size + 1;
current_block = current_frame(i:i+block_size-1, j:j+block_size-1);
min_sad = inf;
best_dx = 0;
best_dy = 0;
for dx = -search_range:search_range
for dy = -search_range:search_range
i_ref = i + dx + search_range;
j_ref = j + dy + search_range;
if i_ref+block_size-1 > size(padded_reference,1) || j_ref+block_size-1 >
size(padded_reference,2)
continue;
end
ref_block = padded_reference(i_ref:i_ref+block_size-1,
j_ref:j_ref+block_size-1);
sad = sum(abs(double(current_block(:)) - double(ref_block(:))));
if sad < min_sad
min_sad = sad;
best_dx = dx;
best_dy = dy;
end
end
end
motion_dx(m,n) = best_dx;
motion_dy(m,n) = best_dy;
end
end
end
% Motion compensation
function predicted_frame = motion_compensation(reference_frame, motion_dx,
motion_dy, block_size, search_range)
[height, width, channels] = size(reference_frame);
predicted_frame = zeros(height, width, channels, 'uint8');
padded_reference = padarray(reference_frame, [search_range, search_range], 'replicate',
'both');
for m = 1:size(motion_dx, 1)
Department of Electronics and Telecommunication Engineering 12
AADITYA J KRISHNA 2024-2025
for n = 1:size(motion_dx, 2)
dx = motion_dx(m,n);
dy = motion_dy(m,n);
i = (m-1)*block_size + 1;
j = (n-1)*block_size + 1;
i_pad = i - dx + search_range;
j_pad = j - dy + search_range;
if i_pad+block_size-1 > size(padded_reference,1) || j_pad+block_size-1 >
size(padded_reference,2)
continue;
end
predicted_block = padded_reference(i_pad:i_pad+block_size-1,
j_pad:j_pad+block_size-1, :);
predicted_frame(i:i+block_size-1, j:j+block_size-1, :) = predicted_block;
end
end
end
OUTPUT:-
Department of Electronics and Telecommunication Engineering 13
AADITYA J KRISHNA 2024-2025
4. Compare uniform & non-uniform quantization techniques for audio compression using
MATLAB. [Simulate both methods on an audio file & evaluate their impact on audio
quality & bitrate]
SOLUTION:-
MATLAB CODE:-
clc;
clear;
close all;
% Load Audio
[audioIn, fs] = audioread('NCS 2.mp3');
audioIn = audioIn(:,1); % Use mono
audioIn = audioIn / max(abs(audioIn)); % Normalize to [-1, 1]
nBits = 8; % Number of quantization bits
L = 2^nBits;
%% Uniform Quantization
uniformStep = 2 / L;
quant_uniform = round(audioIn / uniformStep) * uniformStep;
mse_uniform = mean((audioIn - quant_uniform).^2);
snr_uniform = snr(audioIn, audioIn - quant_uniform);
% Non-uniform Quantization (μ-law Companding)
mu = 255;
% Companding
companded = sign(audioIn) .* log(1 + mu * abs(audioIn)) / log(1 + mu);
% Uniform quantization on companded signal
quant_mu = round(companded * (L/2)) / (L/2);
% Expanding
reconstructed = sign(quant_mu) .* ((1 + mu).^abs(quant_mu) - 1) / mu;
mse_mu = mean((audioIn - reconstructed).^2);
snr_mu = snr(audioIn, audioIn - reconstructed);
%% Bitrate Calculation
bitrate = fs * nBits; % Mono
Department of Electronics and Telecommunication Engineering 14
AADITYA J KRISHNA 2024-2025
fprintf('--- Results ---\n');
fprintf('Bitrate: %.2f kbps\n\n', bitrate / 1000);
fprintf('Uniform Quantization:\n\tSNR = %.2f dB\n\tMSE = %.6f\n\n', snr_uniform,
mse_uniform);
fprintf('Non-uniform (μ-law):\n\tSNR = %.2f dB\n\tMSE = %.6f\n', snr_mu, mse_mu);
%% Plotting
t = (0:length(audioIn)-1)/fs;
figure;
subplot(3,1,1);
plot(t, audioIn);
title('Original Audio');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,2);
plot(t, quant_uniform);
title('Uniform Quantized Audio');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,3);
plot(t, reconstructed);
title('Non-uniform (μ-law) Quantized Audio');
xlabel('Time (s)');
ylabel('Amplitude');
% Optional Listening (Uncomment to listen)
% sound(audioIn, fs); pause(2);
% sound(quant_uniform, fs); pause(2);
% sound(reconstructed, fs);
%% --- Optional Saving (Uncomment to save) ---
% audiowrite('uniform_quantized.wav', quant_uniform, fs);
% audiowrite('mu_law_quantized.wav', reconstructed, fs);
Department of Electronics and Telecommunication Engineering 15
AADITYA J KRISHNA 2024-2025
OUTPUT:-
Department of Electronics and Telecommunication Engineering 16
AADITYA J KRISHNA 2024-2025
5. Implement 2D DCT based intraframe video compression in MATLAB. [Compress each
frame of video using 2D DCT Quantization, and inverse DCT, compare original &
reconstructed frames using PSNR]
SOLUTION:-
MATLAB CODE:-
% Clear workspace and close all figures
clear all;
close all;
% Load video
videoFile = 'Venice_10.mp4'; % Replace with your video file path
vidObj = VideoReader(videoFile);
% Parameters
blockSize = 8; % Size of DCT block (8x8 pixels)
quantizationScale = 50; % Quantization scaling factor (adjust for quality)
% Quantization matrix (JPEG-like for luminance)
quantMatrix = [
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;
Department of Electronics and Telecommunication Engineering 17
AADITYA J KRISHNA 2024-2025
72 92 95 98 112 100 103 99
];
% Read all frames
numFrames = floor(vidObj.Duration * vidObj.FrameRate);
frames = cell(1, numFrames);
reconstructedFrames = cell(1, numFrames);
for i = 1:numFrames
frameRGB = readFrame(vidObj);
% Convert to YCbCr color space
frames{i} = rgb2ycbcr(frameRGB);
end
% Process each frame
height = size(frames{1}, 1);
width = size(frames{1}, 2);
psnrValues = zeros(1, numFrames);
for f = 1:numFrames
inputFrame = double(frames{f});
outputFrame = zeros(size(inputFrame));
% Process each color channel (Y, Cb, Cr)
for channel = 1:3
% Scale quantization matrix for chrominance channels
Department of Electronics and Telecommunication Engineering 18
AADITYA J KRISHNA 2024-2025
if channel > 1
qMatrix = quantMatrix * 1.5; % Stronger quantization for Cb, Cr
else
qMatrix = quantMatrix;
end
qMatrix = qMatrix * (quantizationScale / 50); % Adjust quantization
% Process each block
for y = 1:blockSize:height
for x = 1:blockSize:width
% Extract block
yEnd = min(y + blockSize - 1, height);
xEnd = min(x + blockSize - 1, width);
block = inputFrame(y:yEnd, x:xEnd, channel);
% Pad block if necessary
if size(block, 1) < blockSize || size(block, 2) < blockSize
block(end+1:blockSize, end+1:blockSize) = 0;
end
% Apply 2D DCT
dctBlock = dct2(block);
% Quantization
quantBlock = round(dctBlock ./ qMatrix);
Department of Electronics and Telecommunication Engineering 19
AADITYA J KRISHNA 2024-2025
% Inverse Quantization
iQuantBlock = quantBlock .* qMatrix;
% Inverse 2D DCT
iDctBlock = idct2(iQuantBlock);
% Place reconstructed block back
outputFrame(y:yEnd, x:xEnd, channel) = iDctBlock(1:yEnd-y+1, 1:xEnd-x+1);
end
end
end
% Convert reconstructed frame back to uint8
reconstructedFrames{f} = uint8(outputFrame);
% Compute PSNR
mse = mean((double(frames{f}) - double(reconstructedFrames{f})).^2, 'all');
if mse == 0
psnrValues(f) = inf;
else
psnrValues(f) = 10 * log10((255^2) / mse);
end
fprintf('PSNR for Frame %d: %.2f dB\n', f, psnrValues(f));
end
% Save reconstructed video
outputVideo = VideoWriter('reconstructed_video.mp4', 'MPEG-4');
Department of Electronics and Telecommunication Engineering 20
AADITYA J KRISHNA 2024-2025
outputVideo.FrameRate = vidObj.FrameRate;
open(outputVideo);
% Write reconstructed frames to video
for f = 1:numFrames
writeVideo(outputVideo, ycbcr2rgb(reconstructedFrames{f}));
end
% Close the video file
close(outputVideo);
% Visualize Results (Show first 9 frames to avoid clutter)
figure('Position', [100, 100, 1200, 600]);
for f = 1:min(numFrames, 9)
% Convert frames back to RGB for display
subplot(2, min(numFrames, 9), f);
imshow(ycbcr2rgb(frames{f}));
title(['Original Frame ', num2str(f)]);
subplot(2, min(numFrames, 9), f + min(numFrames, 9));
imshow(ycbcr2rgb(reconstructedFrames{f}));
title(['Reconstructed Frame ', num2str(f)]);
end
% Display average PSNR
avgPSNR = mean(psnrValues(isfinite(psnrValues)));
fprintf('Average PSNR: %.2f dB\n', avgPSNR);
Department of Electronics and Telecommunication Engineering 21
AADITYA J KRISHNA 2024-2025
OUTPUT:-
Department of Electronics and Telecommunication Engineering 22
AADITYA J KRISHNA 2024-2025
6. Compare & contrast lossless & lossy image compression using MATLAB. [Use PNG &
JPEG formats respectively & analyze image quality, file size & compression ratio]
SOLUTION:-
MATLAB CODE:-
% Initialize
clear;
clc;
close all;
% 2. Load Image
% Use built-in grayscale image for simplicity
img = imread('cameraman.tif');
[rows, cols] = size(img);
% 3. Save Images
% PNG (lossless)
imwrite(img, 'temp_png.png');
% JPEG (lossy, quality 70)
imwrite(img, 'temp_jpeg.jpg', 'Quality', 70);
% 4. Read Saved Images
png_img = imread('temp_png.png');
jpeg_img = imread('temp_jpeg.jpg');
% 5. Calculate File Sizes
% Sizes in KB
png_size = dir('temp_png.png').bytes / 1024;
jpeg_size = dir('temp_jpeg.jpg').bytes / 1024;
% Uncompressed size (grayscale: 1 byte per pixel)
raw_size = rows * cols / 1024;
% 6. Calculate Compression Ratios
png_ratio = raw_size / png_size;
jpeg_ratio = raw_size / jpeg_size;
% 7. Calculate Image Quality (PSNR)
% PNG: Should be identical to original
Department of Electronics and Telecommunication Engineering 23
AADITYA J KRISHNA 2024-2025
png_mse = mean((double(img) - double(png_img)).^2, 'all');
png_psnr = 10 * log10(255^2 / max(png_mse, eps)); % Avoid divide-by-zero
% JPEG: Lossy, expect some quality loss
jpeg_mse = mean((double(img) - double(jpeg_img)).^2, 'all');
jpeg_psnr = 10 * log10(255^2 / jpeg_mse);
% 8. Display Results
disp('=== Compression Analysis ===');
disp(['Image: ', num2str(rows), ' x ', num2str(cols), ' pixels']);
disp(['Uncompressed Size: ', num2str(raw_size, '%.1f'), ' KB']);
disp('--- PNG (Lossless) ---');
disp(['File Size: ', num2str(png_size, '%.1f'), ' KB']);
disp(['Compression Ratio: ', num2str(png_ratio, '%.1f'), ':1']);
disp(['PSNR: ', num2str(png_psnr, '%.1f'), ' dB (Inf = perfect)']);
disp('--- JPEG (Lossy, Q=70) ---');
disp(['File Size: ', num2str(jpeg_size, '%.1f'), ' KB']);
disp(['Compression Ratio: ', num2str(jpeg_ratio, '%.1f'), ':1']);
disp(['PSNR: ', num2str(jpeg_psnr, '%.1f'), ' dB']);
% 9. Visualize Images
figure('Name', 'Image Comparison');
subplot(1, 3, 1); imshow(img); title('Original');
subplot(1, 3, 2); imshow(png_img); title('PNG');
subplot(1, 3, 3); imshow(jpeg_img); title('JPEG');
% 10. Clean Up
delete('temp_png.png');
delete('temp_jpeg.jpg');
Department of Electronics and Telecommunication Engineering 24
AADITYA J KRISHNA 2024-2025
OUTPUT:-
Department of Electronics and Telecommunication Engineering 25
AADITYA J KRISHNA 2024-2025
7. Simulate & implement arithmetic coding in MATLAB for text data compression. [Text
is your name]
SOLUTION:-
MATLAB CODE:-
% Arithmetic Coding for Text Compression
% Text: "Aaditya J Krishna"
clear all; close all; clc;
digits(50); % Use variable precision for accuracy
% Input text (your name)
text = 'Aaditya J Krishna';
fprintf('Original text: %s\n', text);
% Step 1: Character probability analysis
unique_chars = unique(text);
num_chars = length(unique_chars);
freq = zeros(1, num_chars);
% Calculate frequency
for i = 1:num_chars
freq(i) = sum(text == unique_chars(i));
end
% Probabilities and cumulative probabilities
prob = freq / sum(freq);
[unique_chars_sorted, sorted_indices] = sort(unique_chars);
prob = prob(sorted_indices);
cum_prob = [0, cumsum(prob)];
% Display character probabilities
fprintf('\nCharacter probabilities:\n');
for i = 1:num_chars
fprintf('Char %c: Prob = %.3f, Cum_Prob = [%.6f, %.6f)\n', ...
unique_chars_sorted(i), prob(i), cum_prob(i), cum_prob(i+1));
end
Department of Electronics and Telecommunication Engineering 26
AADITYA J KRISHNA 2024-2025
% Step 2: Arithmetic Encoding using variable precision
low = vpa(0);
high = vpa(1);
for i = 1:length(text)
idx = find(unique_chars_sorted == text(i));
range = high - low;
high = low + range * vpa(cum_prob(idx+1));
low = low + range * vpa(cum_prob(idx));
fprintf('Encoding %c: Interval = [%.10f, %.10f)\n', text(i), low, high);
end
encoded_value = (low + high) / 2;
fprintf('\nEncoded value: %.10f\n', encoded_value);
% Step 3: Arithmetic Decoding using same precision
decoded = '';
low = vpa(0);
high = vpa(1);
value = encoded_value;
for i = 1:length(text)
range = high - low;
scaled_value = (value - low) / range;
idx=find(vpa(cum_prob(1:end-1))<=scaled_value&scaled_value<
vpa(cum_prob(2:end)), 1);
decoded = [decoded, unique_chars_sorted(idx)];
high = low + range * vpa(cum_prob(idx+1));
low = low + range * vpa(cum_prob(idx));
end
fprintf('\nDecoded text: %s\n', decoded);
% Step 4: Compression statistics
original_bits = length(text) * 8;
compressed_bits = ceil(double(-log2(high - low)));
fprintf('\nOriginal length: %d bits (assuming 8 bits/char)\n', original_bits);
fprintf('Compressed length: %d bits (approx, using log2(1/range))\n', compressed_bits);
Department of Electronics and Telecommunication Engineering 27
AADITYA J KRISHNA 2024-2025
OUTPUT:-
Department of Electronics and Telecommunication Engineering 28
AADITYA J KRISHNA 2024-2025
8. Perform wavelet-based image compression using MATLAB. [Use relevant wavelet
functions in MATLAB & evaluate the quality of compressed image by varying wavelet
families]
SOLUTION:-
MATLAB CODE:-
% Wavelet-Based Image Compression with Quality Evaluation
% Compresses an image using different wavelet families and evaluates quality
clear all; close all; clc;
% Load sample grayscale image
img = imread('cameraman.tif'); % 256x256 grayscale image
if size(img, 3) == 3
img = rgb2gray(img); % Convert to grayscale if RGB
end
img = double(img); % Convert to double for processing
[m, n] = size(img);
% Define wavelet families to test
wavelet_families = {'haar', 'db4', 'sym4'};
num_families = length(wavelet_families);
% Compression parameters
level = 3; % Decomposition level
retain_percent = 0.1; % Retain 10% of largest coefficients (compression ratio)
num_coeffs = m * n; % Total number of coefficients
num_retain = round(retain_percent * num_coeffs); % Number of coefficients to retain
% Initialize arrays to store results
psnr_values = zeros(num_families, 1);
mse_values = zeros(num_families, 1);
compressed_images = cell(num_families, 1);
% Process each wavelet family
for w = 1:num_families
wavelet = wavelet_families{w};
fprintf('Processing wavelet: %s\n', wavelet);
Department of Electronics and Telecommunication Engineering 29
AADITYA J KRISHNA 2024-2025
% Step 1: Perform 2D DWT
[C, S] = wavedec2(img, level, wavelet); % Multi-level 2D DWT
% Step 2: Threshold coefficients for compression
% Sort coefficients by absolute value
[sorted_coeffs, sort_idx] = sort(abs(C(:)), 'descend');
% Set threshold to keep top retain_percent coefficients
threshold = sorted_coeffs(num_retain);
% Zero out coefficients below threshold
C_compressed = C;
C_compressed(abs(C) < threshold) = 0;
% Calculate compression ratio
nonzero_coeffs = nnz(C_compressed);
compression_ratio = num_coeffs / nonzero_coeffs;
fprintf(' Compression ratio: %.2f:1\n', compression_ratio);
% Step 3: Reconstruct image
img_reconstructed = waverec2(C_compressed, S, wavelet);
% Ensure reconstructed image is same size as original
img_reconstructed = img_reconstructed(1:m, 1:n);
% Step 4: Evaluate quality
mse = mean((img(:) - img_reconstructed(:)).^2);
mse_values(w) = mse;
max_pixel = 255; % Assuming 8-bit image
psnr_values(w) = 10 * log10((max_pixel^2) / mse);
fprintf(' MSE: %.2f, PSNR: %.2f dB\n', mse, psnr_values(w));
% Store compressed image
compressed_images{w} = img_reconstructed;
end
% Step 5: Visualize results
figure('Name', 'Wavelet-Based Image Compression Results');
subplot(2, 2, 1);
imshow(uint8(img), []);
Department of Electronics and Telecommunication Engineering 30
AADITYA J KRISHNA 2024-2025
title('Original Image');
xlabel(sprintf('Size: %dx%d pixels', m, n));
for w = 1:num_families
subplot(2, 2, w+1);
imshow(uint8(compressed_images{w}), []);
title(sprintf('Compressed (%s)\nPSNR: %.2f dB', ...
wavelet_families{w}, psnr_values(w)));
xlabel(sprintf('MSE: %.2f', mse_values(w)));
end
% Display summary
fprintf('\nSummary of Compression Results:\n');
fprintf('Wavelet\tPSNR (dB)\tMSE\n');
for w = 1:num_families
fprintf('%s\t%.2f\t\t%.2f\n', wavelet_families{w}, psnr_values(w), mse_values(w));
end
% Save compressed images (optional)
for w = 1:num_families
imwrite(uint8(compressed_images{w}),
sprintf('compressed_%s.tif', wavelet_families{w}));
end
Department of Electronics and Telecommunication Engineering 31
AADITYA J KRISHNA 2024-2025
OUTPUT:-
Department of Electronics and Telecommunication Engineering 32