How to cartoonize an image with Python |

IT-блоги How to cartoonize an image with Python 22 мая 2021 г.

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.drawContours(contoured_image, contours, contourIdx=-1, color=1, thickness=1)
    cv2.imshow('Image after countouring', contoured_image)

    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.


Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.

python tutorial showdev computervision