In the vast and ever-expanding universe of coding projects, there's a special place for those who blend art and technology. One such project is the creation of ASCII art from digital images—a process that turns ordinary pictures into a mosaic of characters from the ASCII standard. It's a fascinating way to explore computer vision and Python programming. Today, I'm excited to share a simple yet powerful way to transform any image into ASCII art using Python and OpenCV.


What is ASCII Art?

ASCII art is a graphic design technique that uses printable characters from the ASCII standard to create visual art. It's been around since the early days of computers, serving as a way to make graphical representations in environments that support only text. From simple smileys like :-) to intricate portraits, ASCII art showcases the creativity possible with just a limited set of characters.


Why Use Python and OpenCV?

Python is renowned for its simplicity and readability, making it an ideal language for beginners and professionals alike. When combined with OpenCV, an open-source computer vision and machine learning software library, Python becomes an incredibly powerful tool for image processing tasks.

OpenCV simplifies complex image processing tasks, such as reading and resizing images, and converting them into grayscale—essential steps for generating ASCII art.


How to Create ASCII Art from Images

The process involves loading an image, converting it to grayscale to simplify the intensity information, resizing it to fit the output medium (like a console or text file), and then mapping each pixel's intensity to a specific ASCII character. The result is a text representation of the original image, viewable in any text editor or console.

Step-by-Step Guide

Install OpenCV: Ensure you have Python and OpenCV installed. OpenCV can be easily installed using pip:

pip install opencv-python

Load and Process the Image: The script reads an image file, converts it to grayscale, and resizes it. This prepares the image for conversion to ASCII.

Convert Pixels to ASCII: By mapping the intensity of each pixel to a character from a predefined set, the script translates the image into ASCII art. Characters are chosen based on their perceived visual weight, with darker characters representing darker areas of the image.

Output the ASCII Art: Finally, the script prints the ASCII art to the console or saves it to a file.

The Python Script


import cv2


def load_image(image_path):
    # Load an image in grayscale
    return cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)


def resize_image(image, new_width=100):
    # Compute the ratio of the new width to the old width, and adjust height accordingly
    ratio = new_width / image.shape[1]
    new_height = int(image.shape[0] * ratio)
    return cv2.resize(image, (new_width, new_height))


def pixel_to_ascii(image):
    # Map grayscale values to ASCII characters
    ascii_chars = "@%#*+=-:. "
    new_image = []
    for row in image:
        new_image.append(''.join([ascii_chars[pixel//32] for pixel in row]))
    return "\n".join(new_image)


if __name__ == "__main__":
    image_path_ = input("Enter the path to the image file: ")
    image_ = load_image(image_path_)
    if image_ is None:
        print("Error loading image.")
    else:
        image_ = resize_image(image_)
        ascii_art = pixel_to_ascii(image_)
        print(ascii_art)

You can save the script on a file called main.py. Now, let's test the script with this source image:

A landscape image

Now we run the script with:

python main.py

And we get the beautiful ASCII art:

Sample of the ASCII art generation

Conclusion

Creating ASCII art from images is a delightful project that marries the precision of programming with the nuance of visual art. It's a testament to the versatility of Python and the power of OpenCV. Whether you're a seasoned developer looking for a creative outlet or a beginner eager to explore the possibilities of coding, this project offers a unique blend of challenge and creativity.

Dive into the code, experiment with different images, and see what kind of ASCII art you can create. The possibilities are as boundless as your imagination. Happy coding!


Thank you for reading and I will see you on the Internet.

This post is public so feel free to share it.

If you like my free articles and would want to support my work, consider buying me a coffee:


Are you working on a project that’s encountering obstacles, or are you envisioning the next groundbreaking web application?

If Python, Django, and AI are the tools you're exploring but you need more in-depth knowledge, you're in the right place!

Get in touch for a 1-hour consultation where I can address your specific challenges.

Developer Service Blog - 1 Hour Consulting - Nuno Bispo
Are you working on a project that’s hitting roadblocks or simply dreaming up the next big web application?

Tagged in: