Creating a Pencil Sketch from an Image Using OpenCV in Python
This tutorial walks through installing OpenCV, selecting an image, converting it to grayscale, inverting it, applying Gaussian blur, and finally combining the results to generate a pencil‑sketch effect, with complete Python code and display commands.
First, install the OpenCV library for Python using the command: pip install opencv-python Choose any image you want to transform into a pencil sketch; the example uses a photo named "dog.jpg".
Read the image in BGR format and convert it to a grayscale image:
import cv2
# Read image
image = cv2.imread("dog.jpg")
# Convert BGR to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)Invert the grayscale image to create a negative, which helps enhance details:
# Image inversion
inverted_image = 255 - gray_imageCreate the pencil sketch by blurring the inverted image, inverting the blurred result, and dividing the original grayscale image by this inverted blur:
blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
inverted_blurred = 255 - blurred
pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)Display the original image and the generated pencil sketch:
cv2.imshow("原图", image)
cv2.imshow("铅笔素描", pencil_sketch)
cv2.waitKey(0)Resulting images are shown below:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
