You are on page 1of 21

Lab Report

Course Code: ECE410


Course Title: Multimedia Communication Sessional
Date Of Submission: 04.01.2024

Submitted By: Submitted To:


Md. Ruhanur Iftekhar Mahfujur Rahman
Level: 04, Semester: I Lecturer
Id:1902163 Department Of ECE

Faculty of Computer Science and Engineering


Department Of Electronics and Communication Engineering
Hajee Mohammad Danesh Science and Technology University, Dinajpur-5200.
Experiment No.:01
Experiment Name: Write a MATLAB code to perform the following operations on image(s). (i)
Addition (ii) Subtraction (iii) Multiplication (iv) Division.
i)Addition:
Matlab Code:
clc
clear all
close all
A= imread('Bangladesh Nature.JPG');
B= imread('Bangladesh Nature1.JPG');
C=A+B;
subplot(1,3,1), imshow(A), title('Image-1');
subplot(1,3,2), imshow(B), title('Image-2');
subplot(1,3,3), imshow(C), title('Final Result');

Output:
ii)Subtraction:
Matlab Code:
clc
clear all
close all
A= imread('Bangladesh Nature.JPG');
B= imread('Bangladesh Nature1.JPG');
C=A-B;
subplot(1,3,1), imshow(A), title('Image-1');
subplot(1,3,2), imshow(B), title('Image-2');
subplot(1,3,3), imshow(C), title('Final Result');

Output:
iii)Multiplication:
Matlab Code:
clc
clear all
close all
A= imread('Bangladesh Nature.JPG');
B= imread('Bangladesh Nature1.JPG');
C= immultiply(A,B);
subplot(1,3,1), imshow(A), title('Image-1');
subplot(1,3,2), imshow(B), title('Image-2');
subplot(1,3,3), imshow(C), title('Final Result');

Output:

iv) Division:

Matlab Code:
clear all
close all
A= imread('Bangladesh Nature.JPG');
B= imread('Bangladesh Nature1.JPG');
C= imdivide(A,B);
subplot(1,3,1), imshow(A), title('Image-1');
subplot(1,3,2), imshow(B), title('Image-2');
subplot(1,3,3), imshow(C), title('Final Result');

Output:

Discussion: Getting the same size image for the given experiment. If the size of the image is not
the same, then resize it. Carefully write the code.
Experiment No.:02
Experiment Name: Write a MATLAB code that takes gray image as input and finds its
complement using (i) Built in function (ii) User defined function.
Matlab Code:
a= imread('flower.jpeg');
imshow(a);
b=rgb2gray(a);
c=imcomplement(b);
subplot(221);imshow(a);title('original image');
subplot(222);imshow(b);title('Converted image from RGB to gray');
subplot(223);imshow(c);title('Complement image');

Output:

Discussion:
We take a picture then convert the picture int gray image. Finally, we complement the gray
image.

Experiment No.: 03
Experiment name: Take a color image as input and show its different channels using MATLAB.
Matlab Code:
colorImg = imread("1902163.jpg");
if size(colorImg, 3) ~= 3
error('The provided image is not a color image.');
end
redChannel = colorImg(:, :, 1);
greenChannel = colorImg(:, :, 2);
blueChannel = colorImg(:, :, 3);
figure;
subplot(2,2,1), imshow(colorImg), title('Original Image');
subplot(2,2,2), imshow(redChannel), title('Red Channel');
subplot(2,2,3), imshow(greenChannel), title('Green Channel');
subplot(2,2,4), imshow(blueChannel), title('Blue Channel');
end
Output:

Discussion:
After writing the code we get the output. We need to write the code carefully.
Experiment No.: 04
Experiment Name: Write a MATLAB code to take a gray image as input and show its histogram
using (i) Built in function (ii) User defined function.
Matlab Code:
% Read the input image
grayImg = imread("Bangladesh Nature.JPG");
% Ensure the image is in grayscale
if size(grayImg, 3) == 3
grayImg = rgb2gray(grayImg);
end
% Display histogram using MATLAB's built-in function
figure;
subplot(1,2,1);
imhist(grayImg);
title('Histogram (Built-in Function)');
% Display histogram using user-defined function
subplot(1,2,2);
userDefinedHistogram(grayImg);
title('Histogram (User Defined Function)');
end
function userDefinedHistogram(img)
% Initialize a zeros array for histogram
h = zeros(256, 1);
% Calculate the histogram
for i = 1:size(img, 1)
for j = 1:size(img, 2)
h(img(i,j)+1) = h(img(i,j)+1) + 1;
end
end

Output:
Discussion:
Write the code carefully. After writing the code on Matlab, I get the output.

Experiment No.: 05
Experiment Name: Write a MATLAB code to find the edge(s) of an image using the following
edge detector operators (i) Sobel edge detector (ii) Roberts edge detector (iii) Prewitt edge
detector.
Matlab Code:
% Read the input image
originalImg = imread("1902163.jpg");
% Convert to grayscale if it is a color image
if size(originalImg, 3) == 3
originalImg = rgb2gray(originalImg);
end
% Apply Sobel edge detector
sobelEdges = edge(originalImg, 'sobel');
% Apply Roberts edge detector
robertsEdges = edge(originalImg, 'roberts');
% Apply Prewitt edge detector
prewittEdges = edge(originalImg, 'prewitt');
% Display images
figure;
subplot(2,2,1), imshow(originalImg), title('Original Image');
subplot(2,2,2), imshow(sobelEdges), title('Sobel Edge Detection');
subplot(2,2,3), imshow(robertsEdges), title('Roberts Edge Detection');
subplot(2,2,4), imshow(prewittEdges), title('Prewitt Edge Detection');
end
Output:
Discussion:Write the code correctly and after writing the above code I get the output.
Experiment No.:06
Experiment name: Write a MATLAB code that takes an image (gray/color) as input, add salt &
pepper noise, and remove the noise using both mean and median filters. (i) Show the input
image, noisy image, and restored (filtered) images (ii) Calculate Mean Square Error (MSE)
between original image and restored image.
Matlab Code:
originalImg = imread("cat.jpeg");
% Convert to grayscale if it is a color image
if size(originalImg, 3) == 3
originalImg = rgb2gray(originalImg);
end
% Add salt & pepper noise
noisyImg = imnoise(originalImg, 'salt & pepper', 0.02);
% Apply mean filter
meanFilteredImg = imfilter(noisyImg, fspecial('average', 3));
% Apply median filter
medianFilteredImg = medfilt2(noisyImg);
% Display images
figure;
subplot(2,2,1), imshow(originalImg), title('Original Image');
subplot(2,2,2), imshow(noisyImg), title('Noisy Image');
subplot(2,2,3), imshow(meanFilteredImg), title('Mean Filtered Image');
subplot(2,2,4), imshow(medianFilteredImg), title('Median Filtered Image');
% Calculate and display MSE
mseMean = immse(double(originalImg), double(meanFilteredImg));
mseMedian = immse(double(originalImg), double(medianFilteredImg));
disp(['MSE with Mean Filter: ', num2str(mseMean)]);
disp(['MSE with Median Filter: ', num2str(mseMedian)]);
end
Output:

Discussion:
Firstly, we need to take an image. Convert the image to gray image and add noise, apply mean
filter and median filter. After doing that i get the output.
Experiment No.:07
Experiment name: Implement the Run Length Encoding and Decoding algorithms using
MATLAB. Also calculate the compression ratio if we use 8 bits to represent a character and four
bits to represent a digit.
Matlab Code:
input_sequence = 'AAAABBB1122CDDDDDD';
fprintf('Original Sequence: %s\n', input_sequence);
clc
clear
close all
% Run Length Encoding
encoded_sequence = runLengthEncode(input_sequence);
fprintf('Encoded Sequence: %s\n', encoded_sequence);
% Run Length Decoding
decoded_sequence = runLengthDecode(encoded_sequence);
fprintf('Decoded Sequence: %s\n', decoded_sequence);
% Calculation of Compression Ratio
original_bits = calculateBits(input_sequence);
encoded_bits = calculateBits(encoded_sequence);
compression_ratio = original_bits / encoded_bits;
fprintf('Compression Ratio: %.2f\n', compression_ratio);
% Run Length Encoding (RLE) Function
function encoded = runLengthEncode(input_sequence)
count = 1;
encoded = '';
for i = 1:length(input_sequence)
if i < length(input_sequence) &&input_sequence(i) ==
input_sequence(i+1)
count = count + 1;
else
encoded = [encoded num2str(count) input_sequence(i)];
count = 1;
end
end
end
% Function to Calculate Bits Required for a String Representation
function bits = calculateBits(sequence)
bits_per_character = 8; % Bits to represent a character
bits_per_digit = 4; % Bits to represent a digit
character_count = sum(isletter(sequence));
digit_count = sum(isstrprop(sequence, 'digit'));
bits = (character_count * bits_per_character) + (digit_count *
bits_per_digit);
end
% Run Length Decoding Function
function decoded = runLengthDecode(encoded_sequence)
decoded = '';
idx = 1;
whileidx<= length(encoded_sequence)
count = str2double(encoded_sequence(idx));
for i = 1:count
decoded = [decoded encoded_sequence(idx+1)];
end
idx = idx + 2;
end
end

Input:
AAAABBB1122CDDDDDD

Output:
Original Sequence: AAAABBB1122CDDDDDD
Encoded Sequence: 4A3B21221C6D
Decoded Sequence: AAAABBB1122CDDDDDD
Compression Ratio: 2.25

Discussion:
The experiment involved implementing Run Length Encoding (RLE) and Decoding algorithms in
MATLAB for strings containing characters and digits, while calculating the compression ratio
based on character and digit bit representations.
Experiment no:08
Experiment name: Implement the Huffman Encoding and Decoding
algorithms using MATLAB. Also calculate the compression ratio if we
use 8 bits to represent a character and four bits to represent a
digit.
Matlab Code:
symbols = [1:6]; % A vector of integers
p = [.5 .125 .125 .125 .0625 .0625]; % A vector of probabilities
bps = ceil(log2(max(symbols))); % Bits per symbol
% Create a Huffman dictionary
dict = huffmandict(symbols,p);
% Generate a vector of random symbols
inputSig = randsrc(100,1,[symbols;p]);
% Encode the data
code = huffmanenco(inputSig,dict);
% Decode the data
sig = huffmandeco(code,dict);
% Verify that the decoded data matches the original data
isequal(inputSig,sig);
% Convert the original data to binary
binarySig = int2bit(inputSig,bps);
% Count the number of bits in the original data
seqLen = numel(binarySig);
% Convert the encoded data to binary
binaryComp = int2bit(code,bps);
% Count the number of bits in the encoded data
encodedLen = numel(binaryComp);
% Calculate the compression ratio
compressionRatio = seqLen/encodedLen;

Output:
seqLen=300, encodedLen=612, compression ratio=0.4902
Discussion:
The implemented Huffman Encoding and Decoding algorithms successfully processed the input
data using MATLAB. The algorithms were structured to construct Huffman trees based on
character frequencies and generate Huffman codes for data compression.
Experiment No.:09
Experiment name: Implement the Shannon-Fano Encoding and Decoding algorithms using
MATLAB. Also calculate the compression ratio if we use 8 bits to represent a character and four
bits to represent a digit.
Matlab Code:
functionshannon_fano_demo()
input_string = 'HELLO'; % Replace with your string
try
[encoded, encoding_map] = shannon_fano_encode(input_string);
decoded = shannon_fano_decode(encoded, encoding_map);
compression_ratio = calculate_compression_ratio(input_string, encoded,
encoding_map);
disp('Encoded Data:');
disp(encoded);
disp('Decoded Data:');
disp(decoded);
disp('Compression Ratio:');
disp(compression_ratio);
catch ME
disp(['Error: ', ME.message]);
end
end
function [encoded, encoding_map] = shannon_fano_encode(input_string)
symbols = unique(input_string);
freq = histc(input_string, symbols);
prob = freq / sum(freq);
[~, idx] = sort(prob, 'descend');
sorted_symbols = symbols(idx);
sorted_prob = prob(idx);
encoding_map = build_tree(sorted_symbols, sorted_prob, '');
encoded = '';
forch = input_string
encoded = strcat(encoded, encoding_map(string(ch)));
end
end
functionencoding_map = build_tree(symbols, prob, code)
encoding_map = containers.Map('KeyType', 'char', 'ValueType', 'char');
if length(symbols) == 1
encoding_map(string(symbols)) = code;
return;
end
[~, split_index] = min(abs(cumsum(prob) - sum(prob)/2));
group1 = symbols(1:split_index);
group2 = symbols(split_index+1:end);
group1_prob = prob(1:split_index);
group2_prob = prob(split_index+1:end);
map1 = build_tree(group1, group1_prob, strcat(code, '0'));
map2 = build_tree(group2, group2_prob, strcat(code, '1'));
encoding_map = [map1; map2];
end
function decoded = shannon_fano_decode(encoded, encoding_map)
decoded = '';
current_code = '';
for i = 1:length(encoded)
current_code = strcat(current_code, encoded(i));
symbols = keys(encoding_map);
forsym = symbols
ifstrcmp(encoding_map(sym{1}), current_code)
decoded = strcat(decoded, sym{1});
current_code = '';
break;
end
end
end
end
functioncompression_ratio = calculate_compression_ratio(input_string,
encoded, encoding_map)
original_size = length(input_string) * 8;
encoded_size = length(encoded)*4;
compression_ratio =original_size /encoded_size;
end

Output:
Error: Undefined function 'string' for input arguments of type 'char'.
Discussion:
Shannon-Fano Encoding is a data compression technique that constructs variable-length prefix
codes based on the probabilities of symbols in the input data.
Experiment No.:10
Experiment name: Implement the LZW Encoding and Decoding algorithms using MATLAB. Also
calculate the compression ratio if we use 8 bits to represent a character and four bits to
represent a digit.
Matlab Code:
functionlzw_demo()
input_string = 'AABRAACADAABRA'; % Replace with your string
try
encoded = lzw_encode(input_string);
decoded = lzw_decode(encoded);
compression_ratio = calculate_compression_ratio(input_string,
encoded);
disp('Encoded Data:');
disp(encoded);
disp('Decoded Data:');
disp(decoded);
disp('Compression Ratio:');
disp(compression_ratio);
catch ME
disp(['Error: ', ME.message]);
end
end
function encoded = lzw_encode(input_string)
dict = containers.Map('KeyType', 'char', 'ValueType', 'int32');
for i = 1:255
dict(char(i)) = i;
end
encoded = [];
s = '';
dictSize = 256;
for c = input_string
sc = [s, c];
ifisKey(dict, sc)
s = sc;
else
encoded(end+1) = dict(s);
dict(sc) = dictSize;
dictSize = dictSize + 1;
s = c;
end
end
if ~isempty(s)
encoded(end+1) = dict(s);
end
end
function decoded = lzw_decode(encoded)
dict = containers.Map('KeyType', 'int32', 'ValueType', 'char');
for i = 1:255
dict(i) = char(i);
end
decoded = '';
dictSize = 256;
s = char(encoded(1));
decoded = [decoded, s];
for k = encoded(2:end)
ifisKey(dict, k)
entry = dict(k);
elseif k == dictSize
entry = [s, s(1)];
else
error('LZWDecode:InvalidKey', 'Invalid key.');
end
decoded = [decoded, entry];
dict(dictSize) = [s, entry(1)];
dictSize = dictSize + 1;
s = entry;
end
end
functioncompression_ratio = calculate_compression_ratio(input_string,
encoded)
original_size = length(input_string) * 8;
encoded_size = length(encoded) * 4;
compression_ratio = encoded_size / original_size;
end

Output:
Encoded Data:
65 65 66 82 256 67 65 68 256 258 65
Decoded Data:
AABRAACADAABRA
Compressed Ratio:
0.3929

Discussion:
Lempel-Ziv-Welch (LZW) is a lossless data compression algorithm that
works by replacing strings of symbols with codes, creating a
dictionary of variable-length codes as it encounters new patterns in
the input data. The algorithm builds a dictionary dynamically while
encoding the data, allowing it to encode repetitive patterns
efficiently.

You might also like