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

MDCS

The document outlines various laboratory exercises conducted by students at Dr. G.U. Pope College of Engineering, focusing on data compression and image processing techniques. Each exercise includes an aim, algorithm, program code, and results indicating successful execution. Topics covered include Huffman coding, Run Length Encoding, Lempel-Ziv algorithm, arithmetic coding, shell scripting for image conversion, and data availability methods.

Uploaded by

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

MDCS

The document outlines various laboratory exercises conducted by students at Dr. G.U. Pope College of Engineering, focusing on data compression and image processing techniques. Each exercise includes an aim, algorithm, program code, and results indicating successful execution. Topics covered include Huffman coding, Run Length Encoding, Lempel-Ziv algorithm, arithmetic coding, shell scripting for image conversion, and data availability methods.

Uploaded by

zann7400
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

CSI THOOTHUKUDI-NAZARETH DIOCESE

DR.G.U.POPE COLLEGE OF ENGINEERING


POPE NAGAR SAWYERPURAM-628 251

Register No :

Certified that this is the bonafide record of work done by


Selvan/Selvi ………………………………………………………………………of ……
Semester ……….. branch for the lab ………………………………………………….

During the year………………………

Staff In-charge H. O.D

Submitted for the university practical Examination held on ……………………….

Internal Examiner External Examiner


INDEX

S.NO DATE TOPIC PAGE MARKS SIGN


NO

Construct Huffman codes for given


symbol probabilities
1. 1

Encode Run Length with fixed-length


code
2. 3

Lempel -ziv algorithm for adaptive


variable-length encoding
3. 5

Compress the given word using


arithmetic coding based on the
4. frequency of the letters 7

Write a shell script,which converts all


images in the current directory in
5. JPEG 9

Write a program to split images from a


video without using any primitives
6. 11

Create a photo album of a trip by


applying appropriate image dimensions
7. and format 13

Write the code for identifying the


popularity of content retrieval from
8. media server 15

Write the code for ensuring data


availability in disks using strip based
9. method 17

Program for scheduling requests for


data streams
10. 19
EX.NO:01
DATE: CONSTRUCT HUFFMAN CODES FOR GIVEN SYMBOL
PROBABILITIES

AIM:

To develop the Huffman code for given symbol probabilities.

ALGORITHM :

STEP 1: Create a priority queue (min-heap).


STEP 2: Extract two minimum nodes.
STEP 3: Create a new internal node.
STEP 4: Insert the new node into the heap.
STEP 5: Repeat steps 2–4 until one node remains.
STEP 6:Generate binary codes.

PROGRAM :

import heapq

class Node:
def _init_(self, symbol, prob):
self.symbol = symbol
self.prob = prob
self.left = None
self.right = None

def _lt_(self, other):


return self.prob < other.prob

def huffman_coding(symbols_with_probs):
heap = [Node(symbol, prob) for symbol, prob in symbols_with_probs]
heapq.heapify(heap)

while len(heap) > 1:


left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = Node(None, left.prob + right.prob)
merged.left = left
merged.right = right
heapq.heappush(heap, merged)

1
root = heap[0]
codes = {}

def generate_codes(node, code=""):


if node is None:
return
if node.symbol is not None:
codes[node.symbol] = code
generate_codes(node.left, code + "0")
generate_codes(node.right, code + "1")

generate_codes(root)
return codes

# User input
n = int(input("Enter the number of symbols: "))
symbols_with_probs = []

for _ in range(n):
symbol = input("Enter symbol: ")
prob = float(input(f"Enter probability for '{symbol}': "))
symbols_with_probs.append((symbol, prob))

# Generate Huffman Codes


codes = huffman_coding(symbols_with_probs)

print("\nHuffman Codes:")
for symbol in codes:
print(f"Symbol: {symbol}, Code: {codes[symbol]}")

OUTPUT :

RESULT :

Thus the Huffman code for given symbol probabilities has been executed
successfully.

2
EX.NO:02
DATE: ENCODE RUN LENGTHS WITH FIXED-LENGTH CODE

AIM:

To develop the Run Lengths with fixed-length code.

ALGORITHM :

STEP 1: Set the maximum run length.


STEP 2: Initialize tracking variables.
STEP 3: Loop through the input string .
STEP 4: Count consecutive duplicates.
STEP 5: Convert count to binary.
STEP 6: Store encoded pair.
STEP 7 : Advance the pointer

PROGRAM :

def rle_fixed_length_encode(data, bit_length):


max_run = (1 << bit_length) - 1
encoded = []

i=0
while i < len(data):
count = 1

while (i + count < len(data) and data[i] == data[i + count] and count < max_run):
count += 1

encoded.append((data[i], format(count, f'0{bit_length}b')))


i += count

return encoded

input_string = input("Enter the string to encode: ")


bit_length = int(input("Enter the fixed bit length for run count: "))
encoded_output = rle_fixed_length_encode(input_string, bit_length)

print("\nEncoded Output:")
for symbol, binary_count in encoded_output:
print(f"({symbol}, {binary_count})")

3
OUTPUT :

RESULT :

Thus the Run lengths with fixed-length code has been executed successfully.

4
EX.NO:03
DATE: LEMPEL -ZIV ALGORITHM FOR ADAPTIVE VARIABLE-LENGTH
ENCODING

AIM:

To develop the Lempel -ziv algorithm for adaptive variable-length encoding.

ALGORITHM :

STEP 1: Initialize data structures.


STEP 2: Iterate through each character.
STEP 3: Build substrings .
STEP 4: Check dictionary for substring.
STEP 5: If new substring.
STEP 6: Update dictionary and reset.
STEP 7 : Handle leftover substring

PROGRAM:

def lz78_compress(data):
dictionary = {}
current = ""
result = []
dict_size = 1

for char in data:


combined = current + char
if combined in dictionary:
current = combined
else:
if current == "":
result.append((0, char))
else:
result.append((dictionary[current], char))
dictionary[combined] = dict_size
dict_size += 1
current = ""

if current:
result.append((dictionary[current], ""))

return result
5
# User input
input_data = input("Enter the string to compress using LZ78: ")

# Compress the input


compressed_output = lz78_compress(input_data)

# Display the output


print("\nLZ78 Compressed Output (index, character):")
for item in compressed_output:
print(item)

OUTPUT :

RESULT :

Thus the Lempel -ziv algorithm for adaptive variable-length encoding has been
executed successfully.

6
EX.NO:04 COMPRESS THE GIVEN WORD USING ARITHMETIC CODING BASED
DATE: ON THE FREQUENCY OF THE LETTERS

AIM:

To compress the given word using arithmetic coding based on the frequency of the
letters.

ALGORITHM :

STEP 1: Calculate character frequencies.


STEP 2: Compute probabilities.
STEP 3: Build cumulative probability intervals.
STEP 4: Initialize encoding range.
STEP 5: Iterate through the input string.
STEP 6: Update range boundaries.
STEP 7 : Generate encoded value.

PROGRAM :

def arithmetic_encode(data):
freq = {ch: data.count(ch) for ch in set(data)}
total = len(data)
probs = {ch: freq[ch]/total for ch in freq}

low = 0.0
high = 1.0
cum = 0.0
bounds = {}

for ch in sorted(probs):
bounds[ch] = (cum, cum + probs[ch])
cum += probs[ch]

for ch in data:
ch_low, ch_high = bounds[ch]
range_ = high - low
high = low + range_ * ch_high
low = low + range_ * ch_low

return (low + high) / 2, bounds

7
s = input("Enter a string: ")
encoded_value, intervals = arithmetic_encode(s)

print(f"\nEncoded Value: {encoded_value}")


print("Intervals:")
for ch, (lo, hi) in intervals.items():
print(f"{ch}: [{lo:.5f}, {hi:.5f})")

OUTPUT :

RESULT :

Thus compressed the given word using arithmetic coding based on the
frequency of the letters has been executed successfully.

8
EX.NO:05 WRITE A SHELL SCRIPT,WHICH CONVERTS ALL
DATE: IMAGES IN THE CURRENT DIRECTORY IN JPEG

AIM:

To write a shell script,which converts all images in the current directory in JPEG.

ALGORITHM :

STEP 1: Check for ImageMagick installation.


STEP 2: Iterate over image filess.
STEP 3: Validate each file.
STEP 4: Extract the base filename.
STEP 5: Convert the image format.
STEP 6: Print conversion status.
STEP 7 : Repeat and finalize.

PROGRAM :

#!/bin/bash

# Check if ImageMagick's convert is installed


if ! command -v convert &> /dev/null; then
echo "Error: ImageMagick (convert) is not installed."
exit 1
fi

# Loop through all image files (common formats)


for img in *.{png,jpg,jpeg,bmp,gif,tiff}; do
# Check if file exists to avoid errors on no matches
[ -f "$img" ] || continue

# Get the filename without extension


filename="${img%.*}"

# Convert to JPEG
convert "$img" "$filename-converted.jpg"

echo "Converted $img to $filename-converted.jpg"


done

echo "All conversions complete."

9
OUTPUT :

RESULT :

Thus the shell script,which converts all images in the current directory in JPEG
has been executed successfully .

10
EX.NO:06 WRITE A PROGRAM TO 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.

ALGORITHM :

STEP 1: Load the video.


STEP 2: Check if video opened successfully.
STEP 3:Initialize frame counter.
STEP 4: Read frames in a loop.
STEP 5: Convert BGR to RGB.
STEP 6:Save each frame as an image.

PROGRAM :

import cv2
from PIL import Image
import os

def split_video_to_images(video_path, output_folder):


video_path = video_path.strip() # remove trailing spaces
cap = cv2.VideoCapture(video_path)

if not cap.isOpened():
print(f"Error: Cannot open video at {video_path}")
return

frame_count = 0

while True:
ret, frame = cap.read()
if not ret:
break
frame_count += 1
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
image.save(os.path.join(output_folder, f"frame_{frame_count:04d}.png"))
print(f"Saved frame {frame_count}")

cap.release()
print(" FRAMES SPLITTED SUCCESSFULLY!")
11
# Fixed path
video_path = r"C:\Users\INDIRA\OneDrive\Pictures\Screenshots\sample_video.mp4"
output_folder = r"C:\Users\INDIRA\OneDrive\Desktop\MDCS"

split_video_to_images(video_path, output_folder)

OUTPUT:

RESULT :

Thus the program to split images from a video without using any primitives
has been executed successfully .

12
EX.NO:07 CREATE A PHOTO ALBUM OF A TRIP BY APPLYING
APPROPRIATE IMAGE DIMENSIONS AND FORMAT
DATE:

AIM:

To create a photo album of a trip by applying appropriate image dimensions and


format.

ALGORITHM :

STEP 1: Read inputs and gather images.


STEP 2: Calculate grid dimensions.
STEP 3:Resize images to thumbnails.
STEP 4: Create a blank album canvas.
STEP 5: Paste thumbnails into the canvas.
STEP 6: Save the final album.

PROGRAM :

from PIL import Image


import os

folder = input("Image folder path: ").strip()


fmt = input("Output format (JPEG, PNG): ").strip().upper()
w, h = int(input("Album width: ")), int(input("Album height: "))
cols = int(input("Images per row: "))
out_path = os.path.join(folder, f"album.{fmt.lower()}")

imgs = [Image.open(os.path.join(folder, f)).copy() for f in os.listdir(folder) if


f.lower().endswith(('jpg','jpeg','png','bmp','webp'))]
if not imgs: exit("No images found.")
rows = (len(imgs) + cols - 1) // cols
tw, th = w // cols, h // rows
thumbs = [img.resize((tw, th)) for img in imgs]
album = Image.new('RGB', (w, h), 'white')

for idx, img in enumerate(thumbs):


x, y = (idx % cols) * tw, (idx // cols) * th
album.paste(img, (x, y))

album.save(out_path, fmt)
print(f"Saved album to {out_path}")
13
OUTPUT :

RESULT :

Thus the create a photo album of a trip by applying appropriate image


dimensions and format has been executed successfully .

14
EX.NO:08 WRITE THE CODE FOR IDENTIFYING THE POPULARITY OF
CONTENT RETRIEVAL FROM MEDIA SERVER
DATE:

AIM:

To write the code for identifying the popularity of content retrieval from media server.

ALGORITHM :

STEP 1: Prompt user input repeatedly.


STEP 2:Store non-empty entries.
STEP 3:Check for empty log.
STEP 4: Count frequency of each content.
STEP 5: Sort by frequency.
STEP 6: Display access statistics
STEP 7:Identify most popular content

PROGRAM :

from collections import Counter

print("Enter content names accessed (type 'done' to finish):")


logs = []

while True:
item = input("Content accessed: ").strip()
if item.lower() == 'done':
break
if item:
logs.append(item)

if not logs:
print("No content was entered.")
exit()

# Count frequency of each content


popularity = Counter(logs)

# Sort by most accessed


sorted_popularity = popularity.most_common()

print("\n Content Popularity:")


for content, count in sorted_popularity:
print(f"{content}: {count} accesses")
15
# Most popular content
most_popular = sorted_popularity[0][0]
print(f"\nMost Popular Content: {most_popular}")

OUTPUT :

RESULT :

Thus the code for identifying the popularity of content retrieval from media
server has been executed successfully .

16
EX.NO:09 WRITE THE CODE FOR ENSURING DATA AVAILABILITY IN DISKS
USING STRIP BASED METHOD
DATE:

AIM:

To write the code for ensuring data availability in disks using strip based method.

ALGORITHM :

STEP 1: Input the number of disks and data.


STEP 2:Create disk folders.
STEP 3:Distribute data in a striped fashion.
STEP 4: Store characters in parts
STEP 5: Initialize a reconstruction string.
STEP 6: Read parts back in striped order.
STEP 7:Compare and display results.

PROGRAM :

import os
n = int(input("Enter number of disks: "))
path = input("Enter disk folder path: ")
data = input("Enter data: ")

disks = [os.path.join(path, f"disk_{i+1}") for i in range(n)]


[os.makedirs(d, exist_ok=True) for d in disks]

# Write striped data


for i, c in enumerate(data):
with open(os.path.join(disks[i % n], f"part_{i//n + 1}.txt"), "a") as f:
f.write(c)
reconstructed = ''
for i in range((len(data) + n - 1) // n):
for d in disks:
p = os.path.join(d, f"part_{i+1}.txt")
if os.path.exists(p):
reconstructed += open(p).read()

print("Original:", data)
print("Reconstructed:", reconstructed)
print("Match!" if data == reconstructed else " Mismatch.")

17
OUTPUT :

RESULT :

Thus write the code for ensuring data availability in disks using strip based
method has been executed successfully .

18
EX.NO:10 PROGRAM FOR SCHEDULING REQUESTS FOR DATA
DATE: STREAMS

AIM:

To develop the Program for scheduling requests for data streams.

ALGORITHM :

STEP 1: Define input data streams.


STEP 2:Convert lists to queues.
STEP 3:Initialize round-robin order.
STEP 4: Start the scheduling loop
STEP 5:Serve one data unit per stream per round.
STEP 6: Reinsert streams with remaining data.
STEP 7:Exit when all data is served.

PROGRAM :

import time
from collections import deque

# Sample data stream requests


data_streams = {
"Stream A": ["A1", "A2", "A3", "A4"],
"Stream B": ["B1", "B2"],
"Stream C": ["C1", "C2", "C3"]
}

# Convert each stream to a queue


queue_map = {name: deque(data) for name, data in data_streams.items()}

# Create a round-robin queue of stream names


round_robin_order = deque(queue_map.keys())

print("Starting round-robin data scheduling...\n")

# Schedule data from each stream


while round_robin_order:
current_stream = round_robin_order.popleft()
stream_queue = queue_map[current_stream]

if stream_queue:
19
data = stream_queue.popleft()
print(f" Served {data} from {current_stream}")
time.sleep(0.5) # Simulate delay
# Put the stream back if it still has data
if stream_queue:
round_robin_order.append(current_stream)

print("\nAll data streams served.")

OUTPUT :

RESULT :

Thus the Program for scheduling requests for data streams has been executed
successfully .

20

You might also like