Generate Pencil Sketch from Photo in Python | by Abhijith Chandradas | Towards Data Science

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.
import cv2import matplotlib.pyplot as plt
The following command can be used to read image using OpenCV.
img=cv2.imread("photo.jpg")
This command reads the file photo.jpg located in the current folder and stores in memory as img.
Displaying image using OpenCV is not very straight forward. The following command can be used to display the photo.
cv2.imshow(‘original image’,img)cv2.waitKey(0)cv2.destroyAllWindows()
When this command is executed, the below photo will open in a new window with title as ‘original image.’
It is not very convenient when new window opens up every time image has to be displayed and also the new window has to be deleted for further execution of code.To avoid these hassles, we can use pyplot module of matplotlib library to display the image in the Jupyter notebook itself.
The following command can be used to display cv2 image using matplotlib.
plt.imshow(img)plt.axis(False)plt.show()
We can observe that the image displayed using matplotlib is not consistent with the original image. This is because OpenCV uses BGR color scheme whereas matplotlib uses RGB colors scheme.We can convert BGR image to RGB by using any of the following methods.
plt.imshow(img[:,:,::-1])plt.axis(False)plt.show()
Using cvtColor method of OpenCV.
RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(RGB_img)plt.axis(False)plt.show()
Converting a photo to pencil sketch involves the following steps:
Using cvtColor function of OpenCV.
grey_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Inverting the image can be done by either of the following methods
invert_img=cv2.bitwise_not(grey_img)#invert_img=255-grey_img
Apply Gaussian blur to the image. The second argument to the function is the kernel size, if should be a pair of odd numbers.Larger the kernel size, more blurred the image will be and it will lose its subtle features. For creating sketch, we require only the prominent features (contrasting edges) from the image. For small images, kernel size of (3,3), (5,5) etc. will be sufficient, whereas for larger images, small kernel size do not create any impact. Appropriate kernel size can be selected by trial and error method.
blur_img=cv2.GaussianBlur(invert_img, (111,111),0)
Repeat step 2
invblur_img=cv2.bitwise_not(blur_img)#invblur_img=255-blur_img
The sketch can be obtained by performing bit-wise division between the grayscale image and the inverted-blurred image.
sketch_img=cv2.divide(grey_img,invblur_img, scale=256.0)
Explaining bit-wise division in detail is beyond the scope of this article. You can access more information on image arithmetic here .
 cv2.imwrite(‘sketch.png’, sketch_img)
cv2.imshow(‘sketch image’,sketch_img)cv2.waitKey(0)cv2.destroyAllWindows()
We can display the original image and sketch side by side for comparison.
plt.figure(figsize=(14,8))plt.subplot(1,2,1)plt.title('Original image', size=18)plt.imshow(RGB_img)plt.axis('off')plt.subplot(1,2,2)plt.title('Sketch', size=18)rgb_sketch=cv2.cvtColor(sketch_img, cv2.COLOR_BGR2RGB)plt.imshow(rgb_sketch)plt.axis('off')plt.show()
We can put everything together to create a sketch function:
Code for this tutorial can be accessed from my GitHub Repo.
If you prefer content in video format, you can check out this YouTube tutorial.
I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.