Untitled
import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont def cartoonize_image(image_path, output_path): # Load the image img = cv2.imread(image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) gray = cv2.medianBlur(gray, 5) # Detect edges edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) # Apply bilateral filter for cartoon effect color = cv2.bilateralFilter(img, 9, 300, 300) cartoon = cv2.bitwise_and(color, color, mask=edges) # Save the cartoonized image cartoon_img = Image.fromarray(cartoon) cartoon_img.save(output_path) print(f"Cartoon saved at {output_path}") # Add a speech bubble def add_speech_bubble(image_path, output_path, text): img = Image.open(image_path) draw = ImageDraw.Draw(img) font = ImageFont.load_default() # Draw a simple speech bubble bubble_coords = [(50, img.height - 150), (img.width - 50, img.height - 50)] draw.rectangle(bubble_coords, fill="white") draw.text((70, img.height - 130), text, fill="black", font=font) img.save(output_path) print(f"Speech bubble added and saved at {output_path}") # Example Usage cartoonize_image("input.jpg", "cartoonized.jpg") add_speech_bubble("cartoonized.jpg", "final_cartoon.jpg", "Hello! I'm a cartoon!")
Leave a Comment