DEV Community

A0mineTV
A0mineTV

Posted on

1

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! ๐ŸŽ‰

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Communityโ€”every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple โ€œthank youโ€ goes a long wayโ€”express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay