Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Last active February 20, 2021 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasG77/b73a1a499eefecb92c4fd1b7aacfd1b7 to your computer and use it in GitHub Desktop.
Save ThomasG77/b73a1a499eefecb92c4fd1b7aacfd1b7 to your computer and use it in GitHub Desktop.
# Code borrowed from https://py.plainenglish.io/convert-a-photo-to-pencil-sketch-using-python-in-12-lines-of-code-4346426256d4
# This code depends from OpenCV Python library you can install with
# pip install opencv-python
# You run it with the following. It relies on Python 3
# python3 generate-image-to-drawing.py /tmp/puppy.png
# or how you installed or your OS
# python generate-image-to-drawing.py /tmp/puppy.png
# It will generate an image at /tmp/puppy_sketch.png
import argparse
import cv2
import pathlib
parser = argparse.ArgumentParser(description="Generate a sketch from an image input")
parser.add_argument("path", help="provide the path to an image e.g jpg or png file. Full list at https://docs.opencv.org/master/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56")
args = parser.parse_args()
file = pathlib.Path(args.path)
if file.exists():
mypath = args.path
img = cv2.imread(mypath)
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
inverted_gray_image = 255 - gray_image
blurred_img = cv2.GaussianBlur(inverted_gray_image, (21,21),0)
inverted_blurred_img = 255 - blurred_img
pencil_sketch_IMG = cv2.divide(gray_image, inverted_blurred_img, scale = 256.0)
# Show the original image
# cv2.imshow('Original', img)
# Show the new image pencil sketch
# cv2.imshow('Pencil Sketch', pencil_sketch_IMG)
prefix = mypath[0:mypath.rfind('.')]
extension = mypath[mypath.rfind('.'):]
output_path = '{}_sketch{}'.format(prefix, extension)
cv2.imwrite(output_path, pencil_sketch_IMG)
print("You successfully created a sketch image at {}".format(output_path))
# Display the window infinitely until any keypress
# cv2.waitKey(0)
# cv2.destroyAllWindows()
else:
print("You must provide a valid path to an image file")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment