CONTENTS
SNO DATE NAME OF THE PAGE SIGN
PROGRAM NO
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 stripbased
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 2014
PROCEDURE:
1. Start the MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. Stop the program.
PROGRAM:
X=input('enter the number of symbol');
N=1:X;
disp('The number of Symbols are N:');
disp(N);
P=input('Enter the Probabilites=');
disp('The probabilites are:');
disp(P);
S=sort(P,'descend');
disp('The Sorted Probabilites are:');
disp(S);
[dict,avglen]=huffmandict(N,S);
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);
codeword=huffmanenco(N,dict);
disp('the codeword are:');
disp(codeword);
decode=huffmandeco(codeword,dict);
disp('decode 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 MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. Stop 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(length(str))];
disp('The encoded string is:');
disp(y);
disp('The compression ratio is:');
ff = size(str,[2]);
gg = size(y, [2]);
cr = ff/gg
b=[];
for i=1:2:length(y)
b=[b y(i)];
end
z=[];
for i=2:2:length(y)
z=[z y(i)];
end
v=[];
for i=1:length(b)
m=b(i);
q=z(i);
for j=1:m
v=[v q];
end
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
% % %Program for LZW Encoding and Decoding of string
close all;
clear all;
clc;
% string to compress
str = 'DAFDADRDAFDA';
str=reshape(str.',1,[] );
display(str);
% pack it
[packed,table, alphabet]=LZW_encoder_string(uint8(str));
fprintf('\n');
fprintf('Output code is:\n'), packed
fprintf('\n');
fprintf('Output Table (New Elements):\n');
% print table
[m n] = size(table);
for i = numel(alphabet)+1:n
fprintf('%d : %s\n', i, char(table{i}));
end
% return;
fprintf('\n');
fprintf('DECODING\n');
% unpack it
[unpacked,utable]=LZW_decoder_string(packed, alphabet);
% transfer it back to char array
fprintf('\nDecoded Stream is:')
unpacked = char(alphabet(unpacked))
% test
isOK = strcmp(str,unpacked)
% show new table elements
fprintf('\n');
fprintf('Output Table (New Elements):\n');
% print table
[m n] = size(utable);
for i = numel(alphabet)+1:n
fprintf('%d : %s\n', i, char(alphabet(utable{i})));
end
OUTPUT
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
DATE : BASED ON THE 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 MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. Stop the program.
PROGRAM:
close all;
clear all;
clc;
str = 'INDIA';
fprintf('The entered string is : %s\n', str);
len = length(str);
fprintf('The length of the string is : %d\n', len);
% % % get unique characters from the string
u = unique(str)
% disp('the unique symbols/characters are');
% disp(u);
fprintf('The unique characters are : %s\n', u);
len_unique = length(u);
fprintf('The length of unique character string is : %d\n', len_unique);
% % % General lookup table
% % % get zeros of length of unique characters
z = zeros(1, len_unique);
p = zeros(1, len_unique);
for i = 1 : len_unique
% % % in 'z' variable we find the occurrence of each characters from 'str'
z(i) = length(findstr(str, u(i)));
% % % in 'p' variable we will get probability of those occurrences
p(i) = z(i) / len;
end
display(z);
display(p);
% % % in 'cpr' variable we will get the cumulative
cpr = cumsum(p);
% % % in 'newcpr' 'cpr' from '0' till last value of 'p'
newcpr = [0 cpr];
display(cpr);
display(newcpr);
% % % make table upto size of 'len_unique'
for i = 1 : len_unique
% % % in first column we are placing 'newcpr' values
table(i, 1) = newcpr(i);
% % % in second column we are placing 'cpr' values
table(i, 2) = cpr(i);
end
% % % Displaying the lookup table
display('The lookup table is : ')
display(table);
% % % Encoder Table
LL = 0;
HL = 1;
for i = 1 : len
for j = 1 : len_unique
% % % if the value from 'str' matches with 'u' then
if str(i) == u(j);
pos = j;
j = j + 1;
% % % displaying position of symbol in unique string
display(pos);
% % % getting the tag value of the matched character
diff_range = HL - LL
HL = LL + (diff_range .* table(pos, 2))
LL = LL + (diff_range .* table(pos, 1))
i = i + 1;
break
end
end
end
% % % displaying tag value
tag = LL;
display(tag);
%%% DECODING %%%
str = '';
% str = [];
for i = 1 : len
for j = 1 : len_unique
% % % If tag value falls between a certain range in lookup table then
if tag (greater than or)= table(j, 1) && tag (less than) table(j, 2)
pos = j;
tag = (tag - table(pos, 1)) / p(j);
decoded_str = u(pos);
str = horzcat(str, decoded_str);
break
end
end
end
% str=horzcat(str);
disp('The decoded string is : ');
display(str)
OUTPUT :
RESULT
Thus the program for compressing the given word using arithmetic coding based on the frequency
of the letters.
EX.NO :5 SHELL SCRIPT WHICH CONVERT ALL IMAGES IN THE DIRECTORY IN
DATE : JPEG
.
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
if ! command -v mogrify&> /dev/null; then
echo "ImageMagick is not installed. Please install it before running this script."
exit 1
fi
# Convert all images 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 MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. Stop the program.
PROGRAM
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 22;
folder = fileparts(which('traffic.avi')); % Determine where demo folder is (works with all versions).
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, FilterIndex] = uigetfile('*.avi');
if ~isequal(baseFileNameNoExt, 0)
movieFullFileName = fullfile(folderName, baseFileNameNoExt);
else
return;
end
else
return;
end
end
try
videoObject = VideoReader(movieFullFileName)
numberOfFrames = videoObject.NumberOfFrames;
vidHeight = videoObject.Height;
vidWidth = videoObject.Width;
numberOfFramesWritten = 0;
figure;
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
promptMessage = sprintf('Do you want to save the individual frames out to individual disk files?');
button = questdlg(promptMessage, 'Save individual frames?', 'Yes', 'No', 'Yes');
if strcmp(button, 'Yes')
writeToDisk = true;
[folder, baseFileNameNoExt, extentions] = fileparts(movieFullFileName);
folder = pwd; % Make it a subfolder of the folder where this m-file lives.
outputFolder = sprintf('%s/Movie Frames from %s', folder, baseFileNameNoExt);
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
else
writeToDisk = false;
end
for frame = 1 : numberOfFrames
thisFrame = read(videoObject, frame);
hImage = subplot(1, 1, 1);
image(thisFrame);
caption = sprintf('Frame %4d of %d.', frame, numberOfFrames);
title(caption, 'FontSize', fontSize);
drawnow; % Force it to refresh the window.
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');
end
if writeToDisk
progressIndication = sprintf('Wrote frame %4d of %d.', frame, numberOfFrames);
else
progressIndication = sprintf('Processed frame %4d of %d.',
frame, numberOfFrames);
end
disp(progressIndication);
numberOfFramesWritten = numberOfFramesWritten + 1;
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"', numberOfFramesWritten, movieFullFileName);
end
disp(finishedMessage); % Write to command window.
uiwait(msgbox(finishedMessage)); % Also pop up a message box.
if ~writeToDisk
return;
end
end
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
DATE : APPROPRIATE IMAGE DIMENSIONS AND FORMAT
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 MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. Stop 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
DATE : CONTENT RETRIEVAL FROM SERVER
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 software.
2. Open new file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. Note the output
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
DATE: BASED METHOD
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 MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. Stop 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
DATE: STREAM
AIM
To write the program for scheduling request for data stream.
SOFTWARE REQUIRED:
MATLAB version 2014
PROCEDURE:
1. Start the MATLAB program.
2. Open new M-file
3. Type the program
4. Save in current directory
5. Compile and Run the program
6. If any error occurs in the program correct the error and run it again
7. For the output see command window\ Figure window
8. 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.