Logo

dev-resources.site

for different kinds of informations.

Transforming Images into ASCII Art with Python and OpenCV

Published at
2/2/2024
Categories
python
opencv
ascii
programming
Author
devasservice
Categories
4 categories in total
python
open
opencv
open
ascii
open
programming
open
Author
12 person written this
devasservice
open
Transforming Images into ASCII Art with Python and OpenCV

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


Enter fullscreen mode Exit fullscreen mode

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)



Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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!

opencv Article's
30 articles in total
Favicon
Update
Favicon
Building OpenCV 4.10.0 with GUI Support in WSL
Favicon
Transform Your Images into Pencil Sketches with Python 🚀
Favicon
Making a simple pointillism painting using OpenCv.
Favicon
Transform Any Image into a Sketch with Python 🚀
Favicon
A Visual Guide to Affine Transformations: Translation, Scaling, Rotation, and Shear
Favicon
Transform Images into Stunning Pencil Sketches with Python and OpenCV 🎨🖌️
Favicon
🚀 How to Create a Pencil Sketch Effect with OpenCV and Matplotlib
Favicon
Integrating OpenCV with Visual Studio C++
Favicon
Fixing libdc1394.so.22: cannot open shared object file (ㅠ﹏ㅠ)
Favicon
Wave Goodbye to the Mouse: Transforming Hand Gestures into Your New Click Commanders!
Favicon
Blurry Image Detection in Laravel
Favicon
Introduction To Computer Vision with Python (Part 1)
Favicon
Building a Desktop C++ Barcode Scanner with Slimmed-Down OpenCV and Webcam
Favicon
Efficient Driver's License Recognition with OCR API: Step-by-Step Tutorial
Favicon
Binary Images & Image Thresholding
Favicon
Introduction to OpenCV: The Ultimate Guide for Beginners
Favicon
Creating a Face Swapping Application with Python and OpenCV
Favicon
Complete Guide for Install OpenCV using Anaconda
Favicon
Step-by-Step Guide To Install OpenCV For Python
Favicon
Highlighting Image Text
Favicon
OPEN CV & DEEP LEARNING ในการตรวจจับโรคผิวหนัง และคัดกรองโดย model Xception
Favicon
Giving Odin Vision
Favicon
Extracting Words from Scanned Books: A Step-by-Step Tutorial with Python and OpenCV
Favicon
Transforming Images into ASCII Art with Python and OpenCV
Favicon
Face Detection Made Easy with OpenCV and Python
Favicon
Building an Application for Facial Recognition Using Python, OpenCV, Transformers and Qdrant
Favicon
Add Text to your certificate image in seconds with Django and OpenCV
Favicon
OpenCV Python cv2 has no attribute TERM_CRITERIA_EPS
Favicon
Anthropometric Measurements using AI/ML

Featured ones: