Cartoonify An Image With OpenCV in Python
Cartoonify An Image With OpenCV in Python
Cartoonify An Image With OpenCV in Python
OPENCV IN PYTHON
# What is OpenCV?
Python is the pool of libraries. It has numerous libraries for real-world
applications. One such library is OpenCV. OpenCV is a cross-platform
library used for Computer Vision. It includes applications like video and
image capturing and processing. It is majorly used in image
transformation, object detection, face recognition, and many other
stunning applications.
Original Image:
#Steps to develop Image Cartoonifier
easygui: Imported to open a file box. It allows us to select any file from
our system.
Numpy: Images are stored and processed as numbers. These are taken
as arrays. We use NumPy to deal with arrays.
Imageio: Used to read the file which is chosen by file box using a path.
Matplotlib: This library is used for visualization and plotting. Thus, it is
imported to form the plot of images.
OS: For OS interaction. Here, to read the path and save images to that
path.
Code:
import cv2 #for image processing
import easygui #to open the filebox
import numpy as np #to store image
import imageio #to read image stored at particular path
import sys
import matplotlib.pyplot as plt
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
Step 2: Building a File Box to choose a particular file
In this step, we will build the main window of our application, where the
buttons, labels, and images will reside. We also give it a title by title ()
function.
Code:
""" fileopenbox opens the box to choose file
and help us store file path as string """
def upload ():
ImagePath=easygui.fileopenbox ()
cartoonify (ImagePath)
Explanation:
The above code opens the file box, i.e the pop-up box to choose the file from
the device, which opens every time you run the code. fileopenbox () is the
method in easyGUI module which returns the path of the chosen file as a
string.
NOTE: Now, all the operation will be done on the button click, thus all the
below steps are the part of function cartoonify (ImagePath)
def cartoonify (ImagePath):
Code:
#read the image
originalmage = cv2.imread (ImagePath)
originalmage = cv2.cvtColor (originalmage, cv2.COLOR_BGR2RGB)
#print (image) # image is stored in form of numbers
# confirm that image is chosen
if originalmage is None:
print ("Cannot find any image. Choose appropriate file")
sys.exit ()
ReSized1 = cv2.resize (originalmage, (960, 540))
#plt.imshow(ReSized1, cmap='grey')
Explanation:
Imread is a method in cv2 which is used to store images in the form of
numbers. This helps us to perform operations according to our needs. The
image is read as a numpy array, in which cell values depict R, G, and B
values of a pixel.
Explanation:
cvtColor (image, flag) is a method in cv2 which is used to transform an
image into the colour-space mentioned as ‘flag’. Here, our first step is to
convert the image into grayscale. Thus, we use the BGR2GRAY flag. This
returns the image in grayscale. A grayscale image is stored as
grayScaleImage.
After each transformation, we resize the resultant image using the resize ()
method in cv2 and display it using imshow () method. This is done to get
more clear insights into every single transformation step.
The above code will generate the following output:
Explanation:
To smoothen an image, we simply apply a blur effect. This is done using
median Blur () function. Here, the centre pixel is assigned a mean value of
all the pixels which fall under the kernel. In turn , creating a blur effect.
Explanation:
Cartoon effect has two specialties:
1. Highlighted Edges
2. Smooth colors
In this step, we will work on the first specialty. Here, we will try to retrieve
the edges and highlight them. This is attained by the adaptive thresholding
technique. The threshold value is the mean of the neighborhood pixel
values area minus the constant C. C is a constant that is subtracted from the
mean or weighted sum of the neighborhood pixels. Thresh_binary is the
type of threshold applied, and the remaining parameters determine the
block size.
Explanation:
In the above code, we finally work on the second specialty. We prepare a
lightened color image that we mask with edges at the end to produce a
cartoon image. We use bilateralFilter which removes the noise. It can be
taken as smoothening of an image to an extent.
The third parameter is the diameter of the pixel neighborhood, i.e, the
number of pixels around a certain pixel which will determine its value. The
fourth and Fifth parameter defines signmaColor and sigmaSpace. These
parameters are used to give a sigma effect, i.e make an image look vicious
and like water paint, removing the roughness in colors.
Explanation:
So, let’s combine the two specialties. This will be done using MASKING. We
perform bitwise and on two images to mask them. Remember, images are
just numbers?
Explanation:
To plot all the images, we first make a list of all the images. The list here is
named “images” and contains all the resized images. Now, we create axes
like subl=plots in a plot and display one-one images in each block on the
axis using imshow() method.
plt.show() plots the whole plot at once after we plot on each subplot.
Step 10: Functionally of save button
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)
Explanation:
Here, the idea is to save the resultant image. For this, we take the old path,
and just change the tail (name of the old file) to a new name and store the
cartoonified image with a new name in the same folder by appending the
new name to the head part of the file.
For this, we extract the head part of the file path by os.path.dirname()
method. Similarly, os.path.splitext(ImagePath)[1] is used to extract the
extension of the file from the path.
imwrite() method of cv2 is used to save the file at the path mentioned.
cv2.cvtColor(ReSized6, cv2.COLOR_RGB2BGR) is used to assure that no
color get extracted or highlighted while we save our image. Thus, at last, the
user is given confirmation that the image is saved with the name and path
of the file.
Once executed with button, this function will result in below output:
Step 11: Making the main window
top=tk.Tk()
top.geometry('400x400')
top.title('Cartoonify Your Image !')
top.configure(background='white')
label=Label(top,background='#CDCDCD', font=('calibri',20,'bold'))
Summary
Yes, now you have a reason to tease your sibling by saying “You look like a
cartoon”. Just cartoonify his/ her image, and show it!