image-to-pencil-sketch

Image To Pencil Sketch Python OpenCV

Make Anime Image Look Like Manga

In this article, we shall implement a Python OpenCV code to convert an image to pencil sketch. If you are new to Python check out this amazing Python Tutorial Series.

Python OpenCV

Opencv is a Python open-source library that is used to implement Computer Vision, Machine Learning, and Image Processing problems. Let us start with installation:

pip install cv2

Read Image

The first step to convert an image to a sketch, you need to read the image. To read the image “imread” method in the cv2 module is used. The image path should be passed inside the cv2.imread as a string. Here is the syntax:

img = cv2.imread("gintoki.jpg")

In order to display the image, we can use “imshow” method. It takes 2 arguments, the first argument is to name the image window and the second argument is the image file.

cv2.imshow("Sakata Gintoki", img)

We shall now see steps to convert an image to pencil sketch by performing a few Python OpenCV methods.

Convert RGB To Gray Scale

Why Convert RGB To Gray Scale Image?

In the real world, the image is made up of 3 layers i.e., RBG. An RBG is a 3-dimensional vector that consists of numeric values in the range 0-255. By converting this RGB we are reducing a 3-dimensional vector to a 2-dimensional vector i.e., a grayscale image(black-white). It increases the speed of execution while dealing with Gray Scale as we are dealing with reduced data now. A normal colored image can be considered as noise, in order to eliminate the noise from the image you do it grayscale. Moreover, By converting an RGB image to a grayscale image it becomes easier to detect the edges.

#rgb color to gray scale
convert = cv2.cvtColor(img_file,cv2.COLOR_RGB2GRAY)

Gaussian Blur In OpenCV

Every image has some kind of noise associated with it. This noise can be in form of. In order to make our image smooth, we apply Gaussian Blur to the image. 

Syntax: cv2.GaussianBlur(image,kernel_size,sigmaX)

blur_img = cv2.GaussianBlur(img,(3,3),0)

To convert the image to a pencil sketch we shall first invert the gray scale image by subtracting with 255. Then apply Gaussian blur on the inverted image. Since we know grayscale is only made of black-white by inverting the grayscale image we are reversing the black and white proportion.

convert = cv2.cvtColor(img_file,cv2.COLOR_RGB2GRAY)
inverted_img = 255 - convert
#apply blur
blur_img = cv2.GaussianBlur(inverted_img,(21,21),0)

Saving The Image In OpenCV

Once you have modified the image, OpenCV also allows you to save the same. By using the cv2.imwrite method we shall save image to pencil sketch image.

cv2.imwrite("image-to-pencil-sketch.png",sketch_img)

Tkinter Filedialog

Python is one of the most popular programming languages that provides various frameworks. Tkinter is a Python Framework that enables us to create GUI applications. Tkinter provides many built-in widgets that help us to create a GUI app.  This widget includes Button, Text, Menu, ScrollBar, Frame, and so on. 

Tkinter Filedialog is a file handling module in Tkinter. Using the functionality of Filedialog we can open any file from our local device. 

Using FileDialog we shall open the image and feed it to cv2.imread and then perform the above steps i.e., Blurring, Converting, Inverting, and so on.

img = filedialog.askopenfile()

Image to Pencil Sketech GUI

"""
For saved image check the folder in which image was located
"""

import cv2
import tkinter as tk
from tkinter import filedialog,messagebox

def anime_img():
    global img_file,save_as
    #open any file that has to be converted
    img = filedialog.askopenfile()
    save_as,ext = img.name.split('.')   #we dont need an extension to be saved as filename
    img_file = cv2.imread(img.name)

def manga_img():
    try:
        #first convert into gray scale image
        convert = cv2.cvtColor(img_file,cv2.COLOR_RGB2GRAY)
        inverted_img = 255 - convert
        #apply blur
        blur_img = cv2.GaussianBlur(inverted_img,(21,21),0)
        #invert the blurred image by subtracting to 255
        #255 is the total range of an image
        final_inversion  = 255 - blur_img

        sketch_img = cv2.divide(convert,final_inversion,scale=255.0)
        #save the image
        cv2.imwrite("{}_manga.png".format(save_as),sketch_img)
        messagebox.showinfo("Success","File saved")
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    except NameError:
        messagebox.showerror("File Unknown","Choose an anime Image first")

def main():
    root = tk.Tk()
    root.geometry("425x425+450+180")
    root.title("Anime to Manga")
    canva = tk.Canvas(root,bg="black",bd=5)
    canva.place(x=0,y=0,width=430,height=430)
    root.minsize(425,425)
    root.maxsize(425,425)
    head = tk.Label(root,text="Mina-san Konnichiwa",font=("arial",20,"bold"),fg="black",bg="white")
    head.place(x=85,y=15)
    frame = tk.LabelFrame(root,bg="gray").place(x=50,y=90,width=330,height=280)
    select = tk.Label(frame,text="Select an Anime Picture",font=("arial",16,"bold"),fg="white",bg="black").place(x=92,y=120)
    convert = tk.Label(frame,text="Download img as Manga",font=("arial",16,"bold"),bg="white",fg="black").place(x=90,y=240)

    anime = tk.Button(frame,text="Anime",font=("arial",14,"bold"),bg="blue",fg="white",bd=5,command=anime_img)
    anime.place(x=128,y=160,width=170,height=50)

    manga = tk.Button(frame,text="Manga",bg="blue",fg="white",font=("arial",14,"bold"),bd=5,command=manga_img)
    manga.place(x=130,y=285,width=170,height=50)
    root.mainloop()

if __name__ == '__main__':
    main()
image-to-pencil-sketch

Conclusion

This is the first Python OpenCV-based article, I might start sharing more amazing stuff in this category. In order to stay tuned subscribe to our newsletter to get updates.

Newsletter: https://animevyuh.org/newsletter/

If you like our content support us: Buy Me A Coffee; Ko-Fi