Turn Photos into Cartoons with Python and OpenCV
A short Python script that shows how to cartoonify a photo with OpenCV: median blur, adaptive-threshold edge detection, and a bilateral filter are combined to turn a regular photograph into a cartoon-style image.
Python projects · Images and OpenCV
Start here
Read the requirements and any configuration below, then follow the usage example. Source paths below are relative to the repository root; run commands from the working directory stated in Usage. This example’s source is in Image2Cartoon/Console_Code/. Install any third-party packages in an isolated Python environment.
Overview
This script applies a series of computer vision operations to transform an input image into a cartoon-like rendering. The original and cartoon images are displayed side by side for comparison.
Prerequisites and installation
opencv-python
Install the dependency:
python -m pip install opencv-python
Usage
Open CartoonImage.py and set the input image path:
input_image_path = 'path/to/your/image.jpg'
Then run the script:
python CartoonImage.py
Two windows will open — one showing the original resized image and one showing the cartoon version. Press any key to close them.
The result is only displayed, not saved. To keep it, add cv2.imwrite('cartoon.jpg', cartoon_image) after the conversion.
How It Works
The cartoon effect is produced in five steps:
- Grayscale conversion — the image is converted from BGR to grayscale
- Median blur — a 5×5 median blur reduces noise
- Edge detection — adaptive mean thresholding identifies edges
- Bilateral filter — the color image is smoothed while sharp edges are preserved
- Bitwise AND — the smoothed color image is combined with the edge mask to produce the cartoon effect
The output is resized to 500×500 pixels.
Tips
- Both images are resized to a fixed 500×500, which stretches photos that are not square. Resize by a scale factor instead to keep the aspect ratio.
cv2.adaptiveThreshold(..., 9, 9)controls edge detection (block size and constant);cv2.bilateralFilter(image, 9, 250, 250)controls how flat the colour areas become. Adjust them to make lines thicker or colours smoother.
Architecture
Image2Cartoon/
└── Console_Code/
└── CartoonImage.py # Main script
Related documentation
Documentation links
Read all Python Projects and Code Examples guides online · Project overview · All developer projects