0% found this document useful (0 votes)
15 views4 pages

Image Compression with Wavelet Transform

The document outlines a Python program that performs image compression using the 2D Wavelet Transform and visualizes multiresolution image pyramids. It includes functions for loading a grayscale image, decomposing it using wavelets, compressing coefficients, reconstructing the image, and calculating PSNR. The program displays the original image, the reconstructed image after compression, and the various levels of the image pyramid.

Uploaded by

allenkeller35g
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)
15 views4 pages

Image Compression with Wavelet Transform

The document outlines a Python program that performs image compression using the 2D Wavelet Transform and visualizes multiresolution image pyramids. It includes functions for loading a grayscale image, decomposing it using wavelets, compressing coefficients, reconstructing the image, and calculating PSNR. The program displays the original image, the reconstructed image after compression, and the various levels of the image pyramid.

Uploaded by

allenkeller35g
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

10.

Write a program to perform image compression using 2D Wavelet Transform and


visualize multiresolution image pyramids.
import numpy as np
import [Link] as plt
from PIL import Image
import pywt
-----------------------------------------------------------
# Load Lena image in grayscale [0,1]
# -----------------------------------------------------------
def load_grayscale():
img = [Link]("[Link]").convert("L")
arr = [Link](img, dtype=np.float64)
arr /= 255.0
return arr
# -----------------------------------------------------------
# Wavelet decomposition
# -----------------------------------------------------------
def wavelet_decompose(img, wavelet="db2", level=3):
coeffs = pywt.wavedec2(img, wavelet=wavelet, level=level)
coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
return coeffs, coeff_arr, coeff_slices
# -----------------------------------------------------------
# Compression based on largest coefficients
# -----------------------------------------------------------
def compress_coeffs(coeff_arr, keep_fraction=0.1):
flat = coeff_arr.flatten()
N = len(flat)
k = int(N * keep_fraction)

idx = [Link]([Link](flat), -k)[-k:]


mask = np.zeros_like(flat, dtype=bool)
mask[idx] = True

compressed = [Link]()
compressed[~mask] = 0
return [Link](coeff_arr.shape)
# -----------------------------------------------------------
# Reconstruction
# -----------------------------------------------------------
def wavelet_reconstruct(compressed_arr, coeff_slices,
wavelet="db2"):
coeffs_compressed = pywt.array_to_coeffs(compressed_arr,
coeff_slices, output_format="wavedec2")
rec = pywt.waverec2(coeffs_compressed, wavelet)
rec = [Link](rec, 0, 1)
return rec
# -----------------------------------------------------------
# SAFE multiresolution pyramid (correct, non-blank)
# -----------------------------------------------------------
def pyramid_from_coeffs(coeffs, wavelet="db2"):
"""
Fully safe multiresolution pyramid reconstruction.
Ensures LL, H, V, D are forcibly cropped to the same shape.
Eliminates all PyWavelets shape mismatch errors.
"""
levels = len(coeffs) - 1
current = coeffs[0] # cA_N
pyramid = [current]

for L in range(levels, 0, -1):


LL = current
H, V, D = coeffs[L]

# Determine common minimal shape across all subbands


r = min([Link][0], [Link][0], [Link][0], [Link][0])
c = min([Link][1], [Link][1], [Link][1], [Link][1])

# Crop ALL subbands to EXACT same size


LLc = LL[:r, :c]
Hc = H[:r, :c]
Vc = V[:r, :c]
Dc = D[:r, :c]

# Perform inverse DWT for this level


current = pywt.idwt2((LLc, (Hc, Vc, Dc)), wavelet)

current = [Link](current, 0, 1)
[Link](current)

return pyramid

# -----------------------------------------------------------
# PSNR calculation
# -----------------------------------------------------------
def psnr(orig, rec):
mse = [Link]((orig - rec)**2)
if mse == 0:
return float("inf")
return 20 * np.log10(1.0 / [Link](mse))
# -----------------------------------------------------------
# MAIN
# -----------------------------------------------------------
if __name__ == "__main__":
img = load_grayscale()
wavelet = "db2"
levels = 3
keep_fraction = 0.1

# Wavelet decomposition
coeffs, coeff_arr, coeff_slices = wavelet_decompose(img,
wavelet, levels)

# Compression
compressed_arr = compress_coeffs(coeff_arr, keep_fraction)

# Reconstruction
recon = wavelet_reconstruct(compressed_arr, coeff_slices,
wavelet)

# Multiresolution pyramid (NOW FIXED)


pyramid = pyramid_from_coeffs(coeffs, wavelet)

# Metrics
print("PSNR:", psnr(img, recon))
# -------------------------------------------------------
# Display results
# -------------------------------------------------------
[Link](figsize=(6,6))
[Link](img, cmap='gray')
[Link]("Original Lena")
[Link]('off')

[Link](figsize=(6,6))
[Link](recon, cmap='gray')
[Link](f"Reconstructed Image (kept
{int(keep_fraction*100)}% coeffs)")
[Link]('off')

for i, p in enumerate(pyramid):
[Link](figsize=(5,5))
[Link](p, cmap='gray')
[Link](f"Pyramid Level {i}")
[Link]('off')

[Link]()

You might also like