Adventures in Machine Learning

Transform Images into Stunning ASCII Art with Python

Converting Images to ASCII Art Using Python

If you’re familiar with ASCII art, you know it’s an art form that uses letters, numbers, and symbols to create images. ASCII art is commonly found in email signatures, online forums, and chat rooms.

But have you ever wanted to create your own ASCII art? In this article, we’ll go over how to convert images to ASCII art using Python.

Loading an Image

To get started, we need to load an image. Python has numerous libraries that can load images, but for this project, we’ll be using the Python Imaging Library (PIL).

To load an image, we will need to import the PIL library and use the Image class. Here’s what the code would look like:

from PIL import Image
try:
    image = Image.open("image.jpg")
except:
    print("Unable to load image")

In the code above, we’re using a try-except block to handle any exceptions that might occur when opening the image. If the image doesn’t exist or can’t be opened, the program will print out an error message.

Resizing the Image

Next, we need to resize the image to scale it down to a smaller size. The reason for this is that ASCII art looks better when viewed from a distance.

If we use a high-resolution image as the source, the resulting art will be too large to view correctly. Here’s an example code that resizes an image:

MAX_SIZE = (100, 100)
def resize_image(image):
    size = image.size
    ratio = min(MAX_SIZE[0] / size[0], MAX_SIZE[1] / size[1])
    new_size = tuple([int(x * ratio) for x in size])
    return image.resize(new_size)
image = resize_image(image)

In the code above, we’ve defined a maximum size (100×100 pixels) and a function that resizes the image to fit within that size while maintaining the aspect ratio.

Converting Image to Grayscale

The next step is to convert the image to grayscale. Grayscale images have a single channel, which represents the brightness of each pixel.

We’ll use the convert() function of the Image class to convert the image. Here’s the code:

GRAYSCALE_MODE = "L"
def to_grayscale(image):
    return image.convert(GRAYSCALE_MODE)
image = to_grayscale(image)

The code above defines a grayscale mode (“L”) and a function that converts the image to grayscale using the convert() function.

Creating an ASCII Character List

Next, we need to create a list of ASCII characters, from darkest to lightest. The darker the character, the more pixels it will represent in the image.

Here’s an example code that creates an ASCII character list:

ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def pixel_to_ascii(pixel_value):
    NUM_CHARS = len(ASCII_CHARS)
    return ASCII_CHARS[int(pixel_value / (256 / NUM_CHARS))]

In the code above, we’ve defined a list of ASCII characters and a function that maps each pixel to the corresponding ASCII character based on its brightness value.

Converting to ASCII Art

Finally, we’re ready to convert the image to ASCII art. Here’s the code that does the job:

def image_to_ascii(image, ascii_chars):
    pixels = image.getdata()
    ascii_art = ""
    for pixel in pixels:
        ascii_art += pixel_to_ascii(pixel)
    return ascii_art
ascii_art = image_to_ascii(image, ASCII_CHARS)
with open("ascii_art.txt", "w") as f:
    f.write(ascii_art)

The code above uses the getdata() function of the Image class to get the pixel values and loop over them.

For each pixel, it maps its value to the corresponding ASCII character using the pixel_to_ascii() function and appends the character to the resulting text. Once we have the ASCII art text, we can save it to a file using the open() function with the “w” (write) mode.

Implementation of the Conversion process

Now that we’ve covered all the steps, here’s the complete Python code that converts an image to ASCII art:

from PIL import Image
MAX_SIZE = (100, 100)
GRAYSCALE_MODE = "L"
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def resize_image(image):
    size = image.size
    ratio = min(MAX_SIZE[0] / size[0], MAX_SIZE[1] / size[1])
    new_size = tuple([int(x * ratio) for x in size])
    return image.resize(new_size)
def to_grayscale(image):
    return image.convert(GRAYSCALE_MODE)
def pixel_to_ascii(pixel_value):
    NUM_CHARS = len(ASCII_CHARS)
    return ASCII_CHARS[int(pixel_value / (256 / NUM_CHARS))]
def image_to_ascii(image, ascii_chars):
    pixels = image.getdata()
    ascii_art = ""
    for pixel in pixels:
        ascii_art += pixel_to_ascii(pixel)
    return ascii_art
try:
    image = Image.open("image.jpg")
except:
    print("Unable to load image")
image = resize_image(image)
image = to_grayscale(image)
ascii_art = image_to_ascii(image, ASCII_CHARS)
with open("ascii_art.txt", "w") as f:
    f.write(ascii_art)

Conclusion

In this article, we’ve gone over how to convert images to ASCII art using Python. We’ve covered all the essential steps, including loading an image, resizing it, converting it to grayscale, creating an ASCII character list, and finally converting it to ASCII art.

By following these steps, you can create your own ASCII art from any image you like!

Trying Different Characters

Now that you know the basics of how to convert images to ASCII art using Python, it’s time to explore and experiment with different ASCII characters to create unique and exciting results. The ASCII character list we used in the previous section consisted of darker characters such as “@” and “#” representing darker pixels and lighter characters such as “.” and “,” representing lighter pixels.

However, you can use any character you like to create your ASCII art. One way to do this is to create a custom list of ASCII characters.

Here’s an example code that defines a new character list:

CUSTOM_CHARS = ["*", "#", "@", "o", "0", "O", " "]
def pixel_to_ascii(pixel_value, ascii_chars):
    NUM_CHARS = len(ascii_chars)
    return ascii_chars[int(pixel_value / (256 / NUM_CHARS))]

In the above example, we’ve defined a new list of ASCII characters and modified the pixel_to_ascii() function to accept the list as a parameter. This means that we can use this new list to create custom ASCII art from an image.

Another way to experiment with different characters is to use Unicode characters. Unicode is a standard for encoding characters and symbols, including letters from various writing systems, mathematical symbols, and emoji.

Here’s an example code that defines a list of Unicode characters:

CUSTOM_CHARS = ["", "", "", "", "", "", "", "", "", "", ""]
def pixel_to_unicode(pixel_value, unicode_chars):
    NUM_CHARS = len(unicode_chars)
    return unicode_chars[int(pixel_value / (256 / NUM_CHARS))]

In the above example, we’ve defined a list of Unicode characters that includes emojis. The pixel_to_unicode() function is similar to pixel_to_ascii(), but it maps pixel values to Unicode characters rather than ASCII characters.

Now that we have a custom list of ASCII or Unicode characters, we can experiment with different combinations to create unique ASCII art pieces. Here are some tips to get started:

  1. Start with a simple image to see how it works with the custom characters you’ve selected.
  2. Play around with different character combinations. Larger images might look good with a mix of larger and smaller characters. For example, use “#” and “@” for larger pixels and “,” and “.” for smaller pixels.
  3. Experiment with different colors. You can use colored ASCII art to create a more visually appealing image.
  4. Try different aspect ratios. Some images might look better with a skinny or wide aspect ratio.
  5. Think outside the box. You don’t have to use only letters, numbers, and symbols. Try using emojis, musical notes, or other Unicode characters to add a unique touch to your ASCII art.

In conclusion, creating custom ASCII art is a fun way to experiment with Python and image manipulation. With a little creativity and experimentation, you can create unique and visually appealing pieces of art. So why not give it a try and see what interesting results you can come up with?

In summary, converting images to ASCII art using Python is a fun and creative way to experiment with image manipulation and Python programming. In this article, we covered the essential steps, including loading an image, resizing, converting it to grayscale, and creating an ASCII character list to convert it to ASCII art.

We also explored the importance of trying different characters, such as custom ASCII and Unicode characters, to create unique and personalized ASCII art. The key takeaway is that with Python, a little creativity, and experimentation, anyone can create visually appealing ASCII art and enjoy the process of coding.

So, what are you waiting for? Start your own ASCII art project today and have fun!

Popular Posts