|
import gradio as gr |
|
import numpy as np |
|
from PIL import Image |
|
from skimage.util import random_noise |
|
from skimage.restoration import denoise_nl_means, estimate_sigma |
|
import hashlib |
|
from skimage import img_as_float |
|
|
|
def hash_password(password): |
|
"""Hash the password to generate noise parameters.""" |
|
hash_object = hashlib.sha256(password.encode()) |
|
hex_dig = hash_object.hexdigest() |
|
return int(hex_dig, 16) |
|
|
|
def add_noise(image, password): |
|
"""Add Gaussian noise to the image based on the password.""" |
|
seed = hash_password(password) % (2**32) |
|
np.random.seed(seed) |
|
mean = np.random.uniform(-0.001, 0.1) |
|
var = np.random.uniform(0.0005, 0.1) |
|
noisy_image = random_noise(np.array(image), mode='gaussian', mean=mean, var=var, clip=True) |
|
noisy_image = (255 * noisy_image).astype(np.uint8) |
|
return Image.fromarray(noisy_image) |
|
|
|
def remove_noise(noisy_image, password): |
|
"""Attempt to remove noise from the image using the same password.""" |
|
if isinstance(noisy_image, np.ndarray): |
|
noisy_image = Image.fromarray(noisy_image.astype('uint8')) |
|
|
|
seed = hash_password(password) % (2**32) |
|
np.random.seed(seed) |
|
image = np.array(noisy_image) |
|
|
|
|
|
image_float = img_as_float(image) |
|
|
|
sigma_est = np.mean(estimate_sigma(image_float, channel_axis=-1)) |
|
|
|
denoised_image = denoise_nl_means(image_float, h=1.15 * sigma_est, fast_mode=True, |
|
patch_size=5, patch_distance=6, channel_axis=-1) |
|
|
|
denoised_image = (255 * denoised_image).astype(np.uint8) |
|
return Image.fromarray(denoised_image) |
|
|
|
|
|
with gr.Blocks() as interface: |
|
gr.Markdown("### Image Noise Encryption and Decryption App") |
|
with gr.Tab("Encrypt"): |
|
with gr.Row(): |
|
image_input = gr.Image(label="Original Image") |
|
password_input = gr.Textbox(label="Password for Encryption", type="password") |
|
encrypt_button = gr.Button("Encrypt Image") |
|
image_output = gr.Image(label="Encrypted Image") |
|
encrypt_button.click(add_noise, inputs=[image_input, password_input], outputs=image_output) |
|
|
|
with gr.Tab("Decrypt"): |
|
with gr.Row(): |
|
image_input_decrypt = gr.Image(label="Encrypted Image") |
|
password_input_decrypt = gr.Textbox(label="Password for Decryption", type="password") |
|
decrypt_button = gr.Button("Decrypt Image") |
|
image_output_decrypt = gr.Image(label="Decrypted Image") |
|
decrypt_button.click(remove_noise, inputs=[image_input_decrypt, password_input_decrypt], outputs=image_output_decrypt) |
|
|
|
|
|
interface.launch() |
|
|