Yuvaraj Vodiboina
All work
(14)Case studyPython, image processing

Pencil Sketch

A photo turned into a pencil sketch in four steps of image processing, with OpenCV. The same four steps run here, on my photo.

Platform
Python, image processing
When
2021
Role
Sole developer
Status
Earlier work, on GitHub
My photo, and the same photo as a pencil sketch, made by the four steps below

Drag across itSlide across it to compare. The sketch is worked out in your browser.

(01)

The problem

Make a recognisable pencil-sketch effect with a short image-processing pipeline that you can explain step by step.

(02)

What I built

The script reads a photo, converts it to grayscale and inverts it, then blurs the inverted image with a 21 by 21 Gaussian kernel. It inverts the blur again and divides the grayscale image by it, scaled by 256. Where the photo is flat the two match and it goes white; at edges they don’t, and dark lines are left, like pencil.

The panel at the top runs the same steps on my photo, in your browser, with the same kernel and the same division.

Hard partA convincing sketch from a pipeline short enough to explain in one breath.

(03)

Under the hood

  1. 01ImageRead with OpenCV
  2. 02GrayscaleColour out, light kept
  3. 03Invert and blurA 21 by 21 Gaussian
  4. 04DivideThe sketch
sketcher.py
import cv2
#reading image
image = cv2.imread("dog.jpg")

#converting image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#image inversion
inverted_image = 255 - gray_image
blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
inverted_blurred = 255 - blurred
pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)
(04)

Decisions

  1. 01

    A division blend

    Dividing the grayscale image by the inverted blur turns flat areas white and keeps the edges, in one line.

    Trade-offThe blur size is fixed, so it suits some photos better than others.

(05)

What I learned

  • The script has a fixed file name and blur size, and needs a desktop to show its windows. Fine for an experiment; a tool would need more.
(06)

Built with

PythonOpenCV

Next15 of 16Python game Flappy Bird The flap-and-dodge game, written in Python with Pygame: gravity, pipes, collisions, sprites and sound.Read the case study