prithivMLmods's picture
Update app.py
d41263f verified
import gradio as gr
import cv2
import numpy as np
def compress_image(image, quality):
quality = int(quality) # Ensure quality is an integer
_, encoded_img = cv2.imencode('.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
compressed_img = cv2.imdecode(encoded_img, 1)
return compressed_img
def calculate_psnr(original, compressed):
mse = np.mean((original - compressed) ** 2)
if mse == 0:
return float('inf')
max_pixel_value = 255.0
psnr = 20 * np.log10(max_pixel_value / np.sqrt(mse))
return psnr
def process_image(image, compression_level):
compressed_img = compress_image(image, compression_level)
psnr_value = calculate_psnr(image, compressed_img)
return compressed_img, f"{psnr_value:.2f} dB"
with gr.Blocks(theme="bethecloud/storj_theme") as demo:
with gr.Row():
image_input = gr.Image(label="Upload Image", type="numpy")
compression_slider = gr.Slider(minimum=1, maximum=100, value=50, label="Compression Level (Quality)")
compressed_image_output = gr.Image(type="numpy", label="Compressed Image")
psnr_output = gr.Textbox(label="PSNR Value (dB)")
submit_button = gr.Button("Compress and Calculate PSNR")
submit_button.click(
fn=process_image,
inputs=[image_input, compression_slider],
outputs=[compressed_image_output, psnr_output]
)
gr.Markdown("PSNR = 10 log10(MAX^2/MSE) = 10 log10(MAX/(MSE)^(1/2))^2 = 20 log10(MAX/(MSE)^(1/2)).")
demo.launch()