Cartoonify Image using OpenCV | Computer Vision project

PyCoder
2 min readNov 2, 2021

--

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products.

This is a small Computer Vision Project to Cartoonify your image using OpenCv.

1. Import Libraries:

import cv2
import numpy as np
import matplotlib.pyplot as plt

2. Create a helper function to import image:

def read_file(filename):
img = cv2.imread(filename)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(img)
return img
filename = 'image.jpg'
img=read_file(filename)

output :

imported image

3 . Create a edge mask:

#helper_function to create edge mask:

def
edge_mask(img,line_size,blur_value):
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
gray_blur = cv2.medianBlur(gray,blur_value)

edges = cv2.adaptiveThreshold(gray_blur,255 , cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,line_size , blur_value)
return edges
#Define the line size and blur sizeline_size , blur_value = 5,5
edges = edge_mask(img,line_size , blur_value)
plt.imshow(edges)

output:

edge mask

4. Color Quantization:

#function to create color quantizationdef color_quantization(img , k):
data = np.float32(img).reshape((-1,3))

criteria = (cv2.TERM_CRITERIA_EPS+ cv2.TERM_CRITERIA_MAX_ITER,20,0.001)

ret ,label , center = cv2.kmeans(data,k,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)

result = center[label.flatten()]
result = result.reshape(img.shape)

return result
img = color_quantization(img,k=10)
plt.imshow(img)

output:

Color_Quantaize image

5. Blurring the image:

blurred = cv2.bilateralFilter(img,d = 7 ,sigmaColor=200,sigmaSpace = 200)

6 . Final Output:

def cartoon():
c = cv2.bitwise_and(blurred,blurred,mask=edges)

plt.imshow(c)
cartoon()

output:

Cartoonify image

Result :

Original Image:

Cartoonify Image:

Note: You can use your own input values for better result.

I hope you like this post. Follow for more such content.

--

--

PyCoder

Python|Data Science|Data Analysis | Content Writer