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")