You are on page 1of 48

A

MAJOR PROJECT REPORT


ON
CARTOONIFY AN IMAGE WITH OPENCV IN PYTHON
Submitted in partial fulfilment of requirement for the award of degree
of
MASTER OF COMPUTER APLICATION(MCA)

M.K.M College of Management and Information Technology for


Girls Hodal, Faridabad (Haryana)
APPROVED BY AICTE AND AFFILATED TO MDU ROTHAK

Session 2023-24

Under the Guidance of: Submitted by:


Ms. Anamika Aggarwal NIDHI
Registration no:1811420473
MCA final year
Certificate

This is to certify that Nidhi, MCA 4th Sem has carried out the project word title
“Cartoonify An Image With OpenCV In Python” under the supervision of
Ms. Anamika Aggarwal
This project work is originally work carried out by the student and has not been
submitted to any other college/institute to the best of knowledge

Supervisor
Ms. Anamika Aggarwal
ACKNOWLEDGEMENT

I take this opportunity to thank our teachers and friends who helped me
throughout the project. Firstly, I would like to thank my guide Ms. Anamika
Aggarwal, Assistant Professor, Department of MCA, MKM College of
Management and IT for Girls, for guiding my Project .We are very deeply
thankful to her support for the valuable advice and time during development of
project.
We extremely grateful to our department staff members, Finally, we express our
heartful thanks to all of our friends who helped us in successful completion of
this project.

NIDHI
MCA 4th SEM
DECLARATION

I “NIDHI” here by declare that the work presented in the College Campus
Project titled “Cartoonify An Image With OpenCV In Python” and submitted
to department of Master of Computer Application “MKM College of
Management and Information Technology for Girls ”, Approved by AICTE and
Affiliated to MDU Rohtak for the partial fulfilment of Master Of Computer
Application in an authentic record of my work carried out during the semester
under the supervision of Ms. Anamika Aggarwal Assistant professor, MKM
College of management and IT for Girls.
Further, I also undertake that the matter embodied in this Project Report is my
own work and has not been submitted by me or by any other candidate for the
award of any other degree anywhere else.
Countersigned by Internal Supervisor

Name: Ms. Anamika Aggarwal


Designation: Assistant Professor
ABSTRACT
This project represents different techniques of converting image to cartoon. using any one of
below mentioned techniques it is possible to convert all type of captured images to cartoon
such as images of person, mountains, trees, flora, and fauna etc. there are several other
techniques for image to cartoon conversion such as using photoshop, adobe illustrator,
windows MAC, Paint .net and much more.
The idea of the Project is based on designated snapshots and videos which are converted to an
art from such, as painting. With the help of GAN, it is possible to convert video as well to its
CARTOONIFY version and development of the project shows that our proposed idea
provides high quality cartooned images and video.
Cartton -style pictures can be seen almost everywhere in our daily life. Numerous
applications try to deal with Cartoon Pictures, a Dataset of Cartoon Pictures will be Valuables
For these applications.
There are several techniques for image to cartoon conversion such as using photoshop, adobe
illustrator, windows MAC, paint.net and much more. Python is the pool of libraries. Rather
than using web applications such as photoshop, use libraries in python which gives us better
output. 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. We will use some of the standard libraries such as NumPy, matplotlib. You can
use a photo of your own in a profile image, create an amusing avatar or turn your photo into a
cartoon. Using Machine learning, we can design such projects. Thus, we will build a python
application that will transform an image into its cartoon using OpenCV.
Python programming is very much important in machine learning projects. The outcomes of
the study are “how to CARTOONIFY an image using OpenCV in python”.
Contents
Chapter 1
Python
1.1 Introduction ------------------------------------------------------------------------------07 - 10
1.2 History ----------------------------------------------------------------------------------- 10 – 11

Chapter 2
Convert the image into Cartoon and Pencil Sketch Image using OpenCV in Python
2.1 Introduction ------------------------------------------------------------------------------ 11 – 13
2.2 What are going to build----------------------------------------------------------------- 13 - 14

Chapter 3
Methodology
3.1 CARTOONIFY the image ---------------------------------------------------------------14-16
3.2 Designing ----------------------------------------------------------------------------------16-19
3.3 Testing--------------------------------------------------------------------------------------19-23

Chapter 4
4.1 Converting Image into a cartoon image------------------------------------------------ 23- 25
4.2 Image processing -------------------------------------------------------------------------25 – 36

Chapter 5
5.1 Converting Image into a Pencil Sketch ---------------------------------------------- 36 – 37
5.2 Image processing ------------------------------------------------------------------------ 37 -45

Chapter 6
6.1 Future Scope ---------------------------------------------------------------------------- 45 – 46
6.2 Conclusion ------------------------------------------------------------------------------ 46 – 47
6.3 references ------------------------------------------------------------------------------- 47- 48
Figures Table
Figure 1 ---------------------------------------------------------------------------------------------15
Figure 2--------------------------------------------------------------------------------------------- 18
Figure 3--------------------------------------------------------------------------------------------- 19
Figure 4--------------------------------------------------------------------------------------------- 19
Figure 5--------------------------------------------------------------------------------------------- 20
Figure 6--------------------------------------------------------------------------------------------- 22
Figure 7--------------------------------------------------------------------------------------------- 23
Figure 8 -------------------------------------------------------------------------------------------- 27
Figure 9-------------------------------------------------------------------------------------------- 29
Figure 10------------------------------------------------------------------------------------------- 30
Figure 11------------------------------------------------------------------------------------------- 31
Figure 12------------------------------------------------------------------------------------------- 32
Figure 13------------------------------------------------------------------------------------------- 34
Figure 14------------------------------------------------------------------------------------------- 36
Figure 15------------------------------------------------------------------------------------------- 39
Figure 16------------------------------------------------------------------------------------------- 40
Figure 17------------------------------------------------------------------------------------------- 41
Figure 18------------------------------------------------------------------------------------------- 42
Figure 19------------------------------------------------------------------------------------------- 42
Figure 20------------------------------------------------------------------------------------------- 43
Figure 21------------------------------------------------------------------------------------------- 45
CHAPTER – 1
PYTHON
1.1 Introduction
Python is a programming language. It’s used for many different applications. It’s used in
some high schools and colleges as an introductory programming language because Python is
easy to learn, but it’s also used by professional software developers at places such as Google,
NASA, and Lucasfilm Ltd. By the way, the language is named after the BBC show “Monty
Python’s Flying Circus” and has nothing to do with reptiles. Making references to Monty
Python skits in documentation is not only allowed, it is encouraged!
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Python Syntax compared to other programming languages
• Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose

Output:

Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar for Python or
run the following on the Command Line (cmd.exe):

To check if you have python installed on a Linux or Mac, then on linux open the command
line or on Mac open the Terminal and type:

If you find that you do not have Python installed on your computer, then you can download it
for free from the following website: https://www.python.org/

Features:
1.It is compact and very easy to use OOP language.
2. It is more capable to express the purpose of the code.
3.It is interpreted line by line. No need to download additional libraries.
4. It can run on variety of platform. Thus, it is a portable language.
5.It is free and open source.
6. Variety of applications Python allows you to split your program into modules that can be reused in
other Python programs.
7.Programs written in Python are typically much shorter than equivalent C, C++, or Java programs,
for several reasons:
• the high-level data types allow you to express complex operations in a single statement;
• statement grouping is done by indentation instead of beginning and ending brackets;
• no variable or argument declarations are necessary.

Disadvantages:
• Python is not the fastest language.
• Its library is not still competent with other language like C, Perl and JAVA.
• Python interpreter is not very strong on catching ‘Type-Mismatch’.
• It is not easy convertible to other programming language.
Indentation:
Python uses indentation to define scope, such as the scope of loops, functions, and classes. Other
programming languages often use curly brackets for this purpose.

Coding:
if 5 > 2:
print ("Five is greater than two!")

Output:
[Running] python -u "c:\Users\heman\OneDrive\Documents\Desktop\Project python\Indensation.py"
Five is greater than two!

Error:
Python will give you an error if you skip the indentation:
Coding:
if 5 > 2:
print ("Five is greater than two!")
Output:
[Running] python -u "c:\Users\heman\OneDrive\Documents\Desktop\Project python\Indensation.py"
File "c:\Users\heman\OneDrive\Documents\Desktop\Project python\Indensation.py", line 5
print ("Five is greater than two!")
^

Comments:
Python uses the hash symbol (#) to start a single-line comment. Multi-line comments can be created
using triple quotation marks (""" or ''').
1.2. HISTORY

History Python was conceived in the late 1980s, and its implementation was
started in December 1989 by Guido van Rossum at CWI in the Netherlands as a
successor to the ABC language (itself inspired by SETL) capable of exception
handling and interfacing with the Amoeba operating system. Van Rossum is
Python's principal author, and his continuing central role in deciding the
direction of Python is reflected in the title given to him by the Python
community, benevolent dictator for life (BDFL).

“Python is an experiment in how much freedom programmers need. Too much


freedom and nobody can read another's code; too little and expressiveness is
endangered.”

_ Guido van Ross


Chapter- 2
Covert the Image into Cartoon and Pencil sketch image using
OpenCV in python

1.1 Introduction
Cartoon is a popular art from that has been widely applied in a device scene. Cartooning of
image is a motion picture that relies on a sequence of illustration for its animation. Modern
carton animation workflows allow artist to use a variety of sources scene content. Some
famous products have been created by turning real-world photography into usable carton
scene materials, where the process is called image cartoonization1. GAN network is a novel
based approach to photo OpenCV provides a common infrastructure for computer vision
application the work done till date is explained by literature survey, A couple of year back,
there had been tremendous growth in the research of GAN (Generative Adversarial Network).
Gan Was put forward in the year 2014 where it was introduced in various applications such as
deep learning, natural language processing (NLP). Akanksha Apte, Ashwathy Unnikrishnan,
Navjeevan Bomble, Prof. Sachin Gavhane proposed different method of image synthesis such
as direct method
Cartoon image commonly used in various kinds of applications. As we know cartoons are
artistically made it requires elegant and fine human artistic skill. while portraying Cartoons in
humongous numbers for any animation movies it gets time- consuming for the artist as they
need to define the sketch of the cartoon properly to get a good result. we all know that
animation plays an important role in the world of cinema, so to overcome the problem faced
by the artiest we have created a program with the help of GAN which not only converts
images but also converts video into an animation.
Cartoons have always been very popular among children even adults for many years. Cartoon
-style picture can be seen almost everywhere in our daily life. more and mor application try to
deal with this Style of picture, so building a cartoon -style dataset will be valuable. such a
data set can serve as training or evaluation benchmark for application, like semantic
classification system, skeleton extraction methods, cartoon picture m1odeling system,etc. It
will be beneficial to various cartoon image application. Like Cartoon face maker, art-teaching
apps, etc. As a result, we construct a basic cartoon dataset and build an efficient semantic
classification neural network for it
Constructing a Cartoon image dataset will be faced with challenges. cartoon image is not the
snapshot of real -world objects so it is difficult to make use of existing resources to generate
cartoon pictures. Although a number of Cartoon image from the internet are available, most
of them have similar cartoon-Style one big Colour Block connect with another. you can use
photo of your own in a profile image, create an amusing avatar or turn your photo into a
cartoon. with a pool of web application available online, an image conversion to cartoon
takes few clicks
we will build one interesting application that will CARTOONIFY the image provided to it. To
build this cartoonifye1r 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 easy Gui, 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.

An introduction to image synthesises with GAN:


A Couple of Years back, there had been tremendous growth in the research of GAN
(Generative Adversarial Network). GAN was put Forword in the year 2014 where it was
introduction in various application such as deep learning, natural language processing (NLP).
From this paper, we explored the different method of image synthesis such as direct method ,
hierarchal method and iterative method.

Auto-painter cartoon image generation from sketch using by using Cgan:


The authors studied various problems faced by sketch artist while sketching various black
and white cartoon drawings, for consideration colouring of various sketch, mixing of a
different were faced by the arts to get a unique or desired colour they need after mixing two
or more colours. So, to overcome this problem an application was known as “sketch -to-
image synthesis while using conditional generative adversarial network” (Cgan)

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.
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
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…
2.What are we going to build?
At the end of this article, 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.
We aim to build an application which looks like:
CHAPTER-3
METHODOLOGY

3.1. CARTOONIFY the Image:

Fig: 1 CARTOONIFY the image


• The process to create a cartoon effect image can be initially branched into
2 divisions –To detect, blur and bold the edges of the actual RGB colour
image. To smooth, quantize and the conversion of the RGB image to
grayscale. The results involved in combining the image and help achieve
the desired result.
• In order to convert the image given by the user to cartoon, first it is
converted to grayscale. 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 grayscale Image.
• To smoothen an image, we simply apply a blur effect. This is done using
median Blur () function. We use bilateral Filter which removes the noise.
It can be taken as smoothening of an image to an extent. Here, we will try
to retrieve the edges and highlight them. This is attained by the adaptive
thresholding technique. We perform bitwise and on two images to mask
them. This finally CARTOONIFY our image.
3.2Designing
CARTOONIFY: Convert Images to Cartoon-Style Image:

Fig. Flowchart for Workflow of Webapp


• Above Figure represents Flowchart for CARTOONIZER webapp. Firstly, the user clicks
on the button select the image or video. After the system opens window for local storage.
System checks for image/video formats allowed. Then the selected image or video will be
uploaded to convert into cartoon image/video. After the successful upload of image/video
the system processes input and produces the output. After the CARTOONIZED output
gets displayed on screen, the user may download the image/video by clicking on
download button. Downloaded result will be stored into the local storage. Finally, the user
can come out of the system.
• After the CARTOONIFY output gets displayed on screen, the user may download the
image/video by clicking on download button. Downloaded result will be stored into the
local storage. Finally, the user can come out of the system.
• For videos, the video being uploaded must have size less than or equal to 30mb. If the
video is longer than 15sec, then it is trimmed to 15sec and converted to cartoon-style
video. Audio will be added to the CARTOONIZED video. First 15sec of the video will be
considered.
Fig: 2 REAL AND CARTOONIFY IMAGE
Auto-painter: Cartoon Image Generation from Sketch by Using Conditional
Generative Adversarial Networks:

Fig:3.3.1 Generative Adversarial Networks

Fig.3.3.2 Discriminator

Fig:3 Real image Fig:4 Real to sketch image


A contains the sketch edge information and A’ mainly contains trained colour painting
information.
3.3Testing
3. CARTOONIZATION Using White-box Technique:
This model is the fastest among four methods on all devices and all resolutions, and has the
smallest model size. Especially, this model can process a 720*1280 image on GPU within
only 17.23ms, which enables it for real-time High-Resolution video processing tasks. This
model applied on diverse real-world scenes, including natural landscape, city views, people,
animals, and plants.

Fig. White Box Technique

Fig: 5 CARTOONIZATION using White Box


1.Import Required Libraries
We will start by importing the required libraries such as OpenCV, NumPy, and Matplotlib.
these libraries will provide us with necessary function to load, process and display the image.
2.load the Image
The first step is to load the input using the function in OpenCV. we can load any image such
as PNG, JPEG, or , BMP.
3.Pre-processing
Pre-processing is an essential step in image processing. we will apply a bilateral filter to the
input image to remove noise and smooth the image this step help to preserve edges while
removing the unwanted details from the image. The bilateral filter is a non -linear filter that
preserves edges while smoothing the image.

4.Feature extraction
Feature extraction is a critical step in Machine learning. we will use the canny edge detection
algorithm is a multi-stage algorithm that detects the edges of an image by looking for the
areas of rapid change in intensity. We will then apply a threshold to the edges to obtain a
binary image.

5.Image transformation
After feature extraction, we will apply a transformation to the binary image to convert it into
a cartoon -like image. We will use the bitwise and function in OpenCV to combine the edges
and the pre-processed image. The bitwise and function take the binary image and the pre-
processed image and perform a bitwise AND operation to produce the final image.

6.Display the result


Final, we will display the input image, the pre-processed image, the edges, and the final
cartoon image side by side using the Matplotlib library. The Matplotlib library provides a
convenient way to display images and plot graphs.
In this project we are accepting input image and then extracting edges, grey image, then
applying median blur with Bilateral Filter technique to convert input mage to cartoon image.
To run this project, you need to have 64-bit operating system and then install python3.7
software which I will send you with Coad. Install this python1n software and then in first or
second installation screen in button you will find checkbox saying add path to variable. You
just select that checkbox and continue with installation. after installation open command
prompt and execute below command. your system must connect to internet before executing
below commands.
• pip install NumPy
• pip install SciPy
• pip install OpenCV-python
• pip install pillow
GAN i.e. “Generative Adversarial Networks “algorithm is used for the
implementation. GAN is a combination of a generative model and a discriminative
model. The generative model creates new instances of data that resembles the training
data. the discriminator is the model used for testing the data comparing it with the
image is fake or real. the Generator and discriminator both are neural network and
both run in competition with each other in the training phase. Compare to the previous
method of cartoon image but, in our project, we only train the real-world image that is
captured with the help of a camera.

Fig:6 CARTOONIZATION using GAN


Fig: 7 Active Diagram

The above activity diagram shows the working of the proposed method. Where it gives an overall
brief idea on how the images and video taken from the camera are converted into cartoon style
(Animation).
Coding and Designing
Chapter – 4

4.1 Converting Image into A cartoon Image


Import cv2:
--> pip install cv2

Then we will import cv2 inside our code, after that, we will use some
of the following functions:
1.Cv2: Imported to use OpenCV for image processing
2. easy Gui: Imported to open a file box. It allows us to select any file from our system.
3. NumPy: Images are stored and processed as numbers. These are taken as arrays. We use
NumPy to deal with arrays.

4. Image Io: Used to read the file which is chosen by file box using a path.
5. Matplotlib: This library is used for visualization and plotting. Thus, it is imported to
form the plot of images.

6. OS: For OS interaction. Here, to read the path and save images to that path.
7. imread ()- This function will load the image i.e in the specified folder.
8. cvtColor ()- This function takes color as an argument and then changes the source image
color into that color.

Steps:
1. Import all required modules (NumPy, image Io, scipy.ndimage, OpenCV)
2. Take Image input
3. Check RGB value of image and convert into according to RGB values
4. Show finale image output using cv2.imwrite()
4.1 Image Processing

Step1: Import Libraries


OpenCV is the only library which is needed for the project.
We will also be using matplotlib library for some visualizations which
is discussed later.

Coding:
import cv2
import matplotlib.pyplot as plt

Step 2: Read Photo


The following command can be used to read image using OpenCV
Coding:
img= cv2.imread('Baby2.jpg')

This command reads the file Baby2.jpg located in the current folder
and stores in memory as img.
Step 3 Show Image using OpenCV

Displaying image using OpenCV is not very straight forward. The following command can
be used to display the photo.

When this command is executed, the below photo will open in a new window with title as

‘original image.’

Coding:
cv2.imshow("orignal ", img)
cv2.imwrite("orignal img.jpg", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
output:

Fig: 8 Baby2.jpg
Step 4: building a File Box to choose a particular file
Explanation:
In this step, we will build the main window of our application, where
the buttons, labels, and images will reside.

Step 5: Beginning with image transformations:


Explanation:
To convert an image to a cartoon, multiple transformations are done.
Firstly, an image is converted to a Grayscale image. Finally, we form
a color1 image and mask it with edges. This creates a beautiful
cartoon image with edges and lightened color1 of the original image.
6: Transforming an image to grayscale
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 grayscale Image.
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.
Coding:
This coding is to convert the real image into grayscale
import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Output2",gray)
cv2.imwrite("gray.jpg",gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Fig: -9 grayscale image


Step 7: Smoothening a grayscale image and simply apply a blur effect.
Explanation:
To smoothen an image, we simply apply a blur effect. This is done using median
Blur () function.
Coding:
This coding is to convert the grayscale into Gray blur image
import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blrimg = cv2.medianBlur(gray,9)
cv2.imshow("output3", blrimg)
cv2.imwrite("blrimg.jpg", blrimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:

Fig: 10 Gray blur image


Step 8: Retrieving the edges of an image
Explanation:
In this step, we will work on the first specialty. Here, we will try to retrieve the
edges and highlight them.
Coding: - This coding converts the image into grayscale, Gray blur and edge
image
import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blrimg = cv2.medianBlur(gray,9)
edgs = cv2.adaptiveThreshold(Blrimg, 255,
cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,
5,5)
cv2.imshow("output5", edgs)
cv2.imwrite("edgs.jpg", edgs)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output

Fig: -11 Edge image


Step 9: Preparing a Mask Image
Explanation:
In the above code, we finally work on the second specialty. We prepare a lightened color1
image that we mask with edges at the end to produce a cartoon image. We use bilateralFilter1
which removes the noise. It can be taken as smoothening of an image to an extent.

Coding: - This coding to convert the real image into mask image
import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
maskimg = cv2.medianBlur(img,9)
cv2.imshow("output3", maskimg)
cv2.imwrite("mask imge.jpg", maskimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:

Fig: - 12 mask image


Step 10: Giving a Cartoon Effect
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?
Yes, so that’s how we mask edged image on our “BEAUTIFY” image.
This finally CARTOONIFY our image!

Coding

import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blrimg = cv2.medianBlur(gray,9)
maskimg = cv2.medianBlur(img,9)
edgs = cv2.adaptiveThreshold(Blrimg, 255,
cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,
5,5)
color = cv2.bilateralFilter(img, 7, 250, 250)
cartoon = cv2.bitwise_and (color,color, mask=edgs)
cv2.imshow("output6", cartoon)
cv2.imwrite("cartoon.jpg", cartoon)
cv2.waitKey(0)
cv2.destroyAllWindows()
output:

Fig: 13 CARTOONIFY IMAGE


Step 11: Plotting all the transitions together
The code below will display all the images in one frame using the subplots.

import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blrimg = cv2.medianBlur(gray,9)
maskimg = cv2.medianBlur(img,9)
edgs = cv2.adaptiveThreshold(Blrimg, 255,
cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,
5,5)
color = cv2.bilateralFilter(img, 7, 250, 250)
cartoon = cv2.bitwise_and (color,color, mask=edgs)
cv2.imshow("output1", img)
cv2.imwrite("orignal img.jpg", img)
cv2.imshow("Output2”, gray)
cv2.imwrite("gray.jpg”, gray)
cv2.imshow("output3", blrimg)
cv2.imwrite("blrimg.jpg", blrimg)
cv2.imshow("output4",Blrimg)
cv2.imwrite("Blrimg.jpg",Blrimg)
cv2.imshow("output5", edgs)
cv2.imwrite("edgs.jpg", edgs)
cv2.imshow("output6", cartoon)
cv2.imwrite("cartoon.jpg", cartoon)
Plotting all the transitions together
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.

Fig: 14 All Outputs images


CHAPTER –5

5.1Converting Image into A Pencil Sketch


In Python, an image is just a two-dimensional array of integers. So, one can do a
couple of matrix manipulations using various python modules in order to get
some very interesting effects. In order to convert the normal image to a sketch,
we will change its original RGB values and assign its RGB values similar to
grey, in this way a sketch of the input image will be generated.
Step 1:
5. Import all required modules (numpy, imageio, scipy. ndimage, OpenCV)
6. Take Image input
7. Check RGB value of image and convert into according to RGB values
8. Show finale image output using cv2.imwrite()

Step 2:
Import cv2:
--> pip install cv2
Then we will import cv2 inside our code, after that, we will use some of the
following functions:
1. imread ()- This function will load the image i.e in the specified
folder.
2. cvtColor ()- This function takes color as an argument and then
changes the source image color into that color.
3. bitwise_not ()- This function will help the image to keep the
properties as same by providing the masking to it.
4. GaussianBlur ()- This function is used to modify the image by
sharpening the edges of the image, smoothen the image, and will
minimize the
blurring property.
5. divide ()- This function is used for the normalization of the image
as it doesn’t lose its previous properties.
Finally will save the image using imwrite() function.
5.2 Image Processing

Step1: Import Libraries


OpenCV is the only library which is needed for the project.
We will also be using matplotlib library for some visualizations which
is discussed later.

Coding:
import cv2
import matplotlib.pyplot as plt

Step 2: Read Photo


The following command can be used to read image using OpenCV

Coding:
img= cv2.imread('Baby2.jpg')

This command reads the file Baby2.jpg located in the current folder
and stores in memory as img.
Step 3 Show Image using OpenCV

Displaying image using OpenCV is not very straight forward. The following
command can be used to display the photo.

When this command is executed, the below photo will open in a new window
with title as ‘original image.’

Coding:
cv2.imshow("orignal ", img)
cv2.imwrite("orignal img.jpg", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
output:

Fig: 15 Original Image Pencil Sketch


Step 4. Converting Image to GrayScale

To decrease the complexity of the image and make the handling easier we will
be converting the image to a grayscale image with the help of
the cvtColor function. The same is plotted with the help of the code mentioned
below
Coding: The code to Grayscale the image is shown below.
import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Output2",gray)
cv2.imwrite("gray.jpg",gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Fig: 16 Grayscale image Pencil Sketch


Step 5. Inverting the Image
Now the next step is to invert the image. Now your question would be why to do that? The answer to
the same is that when an image is inverted it helps in studying the image with more precision and
detail.
The more detailed study is important for the sketch generation as the sketches need to be accurate and
good.

Coding: The code to invert the image is shown below.


import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
invert= cv2.bitwise_not(gray)
cv2.imshow("output3", invert)
cv2.imwrite("invert.jpg", invert)
cv2.waitKey(0)
cv2.destroyAllWindows()
The output of inverted image is displayed below.

Fig: - 17 Inverted Image Pencil sketch


Step.6 Inverting Blur the Image
In addition to this, we will also be smoothing the image to make sure the sketch we obtain is
less edgy and smooth.

Coding: The code for the same is shown below


import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
invert= cv2.bitwise_not(gray)
blur = cv2.GaussianBlur(invert,(21,21),0)
invtblr = cv2.bitwise_not(blur)
cv2.imshow("output4",blur)
cv2.imwrite("invert blur.jpg",blur)
cv2.imshow("output5", invtblr)
cv2.imwrite("invtblur.jpg", invtblr)
cv2.waitKey(0)
cv2.destroyAllWindows()
The output image is shown below

Fig:- 18 Smooth Inverted Image Pencil Sketch Fig:-19 Smooth Invert blur Image Pencil
Sketch
Step 7. Converting your images to pencil sketches
Now that the whole image processing is done, we will be passing the previous outputs to the
function and pass the right and accurate parameters to make the appropriate changes to the
image.

Coding: The same is mentioned in the code below

import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
invert= cv2.bitwise_not(gray)
blur = cv2.GaussianBlur(invert,(21,21),0)
invtblr = cv2.bitwise_not(blur)
sketch = cv2.divide(gray,invtblr,scale=256.0)
cv2.imshow("output6", sketch)
cv2.imwrite("sketch.jpg", sketch)
cv2.waitKey(0)
cv2.destroyAllWindows()
The output is displayed below.

Fig: -20 Final Sketch Pencil Sketch


Step 8. Complete Coding real image Convert into Pencil Sketch image
The code below will display all the images in one frame using the subplots.

import cv2
img= cv2.imread('Baby2.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
invert= cv2.bitwise_not(gray)
blur = cv2.GaussianBlur(invert,(21,21),0)
invtblr = cv2.bitwise_not(blur)
sketch = cv2.divide(gray,invtblr,scale=256.0)

cv2.imshow("orignal ", img)


cv2.imwrite("orignal img.jpg", img)
cv2.imshow("Output2",gray)
cv2.imwrite("gray.jpg",gray)
cv2.imshow("output3", invert)
cv2.imwrite("invert.jpg", invert)
cv2.imshow("output4",blur)
cv2.imwrite("invert blur.jpg",blur)
cv2.imshow("output5", invtblr)
cv2.imwrite("invtblur.jpg", invtblr)
cv2.imshow("output6", sketch)
cv2.imwrite("sketch.jpg", sketch)
cv2.waitKey(0)
cv2.destroyAllWindows()
All Outputs Pencil Sketch Output:

Fig: - 21 All Outputs Pencil Sketch


CHAPTER-6
1.FUTURE SCOPE

The project showed that image was successfully converted into a cartoon-style
image with help of Cartoon GAN as mentioned in also the video clips were
transformed into a1n animation clip with the help of python library called cv2.
In the future work, we would like to focus more on generating a portrait defined
HD 1image even though we used the loss fu1nc1tion but still failed to the result.
we also plan on focusing more on the video conversion so we get HD or a 4k
Quality video which will be more beneficial. User will be provided with a set of
pretrained style image to choose from. Based on the chosen style and the
content image provided by the user, the resulting image with Cartoon like effect
is generated by the program. The implementation is based on of the combination
of Gatys a Neural Algorithm of Artistic Style, Johnsons Perceptual Losses for
Real-Time style transfer and super Resolution, and Ulyano1vs Instance
Normalization.
2.CONCLUSION
Thus, we have shown that how image can be converted to cartoon. we also
stated the examples on how image is converted to cartoon. hardware and
software requirement of image to cartoon conversion are also show in this
paper. The systematic working of image to cartoon conversion and respecting
algorithm and formulae is shown with neat diagram in this paper. Also, we have
state challenges and problems one can face while carttonifying1 the captured
image. In this paper we have also discussed need and scope of carttonifying1
the content image.
In this paper with the help of Cartoon GAN, where GAN stands for Generative
adversarial Network is used to transfor1m image(snapshots) to the finest
cartooned image (animated image). with the help of the loss function and its two
types named as Adversarial loss and Content Loss, we got a 37lexible as well as
a clear edge defined images. Also, with the help of CV2 which is known as
Computer vision, we have transformed video into animation (cantonized video).
3.REFERENCES

1. MD. Salar Mohammad, Bollepalli Pranitha,Shivani Goud Pandula, Pulakanti Teja


Sree.(2021). “Cartoonizing the Image” an International Journal of Advanced Trends in
Computer Science and Engineering, Volume 10,No.4, July – August 2021.
2. S. Rajatha, Anusha Shrikant Makkigadde, Neha L. Kanchan, Sapna, K. Janardhana
Bhat,”Cartoonizer: Convert Images and Videos to Cartoon-Style Images and Videos” an
International Journal of Research in Engineering, Science and Management Volume 4, Issue
7, July 2021.
3.Zengchang Qin, Zhenbo Luo, Hua Wang, " Auto-painter: Cartoon Image Generation from
Sketch by Using Conditional Generative Adversarial Networks”, International Journal on
Image Processing, 2017.
4.Harshitha R,Kavya S Muttur,Prof.Jyothi Shetty Dept. Computer Science,RV College of
Engineering,Bangalore . “Cartooniation Using White-box Technique in Machine
Learning”(2020).
5.Akanksha Apte, Ashwathy Unnikrishnan, Navjeevan Bomble, Prof. Sachin Gavhane,
“Transformation of Realistic Images and Videos into Cartoon Imagesand Video using GAN”
an International Journal of Research in Engineering, Science and Management Volume 4,
Issue 7, July2021.

6.Silviya D’monte, Aakash Varma, Ricky Mhatre, Rahul Vanmali, Yukta sharma
7.Chinmay Joshi, Devendra Jaiswal, Akshata Patil Department Name of Organization:
Information Technology Name of Organization: Kc College of Engineering Management
Studies and Research City: Kopari Thane (East) Country: India

You might also like