|
import numpy as np |
|
import gradio as gr |
|
from skimage import io, color |
|
from numpy.linalg import norm |
|
from PIL import Image |
|
|
|
def svd_compress(image, k): |
|
"""Compress the image using SVD by keeping only the top k singular values.""" |
|
U, S, Vt = np.linalg.svd(image, full_matrices=False) |
|
compressed_image = np.dot(U[:, :k], np.dot(np.diag(S[:k]), Vt[:k, :])) |
|
return compressed_image |
|
|
|
def process_image(image, k): |
|
"""Process the uploaded image, compress it using SVD, and return the result.""" |
|
|
|
image_np = np.array(image) |
|
|
|
|
|
gray_image = color.rgb2gray(image_np) |
|
|
|
|
|
compressed_image = svd_compress(gray_image, k) |
|
|
|
|
|
compressed_image_pil = Image.fromarray((compressed_image * 255).astype(np.uint8)) |
|
|
|
return compressed_image_pil |
|
|
|
|
|
gr.Interface(fn=process_image, |
|
inputs=[gr.Image(type="pil", shape=(500, 500)), |
|
gr.Slider(1, 100, step=1, value=50, label="Compression Rank")], |
|
outputs=gr.Image(type="pil"), |
|
title="Interactive Image Compression using SVD", |
|
description="Upload an image (500x500 max) and adjust the compression rank.") |
|
|
|
gr_interface.launch() |