Edge / app.py
gabrielnkl's picture
Update app.py
5ae09bf verified
import numpy as np
import gradio as gr
# Define some basic convolution kernels
KERNELS = {
"Edge Detection": np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]),
"Sharpen": np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]),
"Blur": np.ones((3, 3)) / 9,
"Emboss": np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]),
}
def apply_convolution(image, kernel_name):
kernel = KERNELS[kernel_name]
# Convert image to grayscale for simplicity
image_gray = np.dot(image[..., :3], [0.2989, 0.5870, 0.1140]) # RGB to grayscale
# Get dimensions
img_h, img_w = image_gray.shape
k_h, k_w = kernel.shape
pad = k_h // 2 # Padding size (assumes square kernel)
# Pad image (zero-padding)
padded_img = np.pad(image_gray, pad, mode='constant', constant_values=0)
# Output image
output = np.zeros((img_h, img_w))
# Perform convolution
for i in range(img_h):
for j in range(img_w):
region = padded_img[i:i+k_h, j:j+k_w] # Extract region
output[i, j] = np.sum(region * kernel) # Apply kernel
# Normalize values to be between 0-255
output = np.clip(output, 0, 255).astype(np.uint8)
return output
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Interactive Convolution with NumPy")
with gr.Row():
image_input = gr.Image(type="numpy", label="Upload Image")
kernel_dropdown = gr.Dropdown(choices=list(KERNELS.keys()), label="Select Kernel")
output_image = gr.Image(type="numpy", label="Processed Image")
process_button = gr.Button("Apply Convolution")
process_button.click(apply_convolution, inputs=[image_input, kernel_dropdown], outputs=output_image)
demo.launch()