How to cartoonize an image with Python

Stokry - May 22 '21 - - Dev Community

In this tutorial, I will show you how to give a cartoon-effect to an image in Python with OpenCV.

OpenCV is an open-source python library used for computer vision and machine learning. It is mainly aimed at real-time computer vision and image processing. It is used to perform different operations on images which transform them using different techniques.

Many apps can turn your photos into cartoons, but you can do this on your own with few lines of code Python code.

This is our test image:

enter image description here

Let's jump to the code.

import numpy as np
import cv2
Enter fullscreen mode Exit fullscreen mode

after that we we read our image:

filename = 'elon.jpeg'
Enter fullscreen mode Exit fullscreen mode

then we will define our resizeImage :

def resizeImage(image):
    scale_ratio = 0.3
    width = int(image.shape[1] * scale_ratio)
    height = int(image.shape[0] * scale_ratio)
    new_dimensions = (width, height)
    resized = cv2.resize(image, new_dimensions, interpolation = cv2.INTER_AREA)

    return resized
Enter fullscreen mode Exit fullscreen mode

the we need to find contours:

def findCountours(image):

    contoured_image = image
    gray = cv2.cvtColor(contoured_image, cv2.COLOR_BGR2GRAY) 
    edged = cv2.Canny(gray, 30, 100)
    contours, hierarchy = cv2.findContours(edged, 
    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(contoured_image, contours, contourIdx=-1, color=1, thickness=1)
    cv2.imshow('Image after countouring', contoured_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return contoured_image
Enter fullscreen mode Exit fullscreen mode

after that, we do a color quantization:

def ColorQuantization(image, K=4):
    Z = image.reshape((-1, 3)) 
Enter fullscreen mode Exit fullscreen mode

then we convert image to numpy float32:

    Z = np.float32(Z) 
Enter fullscreen mode Exit fullscreen mode

also we need to define critera and apply kmeans:

    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001)
    compactness, label, center = cv2.kmeans(Z, K, None, criteria, 1, cv2.KMEANS_RANDOM_CENTERS)
Enter fullscreen mode Exit fullscreen mode

then we convert to uint8 and apply to original image:

   center = np.uint8(center)
   res = center[label.flatten()]
   res2 = res.reshape((image.shape))

   return res2
Enter fullscreen mode Exit fullscreen mode
if __name__ == "__main__":

    image = cv2.imread(filename)
    resized_image = resizeImage(image)
    coloured = ColorQuantization(resized_image)
    contoured = findCountours(coloured)
    final_image = contoured
    save_q = input("Save the image? [y]/[n] ")

    if save_q == "y":

        cv2.imwrite("cartoonized_"+ filename, final_image)
        print("Image saved!")
Enter fullscreen mode Exit fullscreen mode

This is our final result:
enter image description here

Thank you all.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player