File size: 1,430 Bytes
f3a933b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9c593
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
import gradio as gr
import numpy as np
from PIL import Image

def cartoonify(image):
    # Convert the input image (PIL format) to a NumPy array for OpenCV
    img = np.array(image)
    
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    
    # Apply a median blur to reduce noise
    gray_blur = cv2.medianBlur(gray, 7)
    
    # Detect edges using adaptive thresholding (for that cartoon outline effect)
    edges = cv2.adaptiveThreshold(
        gray_blur, 
        255, 
        cv2.ADAPTIVE_THRESH_MEAN_C, 
        cv2.THRESH_BINARY, 
        9, 
        2
    )
    
    # Convert back to RGB so we can apply a bilateral filter
    color = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
    
    # Apply bilateral filter to smooth colors while keeping edges sharp
    color = cv2.bilateralFilter(color, 9, 75, 75)
    
    # Combine edges and smoothed image
    cartoon = cv2.bitwise_and(color, color, mask=edges)
    
    # Convert back to PIL Image for Gradio
    result = Image.fromarray(cartoon)
    return result

# Define the Gradio interface
interface = gr.Interface(
    fn=cartoonify, 
    inputs=gr.Image(type="pil", label="Upload an Image"), 
    outputs=gr.Image(type="pil", label="Cartoonified Image"),
    title="Black and White Cartoon Generator",
    description="Upload an image to convert it into a black-and-white, old-fashioned cartoon style!"
)

# Launch the app
interface.launch()