Cartooning an Image using OpenCV & Python
Currently, there are many applications available in the market that can cartoonify an image. But what if we can make our own? So today we’re going to make our own image cartoonizer using OpenCV & Python.
Image cartoon frames don’t contain so many variants of color and those frames also contain dark edges of each object. There’re lots of ways to do that, but we’re going to use color quantization and the adaptive threshold technique. Using this technique we can achieve a very great result.
What is OpenCV?
OpenCV is a python library for image processing. It is an open-source library that can be used in real-time computer vision applications. In this project, we will use opencv to create image cartoons.
What is Color Quantization?
Color quantization or vector quantization is an image processing technique that reduces the number of colors to show the image while preserving the overall appearance quality. It basically uses the K-Means clustering method to perform the task. K-means clustering is a method of finding a group of data. Each group is called a cluster.
What is the Adaptive threshold technique?
Thresholding is an image segmentation technique by setting all pixels whose values are above the threshold as foreground and the rest of the pixels as background. But in adaptive thresholding, these values are calculated for smaller regions.
Cartoonifier Project Prerequisites :
1. Python – 3.x (We used 3.7.10 for this project)
2. OpenCV – 4.5
Please run below command to install opencv to install the package.
pip install opencv-python
3. Numpy – 1.19.5
Download Image Cartooning Python OpenCV Code
Please download the source code of python image cartoonifier: Image Cartooning Python Project Code
Steps to Develop Image Cartooning Project:
- Import necessary packages and read the image
- Perform Color quantization technique.
- Find edges in the original image.
- Combine edges and the quantized result.
Step 1 – Import necessary packages and read the image:
# ProjectGurukul Cartooning an image using OpenCV-Python # Import necessary packages import cv2 import numpy as np # Reading image img = cv2.imread('image.jpg') # Show the output cv2.imshow('input', img) cv2.waitKey(0) cv2.destroyAllWindows()
- We import OpenCV as the name of cv2 in python.
- We’ll need numpy for image operations.
- cv2.imread function reads images.
- cv2.imshow function shows images.
- waitkey(0) means the OpenCV window will open until we close or press any key.
- cv2.destroyAllWindows() destroys all windows after the program is finished.
Step 2 – Perform color quantization technique:
def cartoonize(img, k): # Defining input data for clustering data = np.float32(img).reshape((-1, 3))
- Define a function called cartoonize that will take two arguments, input image and number of cluster(K).
- To perform color quantization the input data should be in a single column.
- Reshape function reshapes the input data or image to a single column.
print("shape of input data: ", img.shape) print('shape of resized data', data.shape)
shape of input data: (500, 500, 3)
shape of resized data (250000, 3)
In the output, we can see that the input data size is 500×500 means 500 rows and 500 columns, and 3 channels. But the resized data contains only a single column containing 250000 pixels and each pixel contains an RGB value.
# Defining criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0) # Applying cv2.kmeans function _, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
- cv2.kmeans() function performs K-means clustering problem.
- The input parameter k is the number of clusters required.
- criteria is the iteration termination criteria. That means when the criteria are satisfied, the algorithm stops iterating.
- The function gives three outputs, but we’re only interested in the center because it gives the center of the clusters.
center = np.uint8(center) print(center) # Reshape the output data to the size of input image result = center[label.flatten()] result = result.reshape(img.shape) cv2.imshow("result", result) cartoonize(img, 8)
- We defined cluster size 8 which means we’ll get the output of 8 centers containing RGB value.
- Reshape function will reshape the center to the shape of the input image. So our new image will contain only 8 unique colors.
Now, we have almost created image cartoon (with opencv) of the input image, and we can also see in the output that we got a list containing 8 nested lists, which means 8 centers each contain RGB value.
Step 3 – Find edges in the original image:
We’ve seen in image cartoons that each object has dark edges and shades. So in this step, we are going to find the edges of the input image.
# Convert the input image to gray scale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Perform adaptive threshold edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 8) cv2.imshow(‘edges’, edges)
- cvtCOLOR function changes the color space of an image. Here we convert the input image to grayscale.
- adaptiveThreshold function performs the adaptive thresholding to find darker edges and returns a mask of the binary image.
Step 4 – Combine edges and the quantized result:
Now we have the result and the edges. So it’s time to combine them and make image cartoon with python
# Smooth the result blurred = cv2.medianBlur(result, 3) # Combine the result and edges to get final cartoon effect cartoon = cv2.bitwise_and(blurred, blurred, mask=edges)
Before combining those two frames at first we’ll smooth out the result to look more clear.
- medianBlur function applies some blur to smooth an image.
- Bitwise_and combine two frames according to the mask.
OpenCV Image Cartooning Output
Now we’ve successfully converted an image to cartoon version using opencv and python.
In this opencv project, we’ve developed an image cartoonizer application using python. From this project, we’ve learned about thresholding and edge finding from an image, K-means clustering algorithm, color quantization technique, and some other basic image processing techniques.