DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at elbruno.com on

6 1

#OpenCV – How to add a Pencil Sketch effect to an image 🖼️ using Python 🐍

Hi !

Super quick post today with a cool scenario to support my TikTok videos in Spanish (I know 😀):

How to add a pencil sketch effect to an image using python and opencv

Here is the output with an original photo from my office and a new image with the pencil sketch effect:

add pencil sketch effect to an image

Sample code:

# Copyright (c) 2022
# Author : Bruno Capuano
# Create Time : 2022 Feb
# Change Log :
# - Open a local image
# - Apply a pencil sketch effect to the image
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import cv2
# open an image using opencv
imgOriginal = cv2.imread('Office2.jpg')
img = cv2.resize(imgOriginal, (324, 720))
cv2.imshow('@ElBruno - Office', img)
# get image height and width
height, width, channels = img.shape
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_blur = cv2.GaussianBlur(img_gray, (21, 21), 0, 0)
img_blend = cv2.divide(img_gray, img_blur, scale=256)
cv2.imshow('@ElBruno - Pencil Sketch', img_blend)
# save image using opencv
cv2.imwrite('OfficePencilSketch.jpg', img)
# key controller
cv2.waitKey(0)
cv2.destroyAllWindows()

Happy coding!

Greetings

El Bruno


OpenCV and Python

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay