0% found this document useful (0 votes)
29 views

Cg Project

Uploaded by

vinayvinay23686
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Cg Project

Uploaded by

vinayvinay23686
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

ABSTRACT

Computer graphics is an art of drawing pictures, lines, charts, etc. using computers with the help of
programming. Computer graphics image is made up of number of pixels. Pixel is the smallest addressable
graphical unit represented on the computer screen. Computer graphics is a field of computing that enables the
creation, manipulation, and representation of visual images using computers. It encompasses a wide range of
techniques and technologies that have revolutionized the way we interact with digital information and visual
media.
The importance of computer graphics extends across various domains, including entertainment (such as
movies, video games, and virtual reality), design (architecture, industrial design, and graphic design),
simulation (flight simulators, medical simulations), education (interactive learning tools, digital textbooks),
and scientific visualization (data analysis, molecular modeling). Computer graphics is a field of computing
that enables the creation, manipulation, and representation of visual images using computers. It encompasses
a wide range of techniques and technologies that have revolutionized the way we interact with digital
information and visual media. Developed by Silicon Graphics Inc. (SGI) in 1992, OpenGL was designed to
provide a standardized interface for hardware-accelerated 2D and 3D graphics. Over the years, it has become
an industry-standard API and is supported by a wide range of platforms, including Windows, macOS, Linux,
and mobile platforms like Android and iOS.
OpenGL continues to evolve with advancements in graphics hardware and software technologies. Recent
developments focus on enhancing support for modern rendering techniques, improving compatibility with
new hardware architectures, and integrating with emerging technologies such as VR, AR, and real-time ray
tracing. OpenGL remains a fundamental tool for developers and graphics professionals.

iv
Table of Contents
ABSTRACT ......................................................................................................................................i
1. Introduction .................................................................................................................................. 1
1.1 Introduction to Computer Graphics ........................................................................................ 1
1.1 Introduction to OpenGL ......................................................................................................... 3
1.2 Introduction to OpenCV......................................................................................................... 5
1.3 Introduction to Project ........................................................................................................... 6
2. Inbuilt Function in Computre Graphics .......................................................................................9
2.1 OpenGL..................................................................................................................................9
2.2 OpenCV ............................................................................................................................... 11
3. Requirement Specification ........................................................................................................ 12
3.1 Hardware Requirements .......................................................................................................13
3.2 Software Requirements ....................................................................................................... 14
4. Implementation ..........................................................................................................................15
5. Snapshots ...................................................................................................................................30
Conclusion Future
Work References

iv
List of Figures
Sl.no Title Page No

1 Build an Application 18

2 Original image 18

3 Grayscale image 21

4 Smoothening a grayscale image 22

5 Edge image 23

6 Color image 24

7 Cartoon image 25

8 Final output 26

9 Home page 27

10 Final Result 28

iv
Chapter 1
INTRODUCTION

1.1 Introduction to Computer graphics


• The term computer graphics (CG) describes the use of computers to create and manipulate images.
Computer graphics refers to a technology that generates images on a computer screen. It’s used in
digital photography, film and television, video games, and on electronic devices and is responsible for
displaying images effectively to users. Think of computer graphics as the intersection of design and
computer science, with the purpose of delighting and engaging audiences.

• Graphics can be two- or three-dimensional • Computer Graphics is the creation and manipulation of
images or pictures with the help of computers. •

• There are two types of computer graphics: 1) Passive Computer Graphics (Non-interactive
Computer Graphics) 2) Active Computer Graphics (Interactive Computer Graphics

• The major product of computer graphics is a picture, with the help of CG, pictures can be
representedin2D and 3Dspace. Many applications show various parts of the displayed picture
changing in size and orientation. Such type of transformations i.e. the pictures can be made to
grow, shrink, rotate and etc. can be achieved through CG.

• The display on them is often too big to be shown in their entirety. Thus, with the help of CG, a
technique called clipping can be used to select just those parts of the picture that lie on the screen
and to discard the rest.
• Animated films use many of the same techniques that are used for visual effects, but without
necessarily aiming for images that look real. CAD/CAM stands for computer-aided design and
computer-aided manufacturing. These fields use computer technology to design parts and products
on the computer and then, using these virtual designs, to guide the manufacturing process. For
example, many mechanical parts are designed in a 3D computer modeling package and then
automatically produced on a computer-controlled milling device. Developing Sustainable Water
management system for rural areas and implementation approaches.
Swachh Bharat, Make in India, Mudra scheme, Skill development programs etc.
• Spreading public awareness under rural outreach programs.
• Social connect and responsibilities.
• Plantation and adoption of plants. Know your plants.
• Organize National integration and social harmony events /workshops /seminars.

Dept. of CSE,SaIT 2023-24 Page No 01


Cartoonify image

Key Concepts

1. Raster Graphics:
o Pixels: The smallest unit of a digital image, usually arranged in a grid to form an image.
o Resolution: The number of pixels in an image, typically measured in width x height.
o Color Models: Methods for representing colors in digital images, such as RGB (Red, Green,
Blue) and CMYK (Cyan, Magenta, Yellow, Black).
2. Vector Graphics:
o Primitives: Basic geometric shapes like points, lines, curves, and polygons.
o Scalability: Vector graphics can be resized without losing quality because they are defined
mathematically.
3. 3D Graphics:
o Vertices and Edges: Basic elements used to define 3D objects.
o Meshes: Collections of vertices, edges, and faces that define the shape of a 3D object.
o Transformations: Operations such as translation, rotation, and scaling applied to 3D objects.
4. Rendering:
o Rasterization: The process of converting vector graphics into raster images.
o Ray Tracing: A rendering technique that simulates the way light interacts with objects to
produce highly realistic images.
o Shading Models: Methods for calculating the color of surfaces based on light sources, such
as Phong shading and Gouraud shading.
5. Animation:
o Keyframing: Creating animations by specifying the start and end points, with the system
interpolating the frames in between.
o Rigging and Skinning: Techniques for animating complex models, especially characters.
6. Graphics Hardware:

o GPUs (Graphics Processing Units): Specialized hardware designed to perform the


calculations needed for rendering images quickly.

o Shaders: Programs that run on the GPU to perform custom rendering calculations

Dept. of CSE, SaIT 2023-24 Page No 02


Cartoonify image

Applications

1. Entertainment:
o Video Games: Creating interactive worlds and characters.
o Movies and TV: Producing special effects and animated films.
2. Design and Manufacturing:
o CAD (Computer-Aided Design): Designing products, buildings, and machinery.
o CAM (Computer-Aided Manufacturing): Using designs to control manufacturing
processes.
3. Visualization:
o Scientific Visualization: Representing scientific data in visual formats.
o Medical Imaging: Visualizing complex medical data from scans like MRIs and CTs.
4. User Interfaces:
o Graphical User Interfaces (GUIs): Allowing users to interact with computers through visual
elements like windows, icons, and buttons.

1.2 Introduction to OpenGL


OpenGL is a software interface to graphics hardware. This interface consists of about 150 distinct commands
that you use to specify the objects and operations needed to produce interactive three−dimensional
applications. OpenGL is designed as a streamlined, hardware−independent interface to be implemented on
many different hardware platforms. To achieve these qualities, no commands for performing windowing tasks
or obtaining user input are included in OpenGL; instead, you must work through whatever windowing system
controls the particular hardware you’re using. Similarly, OpenGL doesn’t provide high−level commands for
describing models of three−dimensional objects. Such commands might allow you to specify relatively
complicated shapes such as automobiles, parts of the body, airplanes, or molecules. With OpenGL, you must
build up your desired model from a small set of geometric primitives, points, lines, and polygons. OpenGL is
no longer in active development, whereas between 2001 and 2014, OpenGL specification was updated mostly
on a yearly basis, with two releases taking place in 2009 and three in 2010, the latest OpenGL specification
4.6 was released in 2017, after a three-year break, and was limited to inclusion of eleven existing ARB and
EXT extensions into the core profile.

Active development of OpenGL was dropped in favour of the API, released in 2016, and code named Gl
Next during initial development. In 2017, announced that OpenGL ES would not have new versions
a
nd has since concentrated on development of Vulkan and other technologies. As a result, certain
capabilities offered by modern GPUs, e.g. ray tracing, are not supported by OpenGL

Dept. of CSE, SaIT 2023-24 Page No 03


Cartoonify image

Key Concepts

1. Rendering Pipeline:
o Vertex Processing: Vertices are transformed and processed to determine their position on the
screen.
o Clipping: Parts of objects outside the view are discarded.
o Rasterization: Transformed vertices are converted into fragments.
o Fragment Processing: Fragments are processed to determine their final color and depth.
o Frame Buffer Operations: Final image is composed in the frame buffer and displayed on the
screen.
2. Shaders:
o Vertex Shader: Processes each vertex's attributes (position, color, normal, etc.).
o Fragment Shader: Processes fragments generated by rasterization to determine their final
color.
o Geometry Shader: Can add or modify geometry on the fly (optional and more advanced).
3. Buffers:
o Vertex Buffer Object (VBO): Stores vertex data.
o Element Buffer Object (EBO): Stores indices for indexed drawing.
o Frame Buffer Object (FBO): Stores rendered images off-screen.
o Texture Buffer: Stores texture data.
4. Textures:
o Images applied to the surfaces of 3D models to give them detail.
5. Transformations:
o Model Transformation: Moves objects in the scene.
o View Transformation: Simulates the camera position and orientation.
o Projection Transformation: Maps 3D coordinates to 2D screen coordinates.

Basic Workflow

1. Initialize OpenGL Context:


o This is usually done through a windowing system (e.g., GLFW, GLUT).
2. Load and Compile Shaders:
o Write and compile vertex and fragment shader

Dept. of CSE, SaIT 2023-24 Page No 04


Cartoonify image

3. Set Up Buffers:
o Create and bind VBOs and EBOs.
o Upload vertex and index data.
4. Configure Vertex Attributes:
o Define how vertex data is interpreted and passed to the shaders.
5. Render Loop:
o Clear the screen.
o Draw objects.
o Swap buffers to display the rendered frame.

1.3 Introduction to OpenCV

OpenCV (Opensource Computer Vision Library) is an open-source computer vision and machine learning
software library. Initially developed by Intel, it was later supported by Willow Garage and It sees (now part
of Intel). OpenCV is widely used for various applications in computer vision, image processing, and
machine learning. The image processing module in OpenCV is crucially used for tasks related to
manipulating images. It encompasses functions for filtering, transforming, and enhancing images. Human
vision has a resemblance to that of computer vision. Human vision learns from the various life
experiences and deploys them to distinguish objects and interpret the distance between various objects
and estimate the relative position.

Here’s an introduction to its key concepts and features:

Key Concepts

1. Image Processing:
o Basic Operations: Reading, writing, and displaying images.
o Image Transformations: Resizing, cropping, rotating, and affine transformations.
o Color Space Conversions: Converting between different color spaces (e.g., RGB to
Grayscale, HSV).
2. Filtering and Enhancement:
o Smoothing/Blurring: Applying Gaussian, median, and bilateral filters.
o Sharpening: Enhancing edges to make images clearer.
o Histogram Equalization: Improving the contrast of images.
3. Feature Detection and Matching:
o Edge Detection: Using algorithms like Canny to detect edges in image

Dept. of CSE, SaIT 2023-24 Page No 05


Cartoonify image

o Corner Detection: Using algorithms like Harris corner detection.


o Feature Descriptors: Extracting features using SIFT, SURF, ORB, etc.
o Feature Matching: Matching features between images using descriptors.
4. Object Detection and Recognition:
o Face Detection: Using Haar cascades and deep learning-based methods.
o Object Tracking: Tracking objects in videos using algorithms like Mean shift, Cam shift,
and Kalman filters.
o Deep Learning: Integrating deep learning models for object detection (e.g., YOLO, SSD).
5. Image Segmentation:
o Thresholding: Converting images to binary using global or adaptive thresholding.
o Contours: Finding and drawing contours in images.
o Watershed Algorithm: Segmenting objects in images using markers.
6. Camera Calibration and 3D Reconstruction:
o Camera Calibration: Calibrating the camera to remove distortions.
o Stereo Vision: Using two cameras to capture 3D information.
o Structure from Motion (SFM): Reconstructing 3D structures from multiple images.

Applications of Computer Vision

Here we have listed down some of major domains where Computer Vision is heavily used.

• Localization − Determine robot location automatically


• Navigation
• Obstacles avoidance
• Assembly (peg-in-hole, welding, painting)
• Manipulation (e.g. PUMA robot manipulator)
• Human Robot Interaction (HRI) − Intelligent robotics to interact with and serve people.

1.4 Introduction to Project

Cartoonifying an image is a captivating process that transforms ordinary photographs into vibrant
and whimsical cartoon-like representations. This technique involves accentuating certain features,
simplifying details, and applying artistic interpretations to create a playful and imaginative visual
effect. Whether for personal enjoyment, creative projects, or social media engagement, cartoonifying
images adds a unique charm and storytelling element, bridging the gap between reality

Dept. of CSE, SaIT 2023-24 Page No 06


Cartoonify image

and fantasy. Through a combination of digital tools, artistic flair, and a keen eye for exaggeration,
this art form brings a fresh perspective to familiar scenes and faces, making them memorable and
delightful to behold.

Objectives:

1. Understanding Image Processing: Learn how to manipulate images programmatically using


OpenCV.
2. Implementing Image Transformation Techniques: Apply techniques like Gaussian blur, edge
detection, and color quantization to transform images into cartoon-like representations.
3. Exploring Python Libraries: Gain proficiency in using Python libraries such as OpenCV and
NumPy for image manipulation tasks.
4. Developing a Visual Artistic Sense: Learn to interpret and enhance images artistically through
digital means.
5. Creating a Project Portfolio: Build a portfolio showcasing your skills in image processing and
artistic interpretation.

Key Concepts:

1. Image Transformation: Techniques such as Gaussian blur to smoothen the image and edge
detection to highlight edges, crucial for cartoonification.
2. Color Quantization: Reducing the number of colors in an image to create a flat, cartoonish
appearance.
3. Artistic Interpretation: Understanding how to stylize images to achieve a cartoon-like effect while
preserving essential details.
4. Parameter Tuning: Adjusting parameters of filters and transformations to achieve desired
cartoonification effects.
5. Image Filtering: Using filters like bilateral filter and median blur to enhance edges and reduce noise.

Dept. of CSE, SaIT 2023-24 Page No 7


Cartoonify image

Tools and Techniques:

1. OpenCV: Essential library for computer vision and image processing tasks in Python.
2. NumPy: Used for numerical operations and array manipulation, crucial for handling image data.
3. Python Programming: Utilize Python for implementing algorithms and managing image processing
workflows.
4. Edge Detection Algorithms: Techniques like Canny edge detection to identify and highlight edges
in images.
5. Color Quantization Methods: Algorithms to reduce the number of colors in an image, enhancing
the cartoon effect.

Techniques:

1. Grayscale Conversion: Convert the input image to grayscale as a preprocessing step.


2. Smoothing: Apply Gaussian blur to reduce noise and prepare the image for edge detection.
3. Edge Detection: Use techniques such as Laplacian or Canny edge detection to highlight edges in the
image.
4. Color Quantization: Reduce the number of colors in the image to achieve a flat, cartoonish
appearance.
5. Combining Images: Blend the processed cartoon image with the original image to retain important
details.

Dept. of CSE, SaIT 2023-24 Page No 08


CHAPTER 2

INBUILT FUNCTIONS IN COMPUTER GRAPHICS


(OPENGL/OPENCV)
Computer graphics libraries like OpenGL and OpenCV provide a wide range of inbuilt functions that
facilitate the creation and manipulation of graphical content. Below is an overview of some commonly used
functions in each of these libraries.

OpenGL

OpenGL (Open Graphics Library) is a cross-language, cross-platform API for rendering 2D and 3D vector
graphics. It provides a rich set of functions for various graphics operations:

1. Initialization and Configuration


o Glut Init: Initializes the GLUT library.
o Glut Create Window: Creates a window with an OpenGL context.
o Glut Init Display Mode: Sets the initial display mode (e.g., color model, buffering).
2. Drawing Primitives
o GlBegin: Begins the definition of a geometric primitive (e.g., GL_TRIANGLES,
GL_QUADS).
o GlEnd: Ends the definition of a geometric primitive.
o g l Vertex: Specifies a vertex (glVertex3f for 3D coordinates).
3. Transformation Functions
o glTranslate: Translates (moves) an object (gl Translate for 3D translation).
o gl Rotate: Rotates an object (glRotatef for rotation about an axis).
o gl Scale: Scales an object (glScalef for scaling in 3D).
4. Viewing and Projection
o gl Matrix Mode: Sets the current matrix mode (GLPROJECTION, GL_MODELVIEW).
o gl Load Identity: Replaces the current matrix with the identity matrix.
o Glu Perspective: Defines a perspective projection matrix.
o Glu Look At: Defines a viewing transformation.
5. Buffer Operations
o Gl Clear: Clears buffers to preset values (e.g., GL_COLOR_BUFFER_BIT).
o Glut Swap Buffers: Swaps the front and back buffers (for double buffering).

Dept. of CSE, SaIT 2023-24


[Type here]
Page No 9
Cartoonify image

6. Texture Mapping
o Gl gen Textures: Generates texture names.
o Gl bind Texture: Binds a texture to a target
o gltextImage2D: Specifies a 2D texture image.
o gl text Parameter: Sets texture parameters.
7. Lighting and Materials
o gl Enable: Enables server-side GL capabilities (e.g., GL_LIGHTING).
o gl Lightfv: Sets light source parameters.
o Gl Materialfv: Sets material properties for the lighting model.
8. User Interaction
o Glut Keyboard Func: Registers a keyboard callback function.
o Glut Mouse Func: Registers a mouse callback function.
o Glut Motion Func: Registers a motion callback function.

OpenCV

OpenCV (Opensource Computer Vision Library) is an open-source computer vision and machine learning
software library. It provides numerous functions for image processing, computer vision, and machine
learning:

1. Basic Operations on Images


o cv: imread: Reads an image from a file.
o cv: imwrite: Writes an image to a file.
o cv: imshow: Displays an image in a window.
o cv: waitKey: Waits for a keystroke.
2. Drawing Functions
o cv: line: Draws a line.
o cv: circle: Draws a circle.
o cv: rectangle: Draws a rectangle.
o cv: put Text: Puts text on an image.

Dept. of CSE, SaIT 2023-24


[ Ty pe h ere ]
Page No 10
[ T y p e h er e]
Cartoonify image

3. Basic Operations on Images


o cv: imread: Reads an image from a file.
o cv: imwrite: Writes an image to a file.
o cv: imshow: Displays an image in a window.
o cv: waitKey: Waits for a keystroke.
4. Drawing Functions
o cv: line: Draws a line.
o cv: circle: Draws a circle.
o cv: rectangle: Draws a rectangle.
o cv: put Text: Puts text on an image.
5. Image Processing
o cv: cvtColor: Converts an image from one color space to another.
o cv: blur: Applies a blur filter.
o cv: Gaussian Blur: Applies a Gaussian blur filter.
o cv: resize: Resizes an image.
o cv: threshold: Applies a fixed-level threshold to each array element.
o cv: Canny: Applies the Canny edge detector.
6. Geometric Transformations
o cv: warp Affine: Applies an affine transformation to an image.
o cv: warp Perspective: Applies a perspective transformation to an image.
o cv: rotate: Rotates an image by 90, 180, or 270 degrees.

Dept. of CSE, SaIT 2023-24 Page No 11


[Type here] [Type here]
Chapter 3
REQUIREMENTS

3.1 Requirements specification


Creating a requirements specification for a Cartoonify Image involves detailing the functional and non-
functional requirements, system architecture, hardware and software prerequisites, and other relevant
aspects. Here's a comprehensive outline:

1. Introduction

The Cartoonify Image application aims to transform regular images into cartoon-like representations using
OpenCV and Python. This specification outlines the functional and non-functional requirements, system
architecture, hardware and software requirements, as well as development, deployment, and maintenance
considerations for the application.

2. Overall Description

The application will take an input image, process it using various image transformation techniques, and
output a cartoon version of the image. This process involves converting the image to grayscale, applying
edge detection, and then merging color tones to achieve the cartoon effect.

3. Functional Requirements

• Image Processing:
o Convert input image to grayscale.
o Apply edge detection techniques to highlight major edges.
o Reduce the number of colors in the image to give it a cartoon-like appearance.
o Merge color tones to simplify the image.
• User Interface:
o Provide a simple interface to upload images.
o Display the original and cartoonified images side by side.
o Allow users to download the cartoonified image.

4. Non-functional Requirements

• Performance:
o Process an image within a reasonable time frame (e.g., less than 10 seconds for typical image
sizes).

Dept. of CSE, SaIT 2023-24 Page No 12


Cartoonify image

Usability:

o Intuitive user interface with clear instructions.

5. System Architecture

The application will be implemented using the following components:

• Frontend: Web-based interface using HTML, CSS, and JavaScript.


• Backend: Python-based server using Flask framework for handling image processing requests.
• Image Processing: OpenCV library for image transformations and effects.

6. Development and Deployment

• Development Tools: Python IDE (e.g., PyCharm, VS Code), Git for version control

Deployment: Deployed on a cloud platform (e.g., Heroku, AWS) for accessibility

7. Maintenance

• Updates: Regular updates to libraries and frameworks (e.g., OpenCV, Flask).


• Bug Fixes: Prompt resolution of reported bugs.
• User Feedback: Consider user feedback for feature enhancements.

3.1.1 Hardware Requirements

Minimum Hardware Requirements:

• CPU: Dual-core processor (e.g., Intel Core i3 or equivalent)


• RAM: 4 GB
• Storage: 100 MB free disk space

Recommended Hardware:

• CPU: Quad-core processor (e.g., Intel Core i5 or equivalent)


• RAM: 8 GB or higher
• Storage: SSD recommended for faster read/write operations

Dept. of CSE, SaIT 2023-24 Page No 13


3.1.1 Software Requirements

Operating System:

• Supported Platforms: Windows, Linux, macOS


• Versions
o Windows: Windows 10 or later
o Linux: Ubuntu 18.04 LTS or later, CentOS 7 or latermacOS:
o macOS 10.14 Mojave or later

Development Environment:

• Python: Version 3.6 or higher


• Integrated Development Environment (IDE):
o Recommended: PyCharm, Visual Studio Code, or any Python IDE of choice
• Version Control:
o Git and GitHub (or GitLab, Bitbucket) for version control and collaboration

Python Libraries:

• OpenCV: Required for image processing functionalities.


o Installation: Install using pip (pip install opencv-python)
• Flask: Lightweight web framework for backend development.
o Installation: Install using pip (pip install Flask)
• NumPy: Fundamental package for numerical computing in Python.
o Installation: Install using pip (pip install numpy)

Web Browser Compatibility:

• Supported Browsers: Chrome, Firefox, Safari


• Minimum Version: Latest stable versions recommended for best performance and compatibility

Dept. of CSE, SaIT 2023-24 Page No 14


Chapter 4 IMPLEMENTATION

Hardware Requirements
Minimum Hardware Requirements:

• CPU: Dual-core processor (e.g., Intel Core i3 or equivalent)


• RAM: 4 GB
• Storage: 100 MB free disk space

Recommended Hardware:

• CPU: Quad-core processor (e.g., Intel Core i5 or equivalent)


• RAM: 8 GB or higher
• Storage: SSD recommended for faster read/write operations

Software Requirements
Operating System:

• Supported Platforms: Windows, Linux, macOS


• Versions:
o Windows: Windows 10 or later
o Linux: Ubuntu 18.04 LTS or later, CentOS 7 or later
o macOS: macOS 10.14 Mojave or later

Development Environment:

• Python: Version 3.6 or higher


• Integrated Development Environment (IDE):
o Recommended: PyCharm, Visual Studio Code, or any Python IDE of choice
• Version Control:
o Git and GitHub (or GitLab, Bitbucket) for version control and collaboration

Dept. of CSE, SaIT 2023-24 Page No 15


Cartoonify image

Python Libraries:

• OpenCV: Required for image processing functionalities.


o Installation: Install using pip (pip install opencv-python)
• Flask: Lightweight web framework for backend development.
o Installation: Install using pip (pip install Flask)
• NumPy: Fundamental package for numerical computing in Python.
o Installation: Install using pip (pip install numpy)

Web Browser Compatibility:

• Supported Browsers: Chrome, Firefox, Safari


• Minimum Version: Latest stable versions recommended for best performance and
compatibility

Deployment Environment
Server:

• Cloud Platform: Heroku, AWS EC2, Google Cloud Platform, etc.


• Operating System: Linux-based server (provided by the cloud platform)
• Web Server:
o Recommended: Nginx or Apache for serving web requests (if necessary,
depending on deployment complexity)

Database (if applicable):

• Database: SQLite (for lightweight local storage) or PostgreSQL, MySQL (for more
robust data storage needs)

Development and Deployment Considerations

• Development:
o Use virtual environments (e.g., venv or conda) to manage dependencies and
isolate project environments.
o Test the application locally using development servers provided by Flask
(flask run) for debugging and testing purpose

Dept. of CSE, SaIT 2023-24 Page No 16


Cartoonify image

Deployment:

o Deploy the application on a chosen cloud platform following their respective


deployment guides.
o Set up environment variables for sensitive information (e.g., API keys,
database credentials) securely in the deployment environment.

Maintenance

• Updates:
o Regularly update Python packages (pip install --upgrade package-name) to
leverage new features and security patches.
• Monitoring:
o Implement logging and monitoring (e.g., using tools like Prometheus,
Grafana) to track application performance and errors.
• Backup and Recovery:
o Set up regular backups of application data and configuration to ensure quick
recovery in case of failures.

Dept. of CSE, SaIT 2023-24 Page No 17


Cartoonify image

What are we going to build?


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:

Original Image:

Dept. of CSE, SaIT 2023-24 Page No 18


Cartoonify image

Step 1: Importing the required modules

We will import the following modules:

• CV2: Imported to use OpenCV for image processing

• 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

Dept. of CSE, SaIT 2023-24 Page No 19


Cartoonify 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)
Code
def cartoonify(ImagePath):
Step 3: How is an image stored?
Now, just think, how will a program read an image? For a computer, everything is just
numbers. Thus, in the below code, we will convert our image into a numpy array.
#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("Can not find any image. Choose appropriate file")
sys.exit()
ReSized1 = cv2.resize(originalmage, (960, 540))

Dept. of CSE, SaIT 2023-24 Page No 20


Cartoonify image

Beginning with image transformations:

To convert an image to a cartoon, multiple transformations are done. Firstly, an image is


converted to a Grayscale image. Yes, similar to the old day’s pictures.! Then, the Grayscale
image is smoothened, and we try to extract the edges in the image. Finally, we form a color
image and mask it with edges. This creates a beautiful cartoon image with edges and
lightened color of the original image.
Step 4: Transforming an image to grayscale
code
#converting an image to grayscale
grayScaleImage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2GRAY)
ReSized2 = cv2.resize(grayScaleImage, (960, 540))
#plt.imshow(ReSized2, cmap='gray')
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:

Dept. of CSE, SaIT 2023-24 Page No 21


Cartoonify image

Step 5: Smoothening a grayscale image


Code:
#applying median blur to smoothen an image
smoothGrayScale = cv2.medianBlur(grayScaleImage, 5)
ReSized3 = cv2.resize(smoothGrayScale, (960, 540))
#plt.imshow(ReSized3, cmap='gray')

Explanation:
To smoothen an image, we simply apply a blur effect. This is done using medianBlur()
function. Here, the center pixel is assigned a mean value of all the pixels which fall under the
kernel. In turn, creating a blur effect.
The above code generates the following output:

Step 6: Retrieving the edges of an image

Code
#retrieving the edges for cartoon effect
#by using thresholding technique
getEdge = cv2.adaptiveThreshold(smoothGrayScale, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 9, 9)
ReSized4 = cv2.resize(getEdge, (960, 540))
#plt.imshow(ReSized4, cmap='gray')

Dept. of CSE, SaIT 2023-24 Page No 22


Cartoonify image

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.
The above code will generate output like below:

Step 7: Preparing a Mask Image


Code
#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))
#plt.imshow(ReSized5, cmap='gray')
Explanation:
In the above code, we finally work on the second specialty. We prepare a lightened color

Dept. of CSE, SaIT 2023-24 Page No 23


Cartoonify image

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.
Yes, it’s similar to BEAUTIFY or AI effect in cameras of modern mobile phones.
The above code generates the following output:

Step 8: Giving a Cartoon Effect


Code
#masking edged image with our "BEAUTIFY" image
cartoonImage = cv2.bitwise_and(colorImage, colorImage, mask=getEdge)
ReSized6 = cv2.resize(cartoonImage, (960, 540))
#plt.imshow(ReSized6, cmap='gray')
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!
The above code will generate output like below

Dept. of CSE, SaIT 2023-24 Page No 24


Cartoonify image

Step 9: Plotting all the transitions together


Code:
# 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')
//save button code
plt.show()
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.
The above code will generate output like below:

Dept. of CSE, SaIT 2023-24 Page No 25


Cartoonify image

Step 10: Functionally of save button


Code:
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.
Here, newName stores “Cartoonified_Image” as the name of a new file. os.path.join(path1,
newName + extension) joins the head of path to the newname and extension. This forms the
complete path for the new file.
imwrite() method of cv2 is used to save the file at the path mentioned.

Dept. of CSE, SaIT 2023-24 Page No 26


Cartoonify image

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.

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'))
Step 12: Making the Cartoonify button in the main window
upload=Button(top,text="Cartoonify an Image",command=upload,padx=10,pady=5)
upload.configure(background='#364156', foreground='white',font=('calibri',10,'bold'))
upload.pack(side=TOP,pady=50)
Step 13: Making a Save button in the main window
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)
The above code makes a button as soon as the image transformation is done. It gives an
option to the user to save cartoonified image.

Dept. of CSE, SaIT 2023-24 Page No 27


Cartoonify image

Step 14: Main function to build the tkinter window


Code:
top.mainloop()
The Final Result:

Dept. of CSE, SaIT 2023-24 Page No 28


Chapter 5
SNAPSHOTS

The Final Result:

Dept. of CSE, SaIT 2023-24 Page No 29


CONCLUSION
This project successfully demonstrated the transformation of regular images into cartoon-like
representations using OpenCV and Python. Through the application of various image processing
techniques such as edge detection, color quantization, and bilateral filtering, we were able to achieve the
desired cartoon effect. The project involved several key steps, including preprocessing the image to
enhance edges, reducing color complexity to mimic cartoonish colors, and applying bilateral filtering for
smoothing while preserving edges.

The implementation leveraged OpenCV's comprehensive library of functions, which provided robust
support for image manipulation and processing tasks. By combining these techniques in a systematic
workflow, we effectively translated the input images into visually appealing cartoons, showcasing the
potential of computer vision in creative applications.

Furthermore, the project highlighted the importance of parameter tuning in achieving optimal results,
particularly in balancing edge preservation and noise reduction during the bilateral filtering stage.
Exploring different parameter combinations allowed us to refine the cartoonification process and enhance
the output quality.

Overall, this project not only deepened our understanding of image processing fundamentals but also
illustrated practical applications of computer vision in transforming digital media. Future enhancements
could involve integrating machine learning models for more sophisticated feature extraction or developing
interactive applications for real-time cartoonification, thereby expanding the project's scope and usability.

By documenting our methodologies, challenges, and outcomes, this report serves as a valuable resource
for anyone interested in exploring image cartoonification techniques using OpenCV and Python.
FUTURE SCOPE
Here are some potential future scopes and enhancements that could be explored on cartoonifying an image
with OpenCV in Python:

1. Integration of Deep Learning:*Explore the integration of deep learning models, such as convolutional neural
networks (CNNs), for more advanced feature extraction and style transfer techniques in cartoonification.
Models like CycleGAN could be employed to learn mappings between photographic and cartoon domains.

2. Real-time Cartoonification: Develop real-time applications using optimized algorithms and frameworks
(like OpenCV's DNN module or TensorFlow Lite) to enable live video cartoonification on devices with limited
computational resources.

3. Interactive User Interfaces: Create user-friendly interfaces (GUIs) using libraries like Tkinter or PyQt to
allow users to adjust parameters and visualize the cartoonification process in real-time.

4. Multi-style Cartoonification:Extend the project to support multiple cartoon styles (e.g., anime, comic book)
and allow users to select or customize their preferred style.

5. Evaluation Metrics: Define and implement quantitative metrics to evaluate the quality of cartoonification
outputs objectively, such as edge preservation, color fidelity, and perceptual similarity to hand-drawn cartoons.
REFERENCES

[1] Bradski, G., & Kaehler, A. (2008). Learning OpenCV: Computer Vision with the
OpenCV Library. O'Reilly Media.

[2] Liu, X., & Chen, D. (2013). Image cartoonization based on edge and region extraction.
Journal of Visual Communication and Image Representation, 24(7), 1154-1166.

[3] Achanta, R., et al. (2009). Frequency-tuned salient region detection. IEEE International
Conference on Computer Vision and Pattern Recognition, 2009. IEEE.

[4] Kaur, P., & Goyal, R. (2015). An efficient edge-preserving filtering algorithm for image
cartoonization. International Journal of Computer Applications, 121(15), 35-39.

[5] Szeliski, R. (2010). Computer Vision: Algorithms and Applications. Springer.

[6] Sonka, M., Hlavac, V., & Boyle, R. (2014). Image Processing, Analysis, and Machine
Vision. Cengage Learning.

[7] Gonzalez, R. C., & Woods, R. E. (2017). Digital Image Processing. Pearson Education.

[8] Burger, W., & Burge, M. J. (2016). Digital Image Processing: An Algorithmic
Introduction Using Java. Springer.

[9] Pratt, W. K. (2007). Digital Image Processing. John Wiley & Sons.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy