convert image to ascii art in python

To convert an image to ASCII art in Python, we can use the Pillow library for image processing. Here's a step-by-step guide:

  1. Install Pillow library using pip:
main.py
pip install Pillow
19 chars
2 lines
  1. Load the image using Pillow:
main.py
from PIL import Image
img = Image.open('image.jpg')
52 chars
3 lines
  1. Resize the image to fit the terminal size to avoid cropping or distorting the ASCII art:
main.py
import os
terminal_size = os.get_terminal_size()
img.thumbnail(terminal_size)
78 chars
4 lines
  1. Convert the image to grayscale:
main.py
img = img.convert('L')
23 chars
2 lines
  1. Define the ASCII characters for the different shades of gray:
main.py
ASCII_CHARS = [' ', '.', ':', '-', '=', '+', '*', '#', '%', '@']
65 chars
2 lines
  1. Loop through each pixel of the image, convert the pixel value to an ASCII character, and concatenate the characters into a single string:
main.py
pixels = img.getdata()

ascii_art = ''
for pixel in pixels:
    ascii_art += ASCII_CHARS[int(pixel/25)]
104 chars
6 lines
  1. Print the resulting ASCII art:
main.py
print(ascii_art)
17 chars
2 lines

Note that the resulting ASCII art might look distorted or low quality in the console, as characters have a fixed width and height. Some further adjustments (such as applying a custom font or smoothing the image) might be necessary to make the ASCII art look better.

gistlibby LogSnag