Image to Sketch using Python

In this Post, We will see how to convert image to sketch using python with open-cv in just few lines of code.

An image in Python is simply a two-dimensional array of integers. So, using several Python tools, one can perform a few matrix operations to produce some quite intriguing effects. To convert a regular image to a sketch, we’ll change its original RGB values and assign them to RGB values that are similar to grey, resulting in a sketch of the input image.

Insatallation

Step 1 is to install cv2 using pip command.

pip install cv2
#if cv2 doesn't work for you, try this one
pip install opencv-python

Then we will import cv2 inside our code, after that, we will use some of the following functions: 

1. imread()- This function will load the image i.e in the specified folder. 

2. cvtColor()- This function takes color as an argument and then changes the source image color into that color.

3. bitwise_not()- This function will help the image to keep the properties as same by providing the masking to it.

4. GaussianBlur()- This function is used to modify the image by sharpening the edges of the image, smoothen the image, and will minimize the blurring property.

5. divide()- This function is used for the normalization of the image as it doesn’t lose its previous properties.

Finally will save the image using imwrite() function.

Code

Here is the Code using above mentioned functions

Image to Sketch using Python
import cv2
image = cv2.imread('cat.png')
grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey_img)
blur = cv2.GaussianBlur(invert, (21, 21), 0)
invertedblur = cv2.bitwise_not(blur)
sketch = cv2.divide(grey_img, invertedblur, scale=256.0)
cv2.imwrite("catsketch.png", sketch)  

so that was all about converting image to sketch using python with cv2.

Thank you. If you have any questions, drop them in comments.

You can check my other Python Articles from Here : Python Archives – Code Seekers (code-seekers.com)

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *