How to cartoonize an image with Python

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 processi…


This content originally appeared on DEV Community and was authored by Stokry

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

after that we we read our image:

filename = 'elon.jpeg'

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

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

after that, we do a color quantization:

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

then we convert image to numpy float32:

    Z = np.float32(Z) 

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)

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
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!")

This is our final result:
enter image description here

Thank you all.


This content originally appeared on DEV Community and was authored by Stokry


Print Share Comment Cite Upload Translate Updates
APA

Stokry | Sciencx (2021-05-22T08:43:08+00:00) How to cartoonize an image with Python. Retrieved from https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/

MLA
" » How to cartoonize an image with Python." Stokry | Sciencx - Saturday May 22, 2021, https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/
HARVARD
Stokry | Sciencx Saturday May 22, 2021 » How to cartoonize an image with Python., viewed ,<https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/>
VANCOUVER
Stokry | Sciencx - » How to cartoonize an image with Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/
CHICAGO
" » How to cartoonize an image with Python." Stokry | Sciencx - Accessed . https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/
IEEE
" » How to cartoonize an image with Python." Stokry | Sciencx [Online]. Available: https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/. [Accessed: ]
rf:citation
» How to cartoonize an image with Python | Stokry | Sciencx | https://www.scien.cx/2021/05/22/how-to-cartoonize-an-image-with-python/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.