import streamlit as st import cv2 import numpy as np import tempfile import os def cartoonize_image(image): # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply a bilateral filter to reduce noise while preserving edges smooth = cv2.bilateralFilter(gray, 9, 300, 300) # Apply an edge-preserving filter to get the edges edges = cv2.adaptiveThreshold(smooth, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 3) # Convert the edges to color edges = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR) # Combine the edges with the original image to create a cartoon effect cartoon = cv2.bitwise_and(image, edges) # Apply the cv2.stylization function for a stylized cartoon effect cartoon = cv2.stylization(image, sigma_s=150, sigma_r=0.25) return cartoon def main(): st.title("Video to Cartoon Converter") # Upload a video file video_file = st.file_uploader("Choose a video file", type=["mp4"]) if video_file is not None: # Save the uploaded video to a temporary file with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video: temp_video.write(video_file.read()) temp_video_path = temp_video.name # Process and display the cartoonized video cartoon_video_path = cartoonize_video(temp_video_path) # Display the cartoonized video with open(cartoon_video_path, "rb") as f: st.video(f.read(), format="video/mp4", start_time=0) # Clean up the temporary files os.remove(temp_video_path) os.remove(cartoon_video_path) def cartoonize_video(video_path): cap = cv2.VideoCapture(video_path) # Get video details fps = int(cap.get(cv2.CAP_PROP_FPS)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Create a temporary file to save the cartoonized video cartoon_video_path = tempfile.mktemp(suffix=".mp4") cartoon_video = cv2.VideoWriter(cartoon_video_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height)) while True: ret, frame = cap.read() if not ret: break # Cartoonize the frame cartoon_frame = cartoonize_image(frame) # Write the cartoonized frame to the VideoWriter cartoon_video.write(cartoon_frame) cap.release() cartoon_video.release() return cartoon_video_path if __name__ == "__main__": main()