Skip to content

Instantly share code, notes, and snippets.

@dzogrim
Created November 16, 2024 17:12
Show Gist options
  • Save dzogrim/623b1f104f1d3e874d3a0cfe25cd4d6c to your computer and use it in GitHub Desktop.
Save dzogrim/623b1f104f1d3e874d3a0cfe25cd4d6c to your computer and use it in GitHub Desktop.
This script converts an image into a pencil sketch using OpenCV.
#!/usr/bin/env python3.11
# -*- coding: utf-8 -*-
"""
Image to Pencil Sketch Converter
================================
This script converts an image into a pencil sketch using OpenCV.
It accepts the image file path as a command-line argument, processes the image,
and saves the pencil sketch as an output file.
Usage:
python3.11 sketch.py <image_path>
Requirements:
- Python 3.11
- OpenCV library (install using `pip3.11 install opencv-python` or `sudo port install py311-opencv4`)
Author: Dzogrim
Date: 2024-11-16
"""
import cv2
import sys
def image_to_pencil_sketch(image_path, output_path="sketch_image.png"):
"""
Converts an image to a pencil sketch and saves the output.
Parameters:
image_path (str): Path to the input image file.
output_path (str): Path to save the output pencil sketch image. Default is 'sketch_image.png'.
Returns:
None
"""
# Read the input image
image = cv2.imread(image_path)
if image is None:
print("Error: Unable to read the image. Please check the file path.")
sys.exit(1)
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Invert the grayscale image
inverted = 255 - gray_image
# Apply Gaussian blur to the inverted image
blur = cv2.GaussianBlur(inverted, (21, 21), 0)
# Invert the blurred image
inverted_blur = 255 - blur
# Combine the grayscale and inverted blurred images to create a sketch
sketch = cv2.divide(gray_image, inverted_blur, scale=256.0)
# Save the pencil sketch image to the specified output path
cv2.imwrite(output_path, sketch)
print(f"Pencil sketch saved to: {output_path}")
# Display the pencil sketch
cv2.imshow("Pencil Sketch", sketch)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
# Ensure the script is called with the correct number of arguments
if len(sys.argv) != 2:
print("Usage: python sketch.py <image_path>")
sys.exit(1)
# Extract the image path from the command-line arguments
image_path = sys.argv[1]
# Call the function to process the image
image_to_pencil_sketch(image_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment