Hola! 🙂 Do you love sketches? Let’s be honest, who doesn’t love sketches? 😛 Everyone does and now you can convert any image to sketch in seconds.

In today’s blog I’ll guide you how to build your own tool to covert images to sketch. So, by the end of the tutorial you’ll be able to get the following results.

Overview

To achieve the above results, we will first convert the image into grayscale and then we’ll blur the background. Lastly, we’ll add the black and white foreground to the blurred background.

To separate the background we will be inverting the image and then we’ll blur it.

To blend the foreground and background in, we have used a special function ‘dodge’.

Don’t Stop! Continue reading to get into the code and understand the technique.

Importing libraries

We’ll be using

  • Cv2 for basic image processing
  • Numpy for mathematical processing
import cv2
import numpy as np

Loading and processing the image

After importing libraries, we’ll load the required image

img= cv2.imread('pic4.jpeg', -1)
cv2.imshow('before',img)

Now, we’ll convert the image to grayscale.

grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

In the next step, we’ll first obtain the negative of image by inverting it and then we’ll blur the inverted image.

inverted= 255-grayscale
blurred= cv2.blur(inverted,(15,15)) 

Next, we’ll define a function dodge() that combines the foreground and background by normalizing around 255 and subtracting background pixels.

The Colour Dodge blend mode divides the bottom layer by the inverted top layer. This lightens the bottom layer depending on the value of the top layer. We have the blurred image, which highlights the boldest edges.

def dodge(front,back): 
    result=front*255/(255-back)  
    result[result>255]=255 
    result[back==255]=255 
    return result.astype('uint8')

In the next step, we’ll call dodge() function by passing the background and foreground images as grayscale and blurred images in arguments. Before calling the function, we’ll convert the images as float type to ease the mathematical part. In the end, we’ll preview the final image.

blurred= blurred.astype('float')
grayscale= grayscale.astype('float')
final_img= dodge(blurred, grayscale)

cv2.imshow('chris',final_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Conclusion

Finally, we are able to convert the image into a cool sketch. I hope you enjoyed the article.

If you liked this blog feel free to share it.

-Suniti Jain


0 Comments

Leave a Reply

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

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert