Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,36 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
import
|
|
|
3 |
from PIL import Image
|
4 |
-
from io import BytesIO
|
5 |
|
6 |
-
def
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
|
16 |
-
|
17 |
|
18 |
-
|
19 |
-
compressed_image = Image.open(BytesIO(response.content))
|
20 |
-
return compressed_image
|
21 |
-
else:
|
22 |
-
return "Error: Unable to fetch compressed image."
|
23 |
|
24 |
# Gradio interface
|
25 |
-
gr_interface = gr.Interface(fn=
|
26 |
-
inputs="
|
27 |
outputs="image",
|
28 |
title="Interactive Image Compression using SVD",
|
29 |
-
description="Upload an image and
|
30 |
|
31 |
gr_interface.launch()
|
|
|
1 |
+
import numpy as np
|
2 |
import gradio as gr
|
3 |
+
from skimage import io, color
|
4 |
+
from numpy.linalg import norm
|
5 |
from PIL import Image
|
|
|
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 process_image(image, k):
|
14 |
+
"""Process the uploaded image, compress it using SVD, and return the result."""
|
15 |
+
# Convert PIL Image to NumPy array
|
16 |
+
image_np = np.array(image)
|
17 |
+
|
18 |
+
# Convert to grayscale
|
19 |
+
gray_image = color.rgb2gray(image_np)
|
20 |
+
|
21 |
+
# Compress the image
|
22 |
+
compressed_image = svd_compress(gray_image, k)
|
23 |
|
24 |
+
# Convert compressed image back to PIL Image for Gradio output
|
25 |
+
compressed_image_pil = Image.fromarray((compressed_image * 255).astype(np.uint8))
|
26 |
|
27 |
+
return compressed_image_pil
|
|
|
|
|
|
|
|
|
28 |
|
29 |
# Gradio interface
|
30 |
+
gr_interface = gr.Interface(fn=process_image,
|
31 |
+
inputs=[gr.inputs.Image(type="pil"), gr.inputs.Slider(1, 100, step=1, default=50)],
|
32 |
outputs="image",
|
33 |
title="Interactive Image Compression using SVD",
|
34 |
+
description="Upload an image and adjust the compression rank to see the compressed version.")
|
35 |
|
36 |
gr_interface.launch()
|