DEV Community

A0mineTV
A0mineTV

Posted on

🚀 How to Create a Pencil Sketch Effect with OpenCV and Matplotlib

How to Create a Pencil Sketch Effect with OpenCV and Matplotlib

Have you ever wanted to transform your favorite images into pencil sketch art? In this tutorial, we'll build a Python script that processes an image step by step to create a beautiful sketch effect. We'll leverage the power of OpenCV for image manipulation and Matplotlib for visualization.

What You’ll Learn

  1. How to read, process, and save images using OpenCV.
  2. How to visualize image transformations with Matplotlib.
  3. How to create a pencil sketch effect through a combination of image processing techniques.

Let’s dive in!


Prerequisites

Before we start, make sure you have Python installed along with the required libraries:

  • OpenCV (cv2)
  • Matplotlib

You can install these libraries using pip:

pip install opencv-python matplotlib
Enter fullscreen mode Exit fullscreen mode

The Code

Here’s the complete code for the pencil sketch transformation:

import cv2
import matplotlib.pyplot as plt

plt.style.use('ggplot')


def load_and_convert_image(filepath):
    """Load an image and convert it to RGB."""
    img = cv2.imread(filepath)
    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


def display_image(image, title, cmap=None):
    """Display an image with a title and optional colormap."""
    plt.figure(figsize=(8, 8))
    plt.imshow(image, cmap=cmap)
    plt.axis("off")
    plt.title(title)


def save_image(image, output_path):
    """Save an image to the specified file path."""
    cv2.imwrite(output_path, image)


def process_image(filepath, output_path):
    """Process the image to create a sketch effect."""
    # Load and convert the image
    img_rgb = load_and_convert_image(filepath)
    display_image(img_rgb, "Original Image")

    # Convert to grayscale
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
    display_image(img_gray, "GrayScale Image", cmap="gray")

    # Invert the grayscale image
    img_invert = cv2.bitwise_not(img_gray)
    display_image(img_invert, "Inverted Image", cmap="gray")

    # Apply Gaussian blur to the inverted image
    img_smoothing = cv2.GaussianBlur(img_invert, (21, 21), sigmaX=0, sigmaY=0)
    display_image(img_smoothing, "Smoothened Image", cmap="gray")

    # Create the final sketch effect
    final_sketch = cv2.divide(img_gray, 255 - img_smoothing, scale=255)
    display_image(final_sketch, "Final Sketch Image", cmap="gray")

    # Save the final sketch image
    save_image(final_sketch, output_path)
    print(f"Final sketch saved to {output_path}")


def main():
    """Main function to process the image."""
    filepath = 'test.jpeg'  # Replace with your image path
    process_image(filepath, "test_coloring.jpeg")
    plt.show()


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

How It Works

1. Loading and Converting the Image

The load_and_convert_image function reads the image from a file path using OpenCV (cv2.imread) and converts it from BGR to RGB. This conversion is necessary because OpenCV loads images in BGR format, whereas Matplotlib expects RGB.


2. Displaying Images

The display_image function leverages Matplotlib to display images at various stages of the transformation. It includes optional support for colormaps (e.g., grayscale).


3. Converting to Grayscale

We use OpenCV’s cv2.cvtColor to transform the RGB image into a grayscale image. This is the first step in achieving the sketch effect.


4. Inverting the Grayscale Image

The cv2.bitwise_not function inverts the grayscale image, essentially flipping all pixel values.


5. Smoothing the Image

Gaussian blur is applied using cv2.GaussianBlur to create a smooth, blurred version of the inverted image. This step is crucial for achieving the pencil sketch effect.


6. Creating the Sketch

The sketch is created by dividing the grayscale image by the complement of the blurred image (255 - img_smoothing). The division scales the pixel values to produce a pencil-like effect.


7. Saving the Result

The final image is saved to disk using OpenCV’s cv2.imwrite.


Example Usage

To use the script, follow these steps:

  • Replace the placeholder filepath and output_path in the main function with the path to your input image and the desired output file name, respectively. For example:
filepath = 'path/to/your/input_image.jpg'
output_path = 'path/to/your/output_sketch.jpg'
Enter fullscreen mode Exit fullscreen mode
  • Run the script using Python:
python main.py
Enter fullscreen mode Exit fullscreen mode

The script will:

  • Load the original image.

  • Process it step by step, creating a pencil sketch effect.

  • Display intermediate steps (original, grayscale, inverted,
    blurred, and final sketch) using Matplotlib.

  • Save the final sketch to the specified output path.

Once completed, you’ll see the saved sketch image in the output directory.


Output Example

Final Sketch Output

Sketch Output
Sketch Output


Conclusion

In this project, we used Python to create a pencil sketch effect by combining OpenCV and Matplotlib. This is just the beginning—feel free to adapt and enhance the code for your needs.

Top comments (0)