0% found this document useful (0 votes)
4 views21 pages

MMDC

The document outlines a series of experiments related to data compression and image processing, including Huffman coding, run-length encoding, Lempel-Ziv algorithm, arithmetic coding, and image conversion using shell scripts. Each experiment includes aims, algorithms, programs, and results demonstrating successful implementation. The document serves as a comprehensive guide for performing various data compression techniques and image manipulation tasks using Python and shell scripting.

Uploaded by

thehinata1203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

MMDC

The document outlines a series of experiments related to data compression and image processing, including Huffman coding, run-length encoding, Lempel-Ziv algorithm, arithmetic coding, and image conversion using shell scripts. Each experiment includes aims, algorithms, programs, and results demonstrating successful implementation. The document serves as a comprehensive guide for performing various data compression techniques and image manipulation tasks using Python and shell scripting.

Uploaded by

thehinata1203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PAGE

[Link]. DATE EXPERIMENT TITLE NO. MARKS SIGN.


Construct Huffman codes for given symbol
1. probabilities.

Encode run lengths with fixed-length code


2. using python.
Lempel-Ziv algorithm for adaptive variable-
3. length encoding.

Compress the given word using arithmetic


4. coding based on the frequency of the letters.
Write a shell script, which converts all images
5. in the current directory in JPEG.

Write a program to split images from a video


6. without using any primitives.
Create a photo album of a trip by applying
7. appropriate image dimensions and format.

Identifying the popularity of content retrieval


8. from a media server.

Ensuring data availability in disks using strip-


9. based method.

Program for scheduling requests for data


10. streams.

INDEX

[Link]: 01 CONSTRUCT HUFFMAN CODES FOR GIVEN SYMBOL


Date: PROBABILITIES
Aim:
To implement the Huffman coding algorithm for a given set of symbol
probabilities and construct efficient prefix codes.
Algorithm:
1. Input: A list of symbols with their corresponding probabilities or
frequencies.
2. Create a priority queue (min-heap) containing all symbols.
3. While there is more than one node in the queue:
 Remove two nodes with the lowest probabilities.
 Create a new internal node with probability equal to the sum of two.
 Assign 0 and 1 as edges to the two child nodes.
 Insert the new node back into the queue.
4. Repeat until the queue contains only one node – the root of the Huffman
tree.
5. Traverse the tree to assign binary codes to each symbol.
Program:
import heapq
class Node:
def __init__(self, symbol, prob):
[Link] = symbol
[Link] = prob
[Link] = None
[Link] = None
def __lt__(self, other):
return [Link] < [Link]
def huffman_codes(symbols_probs):
heap = [Node(sym, prob) for sym, prob in symbols_probs.items()]
[Link](heap)
while len(heap) > 1:
left = [Link](heap)
right = [Link](heap)
new_node = Node(None, [Link] + [Link])
new_node.left = left
new_node.right = right
[Link](heap, new_node)
root = heap[0]
codes = {}
def generate_codes(node, code=""):
if node:
if [Link]:
codes[[Link]] = code
generate_codes([Link], code + "0")
generate_codes([Link], code + "1")
generate_codes(root)
return codes
# Example input
symbols = {'A': 0.4, 'B': 0.2, 'C': 0.2, 'D': 0.1, 'E': 0.1}
# Output
codes = huffman_codes(symbols)
print("Symbol\tCode")
for s, c in [Link]():
print(f"{s}\t{c}")

Output:

Symbol Huffman Code


A 0
B 11
C 101
D 100
E 1000

Result:
The Huffman coding algorithm successfully generated variable-length, prefix-firee
codes. Symbols with higher probabilities have shorter codes, minimizing the total
weighted path length.
[Link] :02 ENCODE RUN LENGTHS WITH FIXED-LENGTH CODE
Date: USING PYTHON
Aim:

To implement run-length encoding (RLE) using fixed-length codes to compress a


string by encoding repeated characters.

Algorithm:

1. Input a string of characters.


2. Traverse the string while counting consecutive occurrences of each character.
3. Store each character followed by its run-length count.
4. Use a fixed-length binary representation for counts (e.g., 4-bit for max count
15).
5. Output the encoded string in character + binary count format.

Program:

def fixed_length_binary(n, bits=4):


return format(n, f'0{bits}b')
def run_length_encode_fixed(s):
encoded = ""
i=0
while i < len(s):
count = 1
# Count repeated characters, but not more than 2^bits - 1
while (i + 1 < len(s)) and (s[i] == s[i + 1]) and (count < 2 ** 4 - 1):
count += 1
i += 1
encoded += s[i] + fixed_length_binary(count)
i += 1
return encoded
# Example usage
input_str = "AAABBBBCCDAA"
encoded_str = run_length_encode_fixed(input_str)
print("Input String:", input_str)
print("Encoded Output:", encoded_str)

Output:

Input String: AAABBBBCCDAA


Encoded Output: A0011B0100C0010D0001A0010

Result:

The input string "AAABBBBCCDAA'" is compressed using run-length


encodingwith a 4-bit fixed-length binary code. Each character is followed by a 4-
bit binary number representing the count of its repetitions, reducing redundancy
and enabling efficient transmission/storage.

[Link] :03 LEMPEL-ZIV ALGORITHM FOR ADAPTIVE VARIABLE-


Date: LENGTH ENCODING
Aim:

To implement the Lempel-Ziv-Welch (LZW) compression algorithm, which


performs adaptive variable-length encoding for efficient data compression without
prior knowledge of input data statistics.

Algorithm:

LZW Compression
1. Initialize a dictionary with all possible single-character strings.
2. Set w to the first character of the input.
3. For each character c in the input stream:
If w + c exists in the dictionary:
Setw=wte
Else:
Output the code for w
Add w + ¢ to the dictionary
Set w=c
4. Output the code for w (if any).
5. End.

Program:

def lzw_compress(data):
dict_size = 256
dictionary = {chr(i): i for i in range(dict_size)}
w = ""
result = []
for c in data:
wc = w + c
if wc in dictionary:
w = wc
else:
[Link](dictionary[w])
dictionary[wc] = dict_size
dict_size += 1
w=c
if w:
[Link](dictionary[w])
return result
def lzw_decompress(compressed):
from io import StringIO
dict_size = 256
dictionary = {i: chr(i) for i in range(dict_size)}
w = chr([Link](0))
result = StringIO()
[Link](w)
for k in compressed:
if k in dictionary:
entry = dictionary[k]
elif k == dict_size:
entry = w + w[0]
[Link](entry)
dictionary[dict_size] = w + entry[0]
dict_size += 1
w = entry
return [Link]()

# Example
data = "ABABABA"
compressed = lzw_compress(data)
print("Input:", data)
print("Compressed:", compressed)
print("Decompressed:", lzw_decompress([Link]()))

Output:

Input: ABABABA
Compressed: [65, 66, 256, 258, 65]
Decompressed: ABABABA

Result:

The Lempel–Ziv–Welch (LZW) compression algorithm was successfully


implemented. The program efficiently compressed and decompressed the input
data without any loss of information.
[Link] :04 COMPRESS THE GIVEN WORD USING ARITHMETIC
Date: CODING BASED ON THE FREQUENCY OF THE LETTERS
Aim:

To compress a given word using Arithmetic Coding based on the frequency


of its characters.

Algorithm:

1. Calculate frequency of each character in the input.


2. Calculate probabilities and assign cumulative probability intervals.
3. Initialize interval [low, high) to [0.0, 1.0).
4. For each character in the input:
Update the interval based on the character's cumulative probability range.
5. The final compressed value is any number in the final interval (typically
the lower bound is used).

Program:

def arithmetic_encode(input_string):
# Step 1: Frequency Calculation
freq = {}
for ch in input_string:
freq[ch] = [Link](ch, 0) + 1
total = len(input_string)
# Step 2: Probability and Cumulative Calculation
prob = {}
cumulative = {}
low = 0.0
for ch in sorted(freq):
prob[ch] = freq[ch] / total
cumulative[ch] = low
low += prob[ch]
# Step 3: Arithmetic Coding
low = 0.0
high = 1.0
for ch in input_string:
range_ = high - low
high = low + range_ * (cumulative[ch] + prob[ch])
low = low + range_ * cumulative[ch]
return low, freq, prob, cumulative
# Example usage
input_word = "BILLION"
code, freq, prob, cumulative = arithmetic_encode(input_word)
print("Input:", input_word)
print("Frequencies:", freq)
print("Probabilities:", prob)
print("Cumulative:", cumulative)
print("Arithmetic code (compressed value):", code)

Output:

Input: BILLION
Frequencies: {'B': 1, 'I': 2, 'L': 2, 'N': 1, 'O': 1}
Probabilities: {'B': 0.14285714285714285, 'I': 0.2857142857142857, 'L':
0.2857142857142857, 'N': 0.14285714285714285, 'O': 0.14285714285714285}
Cumulative: {'B': 0.0, 'I': 0.14285714285714285, 'L': 0.42857142857142855, 'N':
0.7142857142857142, 'O': 0.857142857142857}
Arithmetic code (compressed value): 0.41632653061224485

Result:

The given word “BILLION” was successfully compressed using Arithmetic


Coding based on the frequency of its letters. The encoded value obtained (≈
0.4163) uniquely represents the entire sequence within the range [0, 1),
demonstrating efficient variable-length data compression. Thus, the program was
executed and verified successfully.
[Link] :05 WRITE A SHELL SCRIPT, WHICH CONVERTS ALL IMAGES
Date: IN THE CURRENT DIRECTORY IN JPEG
Aim:

To write a shell script that converts all image files in the current directory
to JPEG format.

Algorithm:

1. Start the script.


2. Loop through all image files in the current directory (e.g., PNG, BMP,
GIF).
3. Use the convert command (from ImageMagick) to convert each image to
JPEG format.
4. Save the output with a .jpg extension.
5. End the script.

Program:

#!/bin/bash
# Check if ImageMagick is installed
if ! command -v convert &> /dev/null
then
echo "ImageMagick is not installed. Please install it using 'sudo apt install
imagemagick'"
exit 1
fi

# Loop through image files (add more extensions if needed)


for img in *.png *.bmp *.gif *.tiff; do
if [ -f "$img" ]; then
filename="${img%.*}"
convert "$img" "$[Link]"
echo "$img converted to $[Link]"
fi
done

Output:

If the current directory contains:


[Link]
[Link]
[Link]

After running the script:

[Link] converted to [Link]


[Link] converted to [Link]
[Link] converted to [Link]

Result:

The shell script successfully converted all image files in the current directory to
JPEG format using ImageMagick.

[Link] :06 WRITE A PROGRAM TO SPLIT IMAGES FROM A VIDEO


Date: WITHOUT USING ANY PRIMITIVES
Aim:

To extract frames (images) from a video file manually, avoiding high-level


primitives, and save them as individual image files.

Algorithm:

1. Import the required libraries — cv2 and os.


2. Open the video file using [Link]().
3. Retrieve the total number of frames and frame rate.
4. Loop through each frame manually by setting the frame position using [Link]().
5. Read each frame using [Link]() and save it using [Link]().
6. Release the video capture object after processing all frames.

Program:

import cv2
import os
def split_video_to_images(video_path, output_folder):
# Create output folder if it doesn't exist
if not [Link](output_folder):
[Link](output_folder)
cap = [Link](video_path)

if not [Link]():
print("Error: Could not open video.")
return
total_frames = int([Link](cv2.CAP_PROP_FRAME_COUNT))
print(f"Total frames: {total_frames}")
# Manually extract each frame
for frame_num in range(total_frames):
[Link](cv2.CAP_PROP_POS_FRAMES, frame_num) # Set frame position
success, frame = [Link]() # Read frame
if not success:
print(f"Error reading frame {frame_num}")
continue
filename = [Link](output_folder, f"frame_{frame_num:04d}.jpg")
[Link](filename, frame)
[Link]()
print("Frames successfully extracted.")
# Example usage
video_file = "sample_video.mp4" # Replace with your video file path
output_dir = "extracted_frames"
split_video_to_images(video_file, output_dir)

Output:

After running the program, the following images will be created inside the folder
extracted_frames:

extracted_frames/frame_0000.jpg
extracted_frames/frame_0001.jpg
extracted_frames/frame_0002.jpg
...

Each image corresponds to one frame from the video.

Result:

The program successfully extracts all frames from the given video without using
high-level primitives. It manually processes frames one by one and saves them as
images, providing fine control over frame extraction.
[Link] :07 CREATE A PHOTO ALBUM OF A TRIP BY APPLYING
Date: APPROPRIATE IMAGE DIMENSIONS AND FORMAT
Aim:

To develop a photo album of a trip by resizing and formatting images appropriately


using Python, ensuring uniformity in display and compatibility across digital
platforms.

Algorithm:

1. Import Required Libraries: Use the PIL (Python Imaging Library) module for
image processing.
2. Set Target Dimensions and Format: Define the final image size (e.g., 800×600
pixels) and desired format (e.g., JPEG or PNG).
3. Load Images: Access all the images from the selected folder.
4. Resize and Format Images:
 Open each image.
 Resize it to the target dimensions.
 Convert and save it in the desired format.
5. Create Album Layout: Use a simple HTML file or Python script to organize the
processed images as an album.
6. Display Album: View the generated album in a web browser or any image
viewer.

Program:

from PIL import Image


import os
# Define input and output folders
input_folder = 'trip_images'
output_folder = 'album_images'
# Create output folder if it doesn't exist
[Link](output_folder, exist_ok=True)
# Desired image size and format
target_size = (800, 600)
target_format = 'JPEG'
# Process each image
for filename in [Link](input_folder):
if [Link]().endswith(('.jpg', '.png', '.jpeg')):
img_path = [Link](input_folder, filename)
img = [Link](img_path)
# Resize image
img_resized = [Link](target_size)
# Save resized image in JPEG format
output_path = [Link](output_folder, [Link](filename)[0] + '.jpg')
img_resized.save(output_path, target_format)
print("Images resized and formatted successfully.")

Output:

After running the program:


All input images from the folder trip_images are resized to 800×600 pixels.
All images are converted and saved in JPEG format inside the album_images
folder.

Result:

The photo album was successfully created with resized and uniformly formatted
images. This demonstrates how Python and PIL can be used for simple digital
image processing. All images are consistent in size and format, making the album
visually appealing and easy to share.

[Link] :08 IDENTIFYING THE POPULARITY OF CONTENT


Date: RETRIEVAL FROM A MEDIA SERVER

Aim:

To write a Python program that analyzes content request logs to identify the
popularity of each content item retrieved from a media server.

Algorithm:

1. Start
2. Create a log of content requests (e.g., video names or content IDs).
3. Initialize a dictionary to store the count of requests for each content.
4. Loop through each request in the log:
 If the content exists in the dictionary, increment its count.
 Else, add it to the dictionary with count = 1.
5. Sort the dictionary based on request frequency in descending order.
6. Display the content names along with their request counts.
7. Stop

Program:

def identify_popularity(request_logs):
popularity_dict = {}
# Count the number of times each content is requested
for content in request_logs:
if content in popularity_dict:
popularity_dict[content] += 1
else:
popularity_dict[content] = 1
# Sort contents based on number of requests (popularity)
sorted_popularity = sorted(popularity_dict.items(), key=lambda x: x[1],
reverse=True)
# Display results
print("Content Popularity from Media Server:\n")
print("{:<20} {}".format("Content", "Number of Requests"))
print("-" * 35)

for content, count in sorted_popularity:


print("{:<20} {}".format(content, count))

# Sample log data (you can replace this with actual logs)
media_requests = [
"movie1.mp4", "song1.mp3", "movie1.mp4", "movie2.mp4", "song2.mp3",
"movie1.mp4", "song1.mp3", "movie3.mp4", "movie2.mp4", "song1.mp3"
]

identify_popularity(media_requests)

Output:

Content Popularity from Media Server:

Content Number of Requests

movie1.mp4 3
song1.mp3 3
movie2.mp4 2
song2.mp3 1
movie3.mp4 1

Result:

The Python program successfully identified the popularity of content retrieved


from the media server by counting and ranking the number of requests for each
item.
[Link] :09 ENSURING DATA AVAILABILITY IN DISKS USING STRIP-
Date: BASED METHOD

Aim:

To implement a striping method for data storage across multiple disks, ensuring
data availability and improved performance by distributing data in strips across
disks.
This method is commonly used in RAID (Redundant Array of Independent Disks)
particularly RAID 0 (striping without parity) and RAID 5 (striping with parity).

Algorithm:

1. Divide the data into blocks.


2. Distribute (strip) the blocks across multiple disks in a round-robin fashion.
3. Calculate parity for each set of blocks and store it on one of the disks in a
rotating pattern.
4. In case of a disk failure, reconstruct the missing data using parity and the
remaining blocks.
5. Display the striped data for verification.

Program:

def calculate_parity(blocks):
# XOR all data blocks to get the parity
parity = 0
for block in blocks:
parity ^= block
return parity

def striping_with_parity(data_blocks, num_disks):


stripes = []
for i in range(0, len(data_blocks), num_disks - 1):
stripe_data = data_blocks[i:i + (num_disks - 1)]
# Padding if not enough data blocks
while len(stripe_data) < (num_disks - 1):
stripe_data.append(0)
parity = calculate_parity(stripe_data)
stripe = list(stripe_data)
parity_position = (i // (num_disks - 1)) % num_disks
[Link](parity_position, parity)
[Link](stripe)
return stripes

def display_stripes(stripes):
for i, stripe in enumerate(stripes):
print(f"Stripe {i + 1}: {stripe}")

# Example usage
data_blocks = [10, 20, 30, 40, 50, 60, 70] # Simulated data
num_disks = 4
stripes = striping_with_parity(data_blocks, num_disks)
display_stripes(stripes)

Output:

Stripe 1: [60, 10, 20, 30]


Stripe 2: [40, 70, 50, 60]

Result:

The program successfully demonstrates striping with parity, which improves data
availability and fault tolerance across multiple disks.
This concept forms the basis of RAID 5 used in multimedia and high-performance
storage systems.
[Link] :10 PROGRAM FOR SCHEDULING REQUESTS FOR DATA
Date: STREAMS

Aim:

To write a Python program that schedules and processes multiple data stream
requests efficiently using the First-Come-First-Serve (FCFS) scheduling method.

Algorithm:

1. Start
2. Accept or define multiple data stream requests with their arrival times and
processing times.
3. Sort the requests in the order they arrive (FCFS).
4. Process each request one by one, calculating:
 Start time
 Finish time
 Waiting time
 Turnaround time
5. Display the scheduling order and statistics.
6. End

Program:

def schedule_streams(requests):
# Sort requests based on arrival time
[Link](key=lambda x: x['arrival'])
time = 0
print("{:<10} {:<12} {:<12} {:<12}".format("Stream", "Arrival", "Duration",
"Finish"))
print("-" * 45)

for req in requests:


if time < req['arrival']:
time = req['arrival']
time += req['duration']
print("{:<10} {:<12} {:<12} {:<12}".format(req['name'], req['arrival'],
req['duration'], time))
# Example data stream requests
requests = [
{"name": "Stream1", "arrival": 0, "duration": 4},
{"name": "Stream2", "arrival": 2, "duration": 3},
{"name": "Stream3", "arrival": 5, "duration": 2},
]
schedule_streams(requests)

Output:

Stream Arrival Duration Finish

Stream1 0 4 4
Stream2 2 3 7
Stream3 5 2 9

Result:

The program successfully schedules data stream requests using the FCFS
scheduling algorithm, processing each stream in arrival order.

You might also like