DEV Community

A0mineTV
A0mineTV

Posted on

Transform Any Image into a Sketch with Python πŸš€

Have you ever wanted to turn your favorite photos into beautiful sketches? In this tutorial, we'll explore how to achieve that with Python and a few handy libraries. The following code allows you to convert an image into a sketch using grayscale transformation, Gaussian blur, and the dodge effect.


Prerequisites

To follow along, ensure you have Python installed along with these libraries:

pip install numpy imageio scipy opencv-python
Enter fullscreen mode Exit fullscreen mode

Β The Code

Here is the Python code that transforms your image into a sketch:

import numpy as np
import imageio.v2 as imageio  # Using v2 to avoid warnings
import scipy.ndimage
import cv2


def rgb_to_gray(rgb_image):
    """
    Converts an RGB image to grayscale.
    """
    return np.dot(rgb_image[..., :3], [0.2989, 0.5870, 0.1140])


def dodge(front, back):
    """
    Applies the "dodge" effect to create a sketch-like appearance.
    """
    result = front * 255 / (255 - back)
    result[result > 255] = 255
    result[back == 255] = 255
    return result.astype('uint8')


def create_sketch(input_image_path, output_image_path, blur_sigma=13):
    """
    Converts an image into a sketch and saves it.

    Args:
        input_image_path (str): Path to the input image.
        output_image_path (str): Path to save the output sketch image.
        blur_sigma (int, optional): Gaussian blur intensity. Default is 13.
    """
    # Load the image
    image = imageio.imread(input_image_path)

    # Convert to grayscale
    gray_image = rgb_to_gray(image)

    # Invert the colors
    inverted_image = 255 - gray_image

    # Apply Gaussian blur
    blurred_image = scipy.ndimage.gaussian_filter(inverted_image, sigma=blur_sigma)

    # Create the sketch using the dodge effect
    sketch = dodge(blurred_image, gray_image)

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


if __name__ == '__main__':
    # Parameters for execution
    input_image = 'test.jpeg'
    output_image = 'test_coloring.png'

    # Generate the sketch
    create_sketch(input_image, output_image)
Enter fullscreen mode Exit fullscreen mode

How It Works

The script transforms an image into a sketch using the following steps:

  1. Grayscale Conversion

    • The rgb_to_gray function converts an RGB image into a grayscale image. This is done by applying a weighted sum of the red, green, and blue channels: [ \text{Gray} = 0.2989 \times \text{Red} + 0.5870 \times \text{Green} + 0.1140 \times \text{Blue} ]
    • This formula accounts for the human eye's sensitivity to different colors, ensuring an accurate grayscale representation.
  2. Inverting Colors

    • The colors of the grayscale image are inverted to create a "negative" of the image: [ \text{Inverted} = 255 - \text{Gray} ]
    • This inversion is crucial for the dodge effect applied later.
  3. Blurring the Image

    • A Gaussian blur is applied to the inverted image using the scipy.ndimage.gaussian_filter function. The blur_sigma parameter controls the intensity of the blur.
    • The blur softens the details in the image, making the sketch effect more pronounced.
  4. Applying the Dodge Effect

    • The dodge function combines the blurred inverted image and the original grayscale image to simulate a sketch: [ \text{Sketch}[i, j] = \frac{\text{Blurred}[i, j] \times 255}{255 - \text{Gray}[i, j]} ]
    • This technique brightens the darker areas of the grayscale image based on the blurred inverted image.
    • Pixels are clamped to a maximum value of 255 to avoid overflows, ensuring the output remains visually consistent.
  5. Saving the Result

    • The final sketch image is saved using the cv2.imwrite function. The output path is specified as a parameter to the create_sketch function.

By combining these steps, the script generates a visually appealing sketch of the original image, mimicking hand-drawn pencil art.


Example Usage

Place an image named test.jpeg in the same directory as your script and run it. The output will be saved as test_coloring.png.
You can adjust the blur_sigma parameter to control the intensity of the sketch effect. For example:

create_sketch('test.jpeg', 'output_sketch.png', blur_sigma=20)
Enter fullscreen mode Exit fullscreen mode

Possible Enhancements

  • Error Handling: Ensure the input file exists and is an image.

  • Command-Line Arguments: Use argparse to allow dynamic input for file paths and parameters.

  • User Interface: Build a simple GUI using libraries like tkinter for easier interaction.


Output Example

After running the script, you should get a sketch version of your input image. Below is an example of what the output might look like:

Original Image Sketch Output
Original Image Sketch Output

Customizing the Results

  • Sharp Sketch: Reduce the blur_sigma value (e.g., blur_sigma=5) for sharper and more detailed sketches.
  • Softer Sketch: Increase the blur_sigma value (e.g., blur_sigma=20) for a smoother, more artistic effect.

Try experimenting with your own images to see how the effect varies. The results can range from highly detailed to soft and dreamy sketches depending on the input and parameters.


Β Conclusion

This script is a great example of leveraging Python's ecosystem to create stunning visual effects with minimal effort. Experiment with different images and parameters to see what works best for you.

Top comments (1)

Collapse
 
codewanderer profile image
Code Wanderer

Thanks. Gerat.