Open In App

Cartooning an Image using OpenCV – Python

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Instead of sketching images by hand we can use OpenCV to convert a image into cartoon image. In this tutorial you’ll learn how to turn any image into a cartoon. We will apply a series of steps like:

  1. Smoothing the image (like a painting)
  2. Detecting edges (like a sketch)
  3. Combining both to get a cartoon effect

Step 1: Install Required Library

Install OpenCV if it’s not already installed:

pip install opencv-python

Step 2: Read the Image

We start by reading the input image using cv2.imread(). You can download the input image from here.

Python
import cv2
from google.colab.patches import cv2_imshow  

img = cv2.imread("Screenshot.png") 

if img is None:
    print("Error: Could not load image. Check the file path.")
else:
    cv2_imshow(img) 

Output:

Input_image

Original Imgae

Step 3: Convert to Grayscale

Cartoon images depend on edges so we convert the image to grayscale first.

Python
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Step 4: Apply Median Blur

We smooth the grayscale image to remove noise and make edge detection cleaner.

Python
gray_blur = cv2.medianBlur(gray, 5)

Step 5: Detect Edges using Adaptive Thresholding

This will highlight the edges in the image and give it a sketch-like effect.

Python
edges = cv2.adaptiveThreshold(gray_blur, 255,
                              cv2.ADAPTIVE_THRESH_MEAN_C,
                              cv2.THRESH_BINARY,
                              blockSize=9, C=9)

Step 6: Smooth the Original Image Using Bilateral Filter

This filter smooths the image while preserving the edges and give it a cartoon-like appearance.

Python
color = cv2.bilateralFilter(img, d=9, sigmaColor=250, sigmaSpace=250)

Step 7: Combining Edges with Smoothed Image

Now we combine the sketch (edges) and smooth image using bitwise AND to create the final cartoon effect. We display final cartoon image and save it.

Python
cartoon = cv2.bitwise_and(color, color, mask=edges)
cv2_imshow(cartoon)    

cv2.imwrite("cartoon_output.jpg", cartoon)

cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

cartoon_image

Cartoon Output Image

Turning an image into a cartoon using Python and OpenCV is fun and a good way to learn how image processing works. In this project we used a few smart filters to smooth colors, detect edges and combine them to get cartoon effect.

You can download source code from here.



Next Article
Article Tags :

Similar Reads