Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
import streamlit as st
|
4 |
+
from skimage import io, color
|
5 |
+
from numpy.linalg import norm
|
6 |
+
|
7 |
+
def svd_compress(image, k):
|
8 |
+
"""Compress the image using SVD by keeping only the top k singular values."""
|
9 |
+
U, S, Vt = np.linalg.svd(image, full_matrices=False)
|
10 |
+
compressed_image = np.dot(U[:, :k], np.dot(np.diag(S[:k]), Vt[:k, :]))
|
11 |
+
return compressed_image
|
12 |
+
|
13 |
+
def compute_norms(original, compressed):
|
14 |
+
"""Compute different norms to compare image quality."""
|
15 |
+
frobenius_norm = norm(original - compressed, 'fro')
|
16 |
+
l2_norm = norm(original - compressed)
|
17 |
+
max_norm = norm(original - compressed, np.inf)
|
18 |
+
return frobenius_norm, l2_norm, max_norm
|
19 |
+
|
20 |
+
def plot_images(original, compressed, k):
|
21 |
+
"""Plot original and compressed images side by side."""
|
22 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
|
23 |
+
axes[0].imshow(original, cmap='gray')
|
24 |
+
axes[0].set_title("Original Image")
|
25 |
+
axes[0].axis('off')
|
26 |
+
|
27 |
+
axes[1].imshow(compressed, cmap='gray')
|
28 |
+
axes[1].set_title(f"Compressed Image (Rank {k})")
|
29 |
+
axes[1].axis('off')
|
30 |
+
|
31 |
+
st.pyplot(fig)
|
32 |
+
|
33 |
+
# Streamlit app
|
34 |
+
st.title("Image Compression using SVD")
|
35 |
+
|
36 |
+
# Upload an image
|
37 |
+
uploaded_file = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
|
38 |
+
if uploaded_file is not None:
|
39 |
+
# Load the image
|
40 |
+
image = io.imread(uploaded_file)
|
41 |
+
gray_image = color.rgb2gray(image)
|
42 |
+
|
43 |
+
# Select compression rank
|
44 |
+
k = st.slider("Select the rank for compression", min_value=1, max_value=min(gray_image.shape), value=50)
|
45 |
+
|
46 |
+
# Compress the image
|
47 |
+
compressed_image = svd_compress(gray_image, k)
|
48 |
+
|
49 |
+
# Compute norms
|
50 |
+
frobenius_norm, l2_norm, max_norm = compute_norms(gray_image, compressed_image)
|
51 |
+
|
52 |
+
# Display norms
|
53 |
+
st.write(f"Frobenius Norm: {frobenius_norm}")
|
54 |
+
st.write(f"L2 Norm: {l2_norm}")
|
55 |
+
st.write(f"Max Norm: {max_norm}")
|
56 |
+
|
57 |
+
# Plot images
|
58 |
+
plot_images(gray_image, compressed_image, k)
|