MULTIMEDIA DATA COMPRESSION AND STORAGE LABORATORY
LIST OF EXPERIMENTS
1. Construct Huffman codes for given symbol probabilities.
2. Encode run lengths with fixed-length code.
3. Lempel-Ziv algorithm for adaptive variable-length encoding
4. Compress the given word using arithmetic coding based on the frequency of the letters.
5. Write a shell script, which converts all images in the current directory in JPEG.
6. Write a program to split images from a video without using any primitives.
7. Create a photo album of a trip by applying appropriate image dimensions and format.
8. Write the code for identifying the popularity of content retrieval from media server.
9. Write the code for ensuring data availability in disks using strip based method.
10. Program for scheduling requests for data streams.
EX.NO :1 CONSTRUCT HUFFMAN CODES FOR GIVEN SYMBOL
DATE : PROBABILITIES
AIM:
To write a program to construct Huffman codes for given symbol probabilities.
SOFTWARE REQUIRED:
Matlab version 2014a
PROCEDURE:
1. Start the program.
2. Input the number of symbols.
3. Input the probabilities of each symbol.
4. Sort the probabilities in descending order.
5. Generate Huffman codes using the sorted probabilities.
6. Display the average code length.
7. Calculate entropy using the formula:
H = ∑ (P × log₂(1/P))
8. Display the entropy.
9. Calculate efficiency:
Efficiency = (Entropy / Average Length) × 100
10. Encode the symbols using the Huffman codes.
11. Display the encoded (compressed) data.
12. Decode the encoded data back to original symbols.
13. Display the decoded data.
14. End the program.
PROGRAM:
X = input('Enter the number of symbols: ');
N = 1:X;
disp('The number of Symbols are:');
disp(N);
P = input('Enter the Probabilities: ');
disp('The probabilities are:');
disp(P);
[dict, avglen] = huffmandict(N, P);
disp('The average length of the code is:');
disp(avglen);
H = 0;
for i = 1:X
H = H + (P(i) * log2(1 / P(i)));
end
disp('Entropy is:');
disp(H);
disp('bits/msg');
E = (H / avglen) * 100;
disp('Efficiency is:');
disp(E);
msg = [1 2 3 1 2];
codeword = huffmanenco(msg, dict);
disp('The codewords are:');
disp(codeword);
decode = huffmandeco(codeword, dict);
disp('Decoded output is:');
disp(decode);
OUTPUT:
RESULT
Thus the program to construct Huffman coding for the given probabilities using MATLAB.
EX.NO 2 ENCODE RUN LENGTHS WITH FIXED-LENGTH CODE DATE:
AIM:
To write a program for encoding the run lengths with fixed length code.
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the program.
2. Take a sequence of numbers as input.
3. Count how many times each number repeats in a row.
4. Store the count and the number together.
5. Repeat this until the end of the sequence.
6. Show the encoded result.
7. Calculate and show the compression ratio.
8. Use the counts and numbers to rebuild the original sequence.
9. Show the decoded (original) sequence.
10. End the program.
PROGRAM:
clc;
clear all; close all;
disp('The input string is:');
str = [5 5 5 5 5 5 4 4 4 3 3 2];
disp(str);
y = [];
c = 1;
for i = 1:length(str)-1
if str(i) == str(i+1)
c = c + 1;
else
y = [y, c, str(i)];
c = 1;
end
end
y = [y, c, str(end)];
disp('The encoded string is:');
disp(y);
originalSize = length(str);
encodedSize = length(y);
cr = originalSize / encodedSize;
disp('The compression ratio is:');
disp(cr);
b = y(1:2:end); % counts
z = y(2:2:end); % values
v = [];
for i = 1:length(b)
m = b(i);
q = z(i);
v = [v, repmat(q, 1, m)];
end
disp('The output string is:');
disp(v);
OUTPUT:
RESULT
Thus the program for encoding and decoding the run lengths was executed successfully using MATLAB.
EX.NO 3 LEMPEL-ZIV ALGORITHM FOR ADAPTIVE VARIABLE-LENGTH ENCODING
DATE:
AIM:
To write a program for Lempel-Ziv algorithm for adaptive variable-length encoding
.
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the MATLAB program.
2. Open new M-file.
3. Type the program.
4. Type the function for LZW_encoder_string and LZW_decoder_string.
5. Save the program and function required in current directory.
6. Compile and Run the program.
7. If any error occurs in the program correct the error and run it again.
8. For the output see command window\ Figure window
9. Stop the program.
PROGRAM
clc; clear; close all;
str = 'ABABABBABBABA';
disp(['str = ', newline, str]);
alphabet = unique(str);
table = cell(1, 256);
for i = 1:length(alphabet)
table{double(alphabet(i))} = alphabet(i);
end
fprintf('\nInitialising Table\n');
for i = 1:length(alphabet)
fprintf('Table Entry %d : %s\n', i, alphabet(i));
end
fprintf('\n%-5s%-5s%-8s%-8s%-8s\n', 'w', 'k', 'output', 'index', 'symbol');
fprintf('%s\n', repmat('-', 1, 35));
w = '';
packed = [];
next_code = 3; % A = 1, B = 2, so start new codes from 3
table_map = containers.Map({'A','B'}, {1,2});
i = 1;
while i <= length(str)
k = str(i);
wk = [w k];
if isKey(table_map, wk)
w = wk;
else
output_code = table_map(w);
packed(end+1) = output_code; %#ok<*SAGROW>
table_map(wk) = next_code;
fprintf('%-5s%-5s%-8d%-8d%-8s\n', w, k, output_code, next_code, wk);
next_code = next_code + 1;
w = k;
end
i = i + 1;
end
if ~isempty(w)
packed(end+1) = table_map(w);
end
fprintf('\nOutput code is:\n');
fprintf('packed =\n');
disp(packed);
fprintf('\nOutput Table (New Elements):\n');
keys = table_map.keys;
for i = 1:length(keys)
code = table_map(keys{i});
if code > 2
fprintf('%d : %s\n', code, keys{i});
end
end
fprintf('\nDECODING\n');
dec_table = containers.Map({1,2}, {'A','B'});
alphabet = ['A','B'];
unpacked = '';
old = packed(1);
s = dec_table(old);
unpacked = [unpacked s];
next_code = 3;
fprintf('\nInitialising Table\n');
fprintf('Table Entry 1 : A\n');
fprintf('Table Entry 2 : B\n');
fprintf('\n%-5s%-12s%-8s%-8s%-8s\n', 'Input', 'code_w (w*k)', 'output', 'index', 'symbol');
fprintf('%s\n', repmat('-', 1, 50));
for i = 2:length(packed)
curr = packed(i);
if dec_table.isKey(curr)
entry = dec_table(curr);
else
entry = [s s(1)];
end
unpacked = [unpacked entry];
new_entry = [s entry(1)];
dec_table(next_code) = new_entry;
fprintf('%-5d%-12s%-8s%-8d%-8s\n', curr, new_entry, entry, next_code, new_entry);
next_code = next_code + 1;
s = entry;
end
fprintf('\nDecoded Stream is:\n');
disp(unpacked);
isOK = strcmp(str, unpacked);
fprintf('isOK = %d\n', isOK);
RESULT
Thus the program for Lempel –Ziv welch for adaptive variable-length encoding was executed successfully
EX.NO 4 COMPRESS THE GIVEN WORD USING ARITHMETIC CODING BASED ON THE
DATE: FREQUENCY OF THE LETTERS
AIM:
To write a program for compressing the given word using arithmetic coding based on the frequency of the
letters.
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the program.
2. Input the string to be compressed.
3. Find unique characters in the string.
4. Calculate frequency of each character.
5. Compute probabilities of each character = frequency / total length.
6. Calculate cumulative probabilities for each symbol.
7. Build the lookup table with cumulative and upper bounds.
8. Initialize:
• Low = 0,
• High = 1
9. For each symbol in the string:
• Find the corresponding range [Low_i, High_i] from the table.
• Update:
• Range = High - Low
• High = Low + Range * High_i
• Low = Low + Range * Low_i
10. After the last symbol, final tag = Low (compressed value).
11. To decode:
• Use the tag value.
• Compare with the lookup table to identify symbol range.
• Repeat until full string is decoded.
12. Display the compressed tag and decoded string.
13. Stop the program.
PROGRAM:
clc;
clear all;
str = 'INDIA';
fprintf('The entered string is : %s\n', str);
fprintf('The length of the string is : %d\n', length(str));
symbols = unique(str);
fprintf('The unique characters are : %s\n', symbols);
fprintf('The length of unique character string is : %d\n\n', length(symbols));
z = histc(str, symbols); % Frequencies
p = z / length(str); % Probabilities
fprintf('Frequencies z = \n');
disp(z);
fprintf('Probabilities p = \n');
disp(p);
cpr = cumsum(p);
fprintf('Cumulative probability cpr = \n');
disp(cpr);
newcpr = [0 cpr];
fprintf('New cumulative probability newcpr = \n');
disp(newcpr);
fprintf('The lookup table is:\n');
for i = 1:length(symbols)
fprintf('%0.4f\t%0.4f\n', newcpr(i), newcpr(i+1));
end
L = 0; H = 1;
tag = 0;
fprintf('\n');
for i = 1:length(str)
index = find(symbols == str(i));
fprintf('pos = %d\n', index);
range = H - L;
H = L + range * newcpr(index + 1);
L = L + range * newcpr(index);
end
tag = L;
fprintf('\nFinal tag value is: %.4f\n', tag);
low = 0; high = 1;
decoded = '';
for i = 1:length(str)
range = high - low;
value = (tag - low) / range;
index = find(newcpr <= value, 1, 'last');
decoded(end+1) = symbols(index);
high = low + range * newcpr(index + 1);
low = low + range * newcpr(index);
end
fprintf('\nThe decoded string is:\n%s\n', decoded);
fprintf('\nSymbol\tProbability\n');
for i = 1:length(symbols)
fprintf('%c\t%.2f\n', symbols(i), p(i));
end
fprintf('\nEncoded tag value = %f\n', tag);
pos = 1;
diff_range = H - L;
HL = H;
LL = L;
fprintf('\npos =\n\t%d\n', pos);
fprintf('\ndiff_range =\n\t%.4f\n', diff_range);
fprintf('\nHL =\n\t%.4f\n', HL);
fprintf('\nLL =\n\t%.4f\n', LL);
fprintf('\ntag =\n\t%.4f\n', tag);
fprintf('\nThe decoded string is :\n\nstr =\n%s\n', decoded);
RESULT
Thus the program for compressing the given word using arithmetic coding based on the frequency of the letter
.
EX.NO .5 SHELL SCRIPT WHICH CONVERT ALL IMAGES IN THE DIRECTORY IN JPEG
DATE:
AIM:
To write a shell script which convert all images in the current directory in JPEG
SOFTWARE REQUIRED:
Ubantu
Image magick
PROCEDURE
1. Create a new folder and save the images in .png format
2. Type the program in notepad and save as .sh file and save it in the folder already created.
3. Press Windows+R command tab will open and type cmd.
4. Command page will open and type wsl –install.
5. Type commands
a) $cd $(wslpath ‘enter the path of the folder’)
b) chmod +x filename.sh
c) sed -i 's/\r//' filename.sh
d) sudo apt update
e) sudo apt install imagemagick
f) ./convert_images.sh
6. All images in the folder will convert to .jpg format
PROGRAM
#!/bin/bash
# Check if ImageMagick is installed
if ! command -v mogrify &> /dev/null; then
echo "ImageMagick is not installed. Please install it before running this script."
exit 1
fi
# Convert all supported image formats to JPEG
for file in *.{png,gif,bmp,tiff,jpg,jpeg}; do
if [ -f "$file" ]; then
echo "Converting $file to JPEG..."
mogrify -format jpg "$file"
fi
done
echo "Conversion complete."
OUTPUT
.
RESULT
Thus the shell script which convert all images in the current directory in JPEG was executed successfully
EX.NO .6 SPLIT IMAGES FROM A VIDEO WITHOUT USING ANY PRIMITIVES
DATE:
AIM:
To write a program to split images from a video without using any primitives.
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the program and initialize the environment (clear variables, close figures, set display properties).
2. Check for the existence of traffic.avi; if not found, prompt for file selection or terminate.
3. Load the selected video and extract frame count, height, and width.
4. Prompt the user to enable or disable saving of frames as image files.
5. If saving is enabled, create a directory for output images.
6. Loop through each frame: read, display, and show frame number.
7. If saving is enabled, add frame number as text and save as .png.
8. Display a message showing the total number of frames processed or saved.
PROGRAM
clc;
close all;
imtool close all;
clear;
workspace;
fontSize = 22;
folder = fileparts(which('traffic.avi'));
movieFullFileName = fullfile(folder, 'traffic.avi');
if ~exist(movieFullFileName, 'file')
strErrorMessage = sprintf('File not found:\n%s\nYou can choose a new one, or cancel',
movieFullFileName);
response = questdlg(strErrorMessage, 'File not found', 'OK - choose a new movie.', 'Cancel', 'OK - choose
a new movie.');
if strcmpi(response, 'OK - choose a new movie.')
[baseFileNameNoExt, folderName, ~] = uigetfile('*.avi');
if ~isequal(baseFileNameNoExt, 0)
movieFullFileName = fullfile(folderName, baseFileNameNoExt);
else
return;
end
else
return;
end
end
try
videoObject = VideoReader(movieFullFileName);
numberOfFrames = videoObject.NumFrames;
vidHeight = videoObject.Height;
vidWidth = videoObject.Width;
catch ME
disp('Error reading video file:');
disp(ME.message);
return;
end
numberOfFramesWritten = 0;
figure;
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
button = questdlg('Do you want to save the individual frames out to individual disk files?', ...
'Save individual frames?', 'Yes', 'No', 'Yes');
if strcmp(button, 'Yes')
writeToDisk = true;
[~, baseFileNameNoExt, ~] = fileparts(movieFullFileName);
folder = pwd;
outputFolder = fullfile(folder, ['Movie Frames from ', baseFileNameNoExt]);
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
else
writeToDisk = false;
end
for frame = 1 : numberOfFrames
thisFrame = read(videoObject, frame);
image(thisFrame);
title(sprintf('Frame %4d of %d.', frame, numberOfFrames), 'FontSize', fontSize);
drawnow;
if writeToDisk
outputBaseFileName = sprintf('Frame %4.4d.png', frame);
outputFullFileName = fullfile(outputFolder, outputBaseFileName);
text(5, 15, outputBaseFileName, 'FontSize', 20);
frameWithText = getframe(gca);
imwrite(frameWithText.cdata, outputFullFileName, 'png');
numberOfFramesWritten = numberOfFramesWritten + 1;
disp(['Wrote frame ', num2str(frame), ' of ', num2str(numberOfFrames)]);
end
end
if writeToDisk
finishedMessage = sprintf('Done! It wrote %d frames to folder\n"%s"', numberOfFramesWritten,
outputFolder);
else
finishedMessage = sprintf('Done! It processed %d frames of\n"%s"', numberOfFrames,
movieFullFileName);
end
disp(finishedMessage);
uiwait(msgbox(finishedMessage));
OUTPUT(VIDEO)
OUTPUT(FRAME EXTRACTION FROM VIDEO)
RESULT
Thus the program for splitting images from video is executed successfully using MATLAB
EX.NO .7 CREATE A PHOTO ALBUM OF A TRIP BY APPLYING APPROPRIATE IMAGE
DIMENSIONS AND FORMAT
DATE:
AIM:
To write a program to create a photo album of a trip by applying appropriate image dimensions and
Format
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the program execution.
2. Read four image files from the specified file paths.
3. Obtain the dimensions of each image using the size function.
4. Resize all images to 500 × 500 pixels using the imresize function.
5. Create a new figure window for display.
6. Display the resized images in a 2×2 grid layout using the subplot and imshow functions.
7. End the program.
PROGRAM
clc
close all
a=imread('D:/img 4.png');
b=imread('D:/img 1.png');
c=imread('D:/img2.png');
d=imread('D:/img3.png');
[m n] = size(a)
[m n] = size(b)
[m n] = size(c)
[m n] = size(d)
i= imresize(a, [500 500]);
j = imresize(b, [500 500]);
k = imresize(c, [500 500]);
l = imresize(d, [500 500]);
figure;
subplot(2,2,1),imshow(i);
subplot(2,2,2),imshow(j);
subplot(2,2,3),imshow(k);
subplot(2,2,4),imshow(l)
OUTPUT
RESULT:
Thus the program to create a photo album of a trip by applying appropriate image dimensions and Format was
executed successfully
EX.NO .8 WRITE THE CODE FOR IDENTIFYING THE POPULARITY OF CONTENT
RETRIEVAL FROM SERVER
DATE:
AIM
To write the code for identifying the popularity of content retrieval from server.
SOFTWARE REQUIRED
IDLE SHELL 3.11.6
PROCEDURE
1. Start the Python program.
2. Create a class MediaServer with an empty dictionary to store content popularity.
3. Define a method to handle content requests:
o If content is new, set count to 1.
o If content exists, increase its count by 1.
4. Define a method to get top popular content by sorting the dictionary in descending order of count.
5. Create an object of MediaServer.
6. Simulate content requests by calling the request method with different video titles.
7. Call the method to get the most popular content (e.g., top 3).
8. Print the most popular content with their request counts.
PROGRAM
class MediaServer:
def init (self):
self.content_popularity = {} # Dictionary to store content popularity
def request_content(self, video_title):
# Simulate a user request for content retrieval
# In a real scenario, you would log this request and update content popularity accordingly
if video_title not in self.content_popularity:
self.content_popularity[video_title] = 1
else:
self.content_popularity[video_title] += 1
def get_popular_content(self, num_items=5):
# Get the most popular content based on request count
sorted_content = sorted(self.content_popularity.items(), key=lambda x: x[1], reverse=True)
return sorted_content[:num_items]
# Create a media server instance
media_server = MediaServer()
# Simulate content requests (videos)
media_server.request_content("Entertainment News: Celebrity Interviews")
media_server.request_content("Coding Challenge: Algorithmic Puzzles")
media_server.request_content("Movie Night: Classic Films Marathon")
media_server.request_content("Coding Challenge: Algorithmic Puzzles")
media_server.request_content("Movie Night: Classic Films Marathon")
media_server.request_content("Web Development Tutorial: Building a Blog")
media_server.request_content("Gaming Session: Online Multiplayer Adventure")
media_server.request_content("Comedy Show: Stand-up Comedy Special")
media_server.request_content("Coding Bootcamp: Python Crash Course")
media_server.request_content("Comedy Show: Stand-up Comedy Special")
media_server.request_content("Coding Challenge: Algorithmic Puzzles")
# Get the top 3 popular videos
popular_content = media_server.get_popular_content(3)
# Print the popular videos
for video_title, popularity in popular_content:
print(f"Video: {video_title}, Popularity: {popularity}")
OUTPUT
RESULT
Thus the coding for identifying the popularity of content retrieval from server was executed
successfully.
EX.NO .9 ENSURING THE DATA AVAILABILITY IN DISK USING STRIP BASED
METHOD
DATE:
AIM
To write the program to ensure the data availability in disk using strip based method
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the program.
2. Ask the user to enter a set of data (array).
3. Ask the user to enter a number to check.
4. Compare the number with the elements of the array.
5. If the number exists in the array:
6. Display "Yes, it's available."
7. Else:
8. Display "No, it's not available."
9. End the program.
PROGRAM
clc
close
all
% Prompt the user to enter the input data as an array
inputData = input('Enter the data as an array (e.g., [1 2 3 4 5]): ');
% Prompt the user to enter the number to check for availability
numberToCheck = input('Enter the number for availability: ');
% Check if the number is available in the input data
if any(inputData == numberToCheck)
disp('Yes, it''s available.');
else
disp('No, it''s not available.');
end
OUTPUT
RESULT
Thus the program to ensure the data availability in disk using strip based method was executed
successfully
EX.NO .10 PROGRAM FOR SCHEDULIND REQUEST FOE DATA STREAM
DATE:
AIM
To write the program for scheduling request for data stream.
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the program.
2. Define a list of data items (e.g., A, B, C, D).
3. Assign a priority value to each data item (higher value = higher priority).
4. Sort the data items based on their priority in descending order.
5. Rearrange the data items according to the sorted priority.
6. Display the scheduled data in the new order.
7. Stop the program.
PROGRAM
% Define the data with their priorities
data1 = 'Data 1';
data2 = 'Data 2';
data3 = 'Data 3';
data4 = 'Data 4';
% Create a cell array to store the data and their priorities
scheduledData = {data1, data2, data3, data4};
priorities = [4, 3, 1, 2]; % Priority values (higher values mean higher priority)
% Sort the data based on priorities [~,
order] = sort(priorities); scheduledData =
scheduledData(order);
% Display the scheduled data in priority order
disp('Scheduled Data in Priority Order:'); for i =
1:numel(scheduledData)
disp([num2str(i), ': ', scheduledData{i}]);
end
OUTPUT:
RESULT
Thus the program for scheduling request for data stream was executed successfully
.