File size: 2,287 Bytes
2f54e52
 
 
4f355ea
2f54e52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
683892c
2f54e52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
683892c
 
 
 
 
 
8d9d04e
683892c
 
 
 
 
 
 
8d9d04e
2f54e52
683892c
2f54e52
 
 
 
683892c
 
 
 
 
 
 
 
 
 
 
 
2f54e52
8d9d04e
683892c
8d9d04e
f4dcecd
683892c
2f54e52
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import cv2
import numpy as np
import gradio as gr
import tempfile


def process(image, mode, k):
    img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    clahe = cv2.createCLAHE(2.0, (8, 8))
    gray = clahe.apply(gray)

    k = max(3, int(k))
    if k % 2 == 0:
        k += 1

    if mode == "Sketch":
        inv = 255 - gray
        blur = cv2.GaussianBlur(inv, (k, k), 0)
        out = cv2.divide(gray, 255 - blur, scale=256)

    elif mode == "Embroidery":
        blur = cv2.GaussianBlur(gray, (k, k), 0)

        out = cv2.adaptiveThreshold(
            blur,
            255,
            cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
            cv2.THRESH_BINARY,
            11,
            2
        )

    elif mode == "Cartoon":
        color = cv2.bilateralFilter(img, 9, 75, 75)

        gray_c = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        edges = cv2.adaptiveThreshold(
            gray_c,
            255,
            cv2.ADAPTIVE_THRESH_MEAN_C,
            cv2.THRESH_BINARY,
            9,
            2
        )

        edges = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
        out = cv2.bitwise_and(color, edges)

    else:
        out = gray

    # Create temp file for download
    temp_file = tempfile.NamedTemporaryFile(
        suffix=".png",
        delete=False
    )

    cv2.imwrite(temp_file.name, out)

    # Preview image for Gradio
    if len(out.shape) == 2:
        preview = out
    else:
        preview = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)

    return preview, temp_file.name


demo = gr.Interface(
    fn=process,
    inputs=[
        gr.Image(type="pil", label="Upload Image"),
        gr.Dropdown(
            ["Sketch", "Embroidery", "Cartoon"],
            value="Sketch",
            label="Mode"
        ),
        gr.Slider(
            minimum=3,
            maximum=50,
            value=9,
            step=1,
            label="Strength"
        )
    ],
    outputs=[
        gr.Image(label="Preview"),
        gr.File(label="Download PNG")
    ],
    title= "Sketch Converter Studio",
    description="Convert images into sketch, embroidery line art, or cartoon styles."
)

demo.launch()