Nanfeng

Notes on software development, code, and curious ideas

Turning a Color Photo into a Pencil Sketch with Python

A common pencil-sketch effect combines a grayscale image with a blurred inversion using color-dodge blending. Pillow and NumPy make the calculation concise and avoid slow per-pixel Python loops.

Install the dependencies:

1
python -m pip install pillow numpy

Then save this script as sketch.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from pathlib import Path
import numpy as np
from PIL import Image, ImageFilter, ImageOps

source = Path("input.jpg")
target = Path("sketch.png")

with Image.open(source) as image:
gray = ImageOps.grayscale(image)
inverted = ImageOps.invert(gray)
blurred = inverted.filter(ImageFilter.GaussianBlur(radius=12))

base = np.asarray(gray, dtype=np.float32)
blend = np.asarray(blurred, dtype=np.float32)

# Color dodge: base * 255 / (255 - blend)
denominator = np.maximum(255.0 - blend, 1.0)
result = np.clip(base * 255.0 / denominator, 0, 255).astype(np.uint8)

Image.fromarray(result, mode="L").save(target)
print(f"saved {target}")

Place input.jpg beside the script and run python sketch.py. Increase the blur radius for broader, softer shading; decrease it to retain finer edges. High-resolution images consume more memory, so resize a copy before processing if the source is very large.

The result depends heavily on exposure and local contrast. A small contrast adjustment after blending can help pale images, but avoid crushing all light gray detail into pure white.

+