Py.Cafe

jackparmer/

cartoon-me

Webcam Image Cartoonizer

DocsPricing
  • app.py
  • requirements.txt
app.py
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
import streamlit as st
import cv2
import numpy as np
from PIL import Image

def cartoonize_image(image):
    # Convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Apply a median blur
    gray = cv2.medianBlur(gray, 5)
    
    # Detect edges using adaptive thresholding
    edges = cv2.adaptiveThreshold(
        gray,
        255,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        9,
        9
    )
    
    # Apply a bilateral filter to the original image
    color = cv2.bilateralFilter(image, 9, 300, 300)
    
    # Combine the edges with the colored image
    cartoon = cv2.bitwise_and(color, color, mask=edges)
    
    return cartoon

st.title("Webcam Cartoonizer")

# Webcam capture
webcam = st.camera_input("Capture a photo")

if webcam:
    # Convert the captured image to a format OpenCV can work with
    img = Image.open(webcam)
    img = np.array(img)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

    # Cartoonize the image
    cartoon_img = cartoonize_image(img)

    # Convert back to RGB for displaying with Streamlit
    cartoon_img = cv2.cvtColor(cartoon_img, cv2.COLOR_BGR2RGB)

    # Display the original and cartoon images
    st.image(img, caption="Original Image")
    st.image(cartoon_img, caption="Cartoonized Image")