encrypt / app.py
lyimo's picture
Update app.py
c046d34 verified
raw
history blame
2.94 kB
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) # Wider range for mean
var = np.random.uniform(0.0005, 0.1) # Higher variance for stronger noise
noisy_image = random_noise(np.array(image), mode='gaussian', mean=mean, var=var, clip=True)
noisy_image = (255 * noisy_image).astype(np.uint8) # Scale back to 0-255
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) # Reset the seed to generate the same noise parameters
image = np.array(noisy_image)
# Convert image to floating point type needed for denoise_nl_means
image_float = img_as_float(image)
sigma_est = np.mean(estimate_sigma(image_float, channel_axis=-1)) # Use channel_axis=-1 for color images
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) # Scale back to 0-255
return Image.fromarray(denoised_image)
# Define Gradio interface with tabs for adding and removing noise
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)
# Launch the app
interface.launch()