Convert Image into a Pencil Sketch in Python
In this tutorial, we will use computer vision to convert an image into a pencil sketch with the help of the Python OpenCV library. We will use the OpenCVPython library to convert the image to a pencil sketch.
Python program for converting image into a pencil sketch
1. First import the required libraries.
from google.colab.patches import cv2_imshow import cv2
2. Read the picture you want to convert into a pencil sketch.
3. Use the cvtColor function of cv2 to convert the image to grayscale. Converting the image to grayscale provides us with black and white pixels in the image, which will be used to convert the pencil sketch.
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
4. We are using the bitwise_not function, to brighten the lighter areas and vice versa, so that we can find the edges to make a pencil sketch.
image_invert = cv2.bitwise_not(image_gray)
5. We will Gaussian Blur to smooth the image. It helps to reduce noise in the image.
image_smoothing = cv2.GaussianBlur(image_invert, (21, 21),sigmaX=0, sigmaY=0)
6. The final_sketch function divides the grayscale value of the image by the reciprocal of the unsharpness value to make the edges of the image thicker.
7. Finally, use final_sketch to get the pencil sketch.
def final_sketch(x, y): return cv2.divide(x, 255 - y, scale=256) final_image = final_sketch(image_gray, image_smoothing) cv2_imshow(final_image)