Image to Pencil Sketch using Python and OpenCV

Image to Pencil Sketch using Python and OpenCV

In this post, we will go through a program to get a pencil sketch from an image using python and OpenCV.

Step 1:

To use OpenCV, import the library.

import cv2

Step 2:

Read the Image.

image = cv2.imread("vegeta.png")
cv2.imshow("Vegeta",image)
cv2.waitKey(0)

Vegeta.png

Step 3:

Create a new image by converting the original image to grayscale.

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("GrayVegeta",gray_image)
cv2.waitKey(0)

GrayVegeta.png

Step 4:

Invert the grayscale image. We can invert images simply by subtracting from 255, as grayscale images are 8 bit images or have a maximum of 256 tones.

inverted_image = 255-gray_image
cv2.imshow("InvertedVegeta",inverted_image)
cv.waitKey(0)

InvertedVegeta.png

Step 5:

Blur the inverted image using GaussianBlur method in OpenCV library and invert the blurred image.

blurred = cv2.GaussianBlur(inverted_image,(21,21),0)
inverted_blurred = 255-blurred
cv2.imshow("InvertedBlurredVegeta",inverted_blurred)
cv2.waitkey(0)

InvertedBlurredVegeta.png

Step 6:

Divide the grayscale values of the image by the values of image received from step-5 (Note: We inverted the grayscale image and we blurred this image and then again inverted it). Diving an image from its smoothed form will highlight the edges and we get the image like Pencil Sketch.

pencil_sketch = cv2.divide(gray_image,inverted_blurred, scale=256.0)
cv2.imshow("VegetaSketch",pencil_sketch)
cv2.waitKey(0)

VegetaSketch.png