Skip to content

Instantly share code, notes, and snippets.

@henalbrod
Created March 22, 2023 00:59
Show Gist options
  • Save henalbrod/ee175837c61ae64d72493e2e10981f23 to your computer and use it in GitHub Desktop.
Save henalbrod/ee175837c61ae64d72493e2e10981f23 to your computer and use it in GitHub Desktop.
CartoonifyMe script by ChatGPT4
# pip install opencv-python
# pip install opencv-python-headless
# pip install numpy
# pip install scikit-learn
import base64
import cv2
import numpy as np
from PIL import Image
from io import BytesIO
from sklearn.cluster import KMeans
def cartoonize_image(image, num_colors=16, edge_thickness=3):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray, 7)
edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
if edge_thickness > 1:
kernel = np.ones((edge_thickness, edge_thickness), np.uint8)
edges = cv2.dilate(edges, kernel, iterations=1)
color = cv2.bilateralFilter(image, 9, 250, 250)
color = quantize_colors(color, num_colors)
cartoon = cv2.bitwise_and(color, color, mask=edges)
return cartoon
def quantize_colors(image, num_colors):
data = np.float32(image).reshape((-1, 3))
kmeans = KMeans(n_clusters=num_colors)
labels = kmeans.fit_predict(data)
centers = kmeans.cluster_centers_.astype("uint8")
segmented_image = centers[labels.flatten()].reshape(image.shape)
return segmented_image
def base64_to_image(base64_string):
img_data = base64.b64decode(base64_string)
return np.array(Image.open(BytesIO(img_data)))
def image_to_base64(image):
img_pil = Image.fromarray(image)
buffer = BytesIO()
img_pil.save(buffer, format="PNG")
return base64.b64encode(buffer.getvalue()).decode("utf-8")
# Replace this with your base64 string
base64_string = "your_base_64_image"
image = base64_to_image(base64_string)
cartoon_image = cartoonize_image(image, num_colors=16, edge_thickness=3)
cartoon_base64_string = image_to_base64(cartoon_image)
print(cartoon_base64_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment