To Transform images into its Cartoon Using Python


OpenCV is a powerful tool for image processing, and it can be used to perform a variety of tasks such as object detection, face recognition, and image stitching.

One particularly fun application of OpenCV is to convert an image into its cartoon form. This can be done by first converting the image into grayscale, then applying a median filter to remove noise. Next, the edges of the image need to be detected using a Canny edge detector.

Finally, these edges can be thresholded and filled in with color to produce the final cartoon image. While this process may sound complicated, it can be easily accomplished using the OpenCV library. As a result, anyone who wants to have some fun with their images should definitely give this method a try.

Cartooning Image with OpenCV

We aim to transform images into its cartoon. Yes, we will CARTOONIFY the images. Thus, we will build a python application that will transform an image into its cartoon using OpenCV.

What is OpenCV?

OpenCV is a free Python library used for machine learning and computer vision. It is mostly used for computer vision and image processing in real time. It can be used to do different things to images that change them in different ways. In this article, we’ll try to change some images by using OpenCV’s CV2 version.

We will install opencv and numpy :

pip install opencv-python pip install numpy

Now, we will import required libraries that are cv2 and numpy using the code given below:

import cv2 import numpy as np
Code language: JavaScript (javascript)

Full Script to transform images into its Cartoon using the OpenCV library

import cv2 import numpy as np from tkinter.filedialog import * photo = askopenfilename() img = cv2.imread(photo) grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) grey = cv2.medianBlur(grey, 5) edges = cv2.adaptiveThreshold( grey, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) # cartoonize color = cv2.bilateralFilter(img, 9, 250, 250) cartoon = cv2.bitwise_and(color, color, mask=edges) cv2.imshow("Image", img) cv2.imshow("Cartoon", cartoon) # save cv2.imwrite("cartoon.jpg", cartoon) cv2.waitKey(0) cv2.destroyAllWindows()
Code language: Python (python)

Source code here

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts