Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import pywt
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
LEVEL_THRESHOLDS = {
|
| 7 |
+
1: 20,
|
| 8 |
+
2: 40,
|
| 9 |
+
3: 60,
|
| 10 |
+
4: 80
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
def threshold_single_level(coeffs_level, threshold):
|
| 14 |
+
LH, HL, HH = coeffs_level
|
| 15 |
+
new_LH = np.where(np.abs(LH) < threshold, 0, LH)
|
| 16 |
+
new_HL = np.where(np.abs(HL) < threshold, 0, HL)
|
| 17 |
+
new_HH = np.where(np.abs(HH) < threshold, 0, HH)
|
| 18 |
+
return (new_LH, new_HL, new_HH)
|
| 19 |
+
|
| 20 |
+
def wavelet_compress(img, level):
|
| 21 |
+
if img.ndim == 3:
|
| 22 |
+
img = img[..., :3]
|
| 23 |
+
img = np.dot(img, [0.299, 0.587, 0.114])
|
| 24 |
+
img = img.astype(np.uint8)
|
| 25 |
+
h, w = img.shape
|
| 26 |
+
threshold = LEVEL_THRESHOLDS[level]
|
| 27 |
+
coeffs = pywt.wavedec2(img, "haar", level=level)
|
| 28 |
+
new_coeffs = [coeffs[0]]
|
| 29 |
+
for level_tuple in coeffs[1:]:
|
| 30 |
+
new_tuple = threshold_single_level(level_tuple, threshold)
|
| 31 |
+
new_coeffs.append(new_tuple)
|
| 32 |
+
recon = pywt.waverec2(new_coeffs, "haar")
|
| 33 |
+
recon = recon[:h, :w]
|
| 34 |
+
recon = np.clip(recon, 0, 255).astype(np.uint8)
|
| 35 |
+
return recon
|
| 36 |
+
|
| 37 |
+
def interface(img, level):
|
| 38 |
+
return wavelet_compress(img, level)
|
| 39 |
+
|
| 40 |
+
demo = gr.Interface(
|
| 41 |
+
fn=interface,
|
| 42 |
+
inputs=[
|
| 43 |
+
gr.Image(type="numpy", label="Upload Image"),
|
| 44 |
+
gr.Slider(1, 4, step=1, value=1, label="Wavelet Level")
|
| 45 |
+
],
|
| 46 |
+
outputs=gr.Image(label="Reconstructed Image"),
|
| 47 |
+
title="Wavelet Image Compression (A-Version)",
|
| 48 |
+
description="Higher wavelet levels use larger thresholds, resulting in stronger distortion."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
demo.launch()
|