In this blog post, we will explore the art of generating an ASCII representation of an image by using Python. The idea behind ASCII art is to represent images using a set of characters, symbols, and spaces, while preserving the general layout and contrast of the original image. This concept has been around since the early days of computing as a way to display images on devices with limited graphical capabilities.
For this task, we will need two essential Python libraries: Pillow
(Python Imaging Library) and numpy
.
You can install them using pip
:
pip install Pillow numpy
Let's get into our Python code to explore the conversion process.
First, import the necessary libraries:
from PIL import Image import numpy as np
Now, let's create a function that reads an image and returns its ASCII representation:
def image_to_ascii(image_path, width, chars): image = Image.open(image_path) aspect_ratio = image.width/image.height height = int(width / aspect_ratio) * 2 image = image.resize((width, height)) grayscale_image = image.convert("L") pixel_values = np.asarray(grayscale_image) return "\n".join("".join(chars[int(pixel_value/256 * len(chars))] for pixel_value in row) for row in pixel_values)
This function first reads the image, calculates the height while keeping the aspect ratio and resizes it according to the desired width. It then converts the resized image to grayscale and retrieves its pixel values as a NumPy array. Finally, it translates the pixel values into ASCII characters by using the specified list of characters as a lookup table.
You can test this function with any image file and a custom list of characters, for instance:
CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."] filePath = "sample_image.jpg" ascii_art = image_to_ascii(filePath, 80, CHARS) print(ascii_art)
This code snippet will print the ASCII representation of sample_image.jpg
using 80 characters per row and the custom list of characters in CHARS
.
With this brief tutorial, you have learned how to generate an ASCII representation of an image using Python. You can further customize the image_to_ascii
function by changing the list of characters, or adjusting the resizing and conversion settings to better suit your needs.
I hope you enjoyed this article and now have a better understanding of the process behind generating ASCII art from images! Feel free to explore and experiment further with different images and character settings.