Cartoonify Image Using OpenCV and Python

Amrutha Last Updated : 16 Oct, 2024
5 min read

This article was published as a part of the Data Science Blogathon.

Introduction

In this article, we will build one interesting application that will cartoonify the image provided to it. To build this cartoonifyer application we will use python and OpenCV. This is one of the exciting and thrilling applications of Machine Learning. While building this application we will also see how to use libraries like easygui, Tkinter, and all. Here you have to select the image and then the application will convert that image into its cartoon form. Mainly, we build this application using OpenCV and python as the programming languages.

Let’s get started.

Converting An Image To A Cartoon Using OpenCV

OpenCV

OpenCV is an open-source library in python that is used mainly for computer vision tasks in the areas of machine learning and artificial intelligence. Nowadays, openCV is playing a major role in the field of technology. Using OpenCV we can process images and videos for some tasks like object detection, face detection, object tracking, and all.

OpenCV has c, c++, java, and python interfaces and it supports all kinds of systems such as Windows, Linux, Android, Mac OS, IoS, and all…

Requirements

Python: We use python as a programming language for building the application.

cv2: We use cv2 for image processing.

Numpy: Mainly NumPy is used for dealing with arrays. Here the images that we use are stored in the form of arrays. So for that, we use NumPy.

easygui: easygui is a module used for GUI programming in python. In our application easygui is used to open the file box to upload images from the local system.

Imageio: Imageio is a python library that reads and writes the images.

Matplotlib: Matplotlib is used for visualization purposes. Here we plot the images using matplotlib.

OS: Here in our application os is used for dealing with paths like reading images from the path and saving the image to the path.

Tkinter: Tkinter is a standard Graphical User Interface(GUI) package.

Methodology

Methodology

This is the methodology that we are going to follow to build our cartoonify application. First of all using easygui, we will upload the image, and then the image is converted to a greyscale image.

The next two steps are the important steps to converting images into cartoon images. They are smoothening and then retrieving the edges. In this color of the image is smoothened to give the cartoon look and then we retrieve the edges and then highlight them in the final image.

Next, we will prepare a mask Image. In this, we use the bilateral filter with removes the noise and smoothen it to some extent. Now the final step is giving the cartoon effect. To the image which we got in the previous step, we combine our two important steps and finally give a mask-edged image that looks like a cartoon image.

Let’s move on to the coding part.

Implementation

Start by importing all the required libraries such as NumPy, cv2, easygui, imageio, sys,matplotlib, os, and required Tkinter libraries. The importance of these libraries is discussed before.

Python Code:

# import the necessary packages
import cv2
import imutils

#import the required libraries
#import cv2
import easygui 
import imageio 
import sys
import matplotlib.pyplot as plt
import os
import numpy as np


import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image

To upload the image from the local system, define an upload function and use a fileopenbox that opens the box to choose a file, and stores the file path.

def upload():
ImagePath=easygui.fileopenbox()
cartoonify(ImagePath)

Define Cartoonify Function

Now create a function cartoonify which includes all the steps from converting to greyscale to the final cartoon image. The first step is to convert it into a greyscale image and then apply the blur to smoothen the image which is one of the main steps in cartooning the image. For smoothening, the blur effect is given using the median blur() function.  and then retrieving the edges and highlighting for cartoon effect which is another important step of the application and then applying the bilateral filter which is in built that helps to remove the noise present in the image and provides the clean image and then masking the edged image and Finally we plot an image which contains all the six traditions throughout the process.

To plot all the transitions, we form a list of all images. We have saved all the images from first as ReSized1, ReSized2, ReSized3, ReSized4, ReSized5, ReSized6. On a single plot, we will plot all these six. And then finally plt. show() will print all the images.

def cartoonify(ImagePath):
    originalmage = cv2.imread(ImagePath)
    originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB)
# check if the image is chosen
    if originalmage is None:
        print("Can not find any image. Choose appropriate file")
        sys.exit()
    ReSized1 = cv2.resize(originalmage, (960, 540))
    grayScaleImage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2GRAY)
    ReSized2 = cv2.resize(grayScaleImage, (960, 540))
#applying median blur to smoothen an image
    smoothGrayScale = cv2.medianBlur(grayScaleImage, 5)
    ReSized3 = cv2.resize(smoothGrayScale, (960, 540))
#retrieving the edges for cartoon effect
    getEdge = cv2.adaptiveThreshold(smoothGrayScale, 255, 
      cv2.ADAPTIVE_THRESH_MEAN_C, 
      cv2.THRESH_BINARY, 9, 9)
    ReSized4 = cv2.resize(getEdge, (960, 540))
#applying bilateral filter to remove noise 
    #and keep edge sharp as required
    colorImage = cv2.bilateralFilter(originalmage, 9, 300, 300)
    ReSized5 = cv2.resize(colorImage, (960, 540))
    #masking edged image with our "BEAUTIFY" image
    cartoonImage = cv2.bitwise_and(colorImage, colorImage, mask=getEdge)
    ReSized6 = cv2.resize(cartoonImage, (960, 540))

#Plotting the whole transition
    images=[ReSized1, ReSized2, ReSized3, ReSized4, ReSized5, ReSized6]
    fig, axes = plt.subplots(3,2, figsize=(8,8), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1))
    for i, ax in enumerate(axes.flat):
        ax.imshow(images[i], cmap='gray')
    plt.show()

For the main window where we upload the image. When we run the code, a new window will pop up that gives the option to upload the image from the desktop. Here we set the geometry like the size of the window, and the title of the window which we set to ” Cartoonify Your Image !” and then set the labeling style.

top=tk.Tk()
top.geometry('500x500')
top.title('Cartoonify Your Image !')
top.configure(background='#eadbc8')
label=Label(top,background='#eadbc8', font=('ariel',20,'bold'))

Adding Buttons

In the main window make the cartoonify button. This button helps in uploading the image from the desktop. Here we will set what the button should look like. The color of the button, its position on the window, the style of the text on it, and all.

upload=Button(top,text="Cartoonify an Image",command=upload,padx=50,pady=10)
upload.configure(background='blue', foreground='white',font=('ariel',10,'bold'))
upload.pack(side=TOP,pady=200)

This is what the window looks like. When you run the application, this window will pop up with a button naming Catoonify your Image. Using this button you have to upload the image from your desktop.

Adding Buttons

Saving Image

we can also save the image in the local system. But in this application, we just give the cartoon effect to the image. To save the image,

def save(ReSized6, ImagePath):
    #saving an image using imwrite()
    newName="cartoonified_Image"
    path1 = os.path.dirname(ImagePath)
    extension=os.path.splitext(ImagePath)[1]
    path = os.path.join(path1, newName+extension)
    cv2.imwrite(path, cv2.cvtColor(ReSized6, cv2.COLOR_RGB2BGR))
    I = "Image saved by name " + newName +" at "+ path
    tk.messagebox.showinfo(title=None, message=I)

For creating the save button on the main window, use the following code.

save1=Button(top,text="Save cartoon image",command=lambda: save(ImagePath, ReSized6),padx=30,pady=5)
save1.configure(background='#364156', foreground='white',font=('calibri',10,'bold'))
save1.pack(side=TOP,pady=50)

Finally, run it to get the output with all the transitions of the image.

top.mainloop()
Saving Image

Conclusion

Finally, we will get the output image as shown above. It contains all the 6 transitions of the image. And the final image is the cartoon image. I hope you have enjoyed this application. This is the “Cartoon Version” of the image. Now using this application, you can create your cartoon image. This is Thrilling!!!!!!

Overall in this article, we have seen

  • How to build an application to convert an image into its cartoon form.
  • How to use Tkinter to provide GUI.
  • How to use easygui
  • Working on the application

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

This is Amrutha, I am pursuing B.Tech in the Computer science Department. I am interested in developing ML Models with python and Data Analysis. And also I have an interest in Web Development. I hope my articles in Analytics Vidhya help you to learn better. Thank you!!

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details