In this tutorial, we will be looking at how to convert a photo to sketch using Python. To do this we will use OpenCV library as our image manipulation library.
To begin run the command below on your terminal to install opencv.
pip install opencv-python
After installing OpenCV , create a folder called sketch and create a file called main.py . Insert the photo you want to convert into the folder.
Now let’s code our program, inside the main.py import opencv as shown below.
import cv2
Now let’s load our image.
img = cv2.imread('sample.jpg')
Next convert the loaded image into a gray scale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Invert the grayscale image to create a negative image.
inverted_gray_img = 255 - gray_img
Here we will apply a gaussian blur to the inverted grayscale image
blurred_img = cv2.GaussianBlur(inverted_gray_img, (21, 21), 0)
Now let’s blend the inverted image and the blurred image.
def dodgeV2(image, mask):
return cv2.divide(image, 255-mask, scale=256)
sketch_img = dodgeV2(gray_img, blurred_img)
cv2.imshow('Original Image', img)
cv2.imshow('Pencil Sketch', sketch_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Now run the code as shown below.
python3 main.py
After running the command above, here is our sketch image.
Here is the whole code.
import cv2
img = cv2.imread('sample.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
inverted_gray_img = 255 - gray_img
blurred_img = cv2.GaussianBlur(inverted_gray_img, (21, 21), 0)
def dodgeV2(image, mask):
return cv2.divide(image, 255-mask, scale=256)
sketch_img = dodgeV2(gray_img, blurred_img
cv2.imshow('Original Image', img)
cv2.imshow('Pencil Sketch', sketch_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
There you have it, thanks for reading. Happy Coding