DEV Community

A0mineTV
A0mineTV

Posted on

Transform Images into Stunning Pencil Sketches with Python and OpenCV πŸŽ¨πŸ–ŒοΈ

Have you ever wondered how to transform your photos into beautiful pencil sketches? With Python and the powerful OpenCV library, you can create a script that achieves just that. In this article, I’ll walk you through a project I recently developed that converts images into pencil sketches in just a few lines of code.

Let’s dive into the details of how it works!


πŸš€ The Goal

The main objective of this project is to take an image as input and process it step-by-step to generate a pencil sketch version of it. The output is a stunning, artistic rendering that looks as though it’s been drawn by hand.

✨ Features:

  • Simple and lightweight script.

  • Uses OpenCV, a popular image processing library.

  • Converts any image to a pencil sketch in seconds.

  • Easily extendable for batch processing or web integration.


πŸ› οΈ Tools and Technologies

To build this project, I used:

  • Python: The core programming language for this project.

  • OpenCV: A robust library for computer vision and image processing tasks.


πŸ“„ Code Breakdown

Here’s the complete code:

import cv2


def create_sketch(input_image_path, output_image_path):
    """
    Converts an image into a pencil sketch and saves the result.

    Args:
        input_image_path (str): Path to the input image file.
        output_image_path (str): Path to save the resulting sketch.
    """
    # Load the image
    image = cv2.imread(input_image_path)

    if image is None:
        raise FileNotFoundError(f"Image not found at {input_image_path}")

    # Convert the image to grayscale
    grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Invert the grayscale image
    inverted_img = cv2.bitwise_not(grey_img)

    # Apply Gaussian blur to the inverted image
    blurred_img = cv2.GaussianBlur(inverted_img, (21, 21), 0)

    # Invert the blurred image
    inverted_blurred_img = cv2.bitwise_not(blurred_img)

    # Create the pencil sketch by dividing the grayscale image by the inverted blurred image
    sketch = cv2.divide(grey_img, inverted_blurred_img, scale=256.0)

    # Save the resulting sketch
    cv2.imwrite(output_image_path, sketch)


# Example usage
create_sketch('test.jpeg', 'image_coloring.png')
Enter fullscreen mode Exit fullscreen mode

🧩 Step-by-Step Explanation

  1. Reading the Image:

    • The cv2.imread() function loads the image from the specified path.
    • If the image is not found, an error is raised to prevent further execution.
  2. Converting to Grayscale:

    • Using cv2.cvtColor(), the image is converted into grayscale for simplicity. This reduces the color channels to a single intensity channel.
  3. Inverting the Image:

    • The grayscale image is inverted using cv2.bitwise_not(). This creates a negative of the original grayscale image.
  4. Blurring:

    • A Gaussian blur is applied to the inverted image using cv2.GaussianBlur(). This smooths the image, simulating the effect of a pencil stroke.
  5. Creating the Sketch:

    • The final sketch is generated using cv2.divide(), which divides the grayscale image by the inverted blurred image, adjusting for contrast with the scale parameter.
  6. Saving the Sketch:

    • The processed sketch is saved to the specified output path with cv2.imwrite().

✨ Example Output

Here’s what the process looks like visually:

  1. Original Image:

    Original Image

  2. Pencil Sketch:

    Pencil Sketch


πŸš€ Next Steps

If you want to extend this project, here are a few ideas:

  1. Batch Processing:

    Process multiple images in a folder and save the sketches automatically.

  2. Web App:

    Build a simple Flask or Django app to upload images and download sketches.

  3. Customization:

    Allow users to tweak parameters like blur intensity or sketch contrast.

  4. Real-Time Sketching:

    Integrate a webcam feed to apply the sketch effect in real-time.

  5. Integration with Social Media:

    Automatically share the generated sketches to platforms like Instagram or Twitter.


πŸ’‘ Final Thoughts

This pencil sketch project showcases how easy it is to combine Python and OpenCV to achieve amazing results. It’s a great starting point for anyone looking to dive into computer vision or add some artistic flair to their projects.

Whether you're a beginner exploring image processing or a seasoned developer looking to create something creative, this project is a fun and rewarding challenge.

I’d love to hear your thoughts or see your own implementations! Feel free to leave a comment or share your versions below. Let’s keep creating! πŸŽ‰

Top comments (0)