cartoon_app.py / app.py
Dadada5826's picture
Update app.py
dee8688 verified
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()