File size: 2,256 Bytes
530752c
f38b5cf
f1690e5
f38b5cf
 
 
 
f1690e5
f38b5cf
 
f1690e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f38b5cf
 
 
c2122de
7b47d12
f1690e5
 
 
7b47d12
 
f38b5cf
f1690e5
 
 
 
 
 
 
f38b5cf
 
 
7b47d12
 
f38b5cf
 
f1690e5
 
 
 
 
 
 
 
 
f38b5cf
f1690e5
f38b5cf
 
 
 
f1690e5
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
55
56
57
58
59
60
61
62
63
64
65
66
67
# created with great guidance from https://github.com/NimaBoscarino

import os
import gradio as gr

import kornia as K
from kornia.core import Tensor
import torch


def filters(file, box_blur, blur_pool2d, gaussian_blur2d, max_blur_pool2d, median_blur):
    """
    Apply a series of image filters to the input image.
    """
    # Handle filepath string and file object
    if isinstance(file, str):
        filepath = file
    else:
        filepath = file.name

    # Check if file exists
    if not os.path.exists(filepath):
        raise ValueError(f"File not found: {filepath}")
    # load the image using the rust backend
    img: Tensor = K.io.load_image(filepath, K.io.ImageLoadType.RGB32)
    img = img[None]  # 1xCxHxW / fp32 / [0, 1]

    # apply tensor image enhancement
    x_out: Tensor = K.filters.box_blur(img, (int(box_blur), int(box_blur)))
    x_out = K.filters.blur_pool2d(x_out, int(blur_pool2d))
    x_out = K.filters.gaussian_blur2d(x_out,
                                    (int(gaussian_blur2d), int(gaussian_blur2d)),
                                    (float(gaussian_blur2d), float(gaussian_blur2d)))
    x_out = K.filters.max_blur_pool2d(x_out, int(max_blur_pool2d))
    x_out = K.filters.median_blur(x_out, (int(median_blur), int(median_blur)))

    # Ensure output is in the range [0, 1]
    x_out = torch.clamp(x_out, 0, 1)

    # Convert to numpy array and scale to [0, 255]
    output_image = (x_out.squeeze().permute(1, 2, 0).cpu().numpy() * 255).astype('uint8')

    return output_image


examples = [
    ["examples/ninja_turtles.jpg", 1, 1, 1, 1, 1],
    ["examples/kitty.jpg", 1, 1, 1, 1, 1],
]

demo = gr.Interface(
    fn=filters,
    inputs=[
        gr.Image(type="filepath", label="Input Image"),
        gr.Slider(minimum=1, maximum=10, step=1, value=1, label="Box Blur"),
        gr.Slider(minimum=1, maximum=10, step=1, value=1, label="Blur Pool"),
        gr.Slider(minimum=1, maximum=21, step=2, value=1, label="Gaussian Blur"),
        gr.Slider(minimum=1, maximum=20, step=1, value=1, label="Max Pool"),
        gr.Slider(minimum=1, maximum=5, step=2, value=1, label="Median Blur"),
    ],
    outputs=gr.Image(type="numpy", label="Output Image"),
    examples=examples,
    live=True
)

demo.launch()