Cartoonify Image in Just 6 Steps using OpenCV| Computer Vision

#BlogsWithCC

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.

  • Import Libraries:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  • 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 :

image.png

  • 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 size

line_size , blur_value = 5,5
edges = edge_mask(img,line_size , blur_value)
plt.imshow(edges)

output:

image.png

  • Color Quantization:
#function to create color quantization

def 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:

image.png

  • Blurring the image:
blurred = cv2.bilateralFilter(img,d = 7 ,sigmaColor=200,sigmaSpace = 200)
  • Final Output:
def cartoon():
    c = cv2.bitwise_and(blurred,blurred,mask=edges)

    plt.imshow(c)
cartoon()

output: image.png

Result :

  • Original Image:

image.png

  • Cartoonify Image:

image.png