File size: 1,747 Bytes
56e5dd9
5ae09bf
56e5dd9
 
 
 
 
 
 
 
 
 
 
5ae09bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e5dd9
5ae09bf
56e5dd9
5ae09bf
 
56e5dd9
 
 
5ae09bf
56e5dd9
 
5ae09bf
56e5dd9
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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()