Python Tutorial: How to convert a picture to ASCII art with PIL

Python Tutorial: How to convert a picture to ASCII art with PIL

ASCII art is an art form that converts images into characters. Python is a flexible and powerful programming language that can be used to convert pictures into ASCII art. This article shows how to do this using Python and the PIL library.

There is a complete code at the end of the article

Effect

First look at the effect on the picture

original image

insert image description here

ASCII art

%%%@@%#*++++++++++++++++++++++++++++++++++*#%@@%%%
%@@%*++++++++++++++++++++++++++++++++++++++++*%@@%
@%*+=+++++++++++++==++++++==+++++++++++++++++=+*%@
%*=+++++++++++++++*##%%%%%#*++====+++++++++++++=*%
*=++++++++++++++#%%%#****#%%%#*****++=++++++++++=*
++++++++++++==*%@#++====+*#%@%%%%%%%%#++++++++++++
+++++++++=++*#%@#++=++*#%%%#*++++++*#%%#++++++++++
+++++++++*%%%%@%+++*%%%#*++=++**++===+%@#+++++++++
++++++++%@%*+*@%+++%@*+==+*#%%%%%#*++=+%@*++++++++
+++++++%@#+==#@%+++%@*+*#%@%*+++*%%%%#*%@#=+++++++
+++++=#@%+++=#@%+++%@%%%##%%%#*+==+*#%@@%*=+++++++
+++++=#@%+++=#@%+=+%@#++==++#@%%#*++=+*#@%*+++++++
+++++++%@#+++*%%%#*%@*=++++=*@%*#%%%*+=+#@%+++++++
+++++++*%@#*+=++*#%%@#++==++#@%+=+%@*=+++%@*=+++++
+++++++=*@@@%#*+==+*#%%%##%%%@%+++%@*=+++%@*=+++++
++++++++#@%*#%%%%*+++*%@%#*+*@%+++%@*==+#@%+++++++
++++++++*@%+=++*#%%%%%#*+==+#@%+++%@*+*%@%++++++++
+++++++++%@%+====+**++=++*%%%%*+++%@%%%%*+++++++++
++++++++++#%%#*++++++*#%%%#*+++++#@%#*++=+++++++++
++++++++++++#%%%%%%%%@%#*+====++#@%*==++++++++++++
*+++++++++++=++*****#%%%#****#%%%#++++++++++++++++
%*=+++++++++++++====++*#%%%%%##*+=++++++++++++++++
@%*+=++++++++++++++++++=++++++=+++++++++++++++++++
%@@#*+++++++++++++++++++++++++++++++++++++++++++++
%%%@@%#*++++++++++++++++++++++++++++++++++++++++++

Preparation

Before starting, you need to make sure you have installed the Python and PIL libraries. You can check if the PIL library is installed with the following command:

import PIL
print(PIL.__version__)

If the version information of the PIL library is output, it means that the installation has been successful.

load image

First, you need to load an image in PNG format and convert it to RGB format. You can use Image.open()the function to load the image, and use convert()the method to convert it to RGB format:

from PIL import Image
# 直接将图片放再相同的目录,写名字就可以了
# 加载 PNG 图像
image = Image.open("xxx.png").convert('RGB')

resize picture

When converting an image to ASCII art, it needs to be resized appropriately. The image can be resized using resize()the method :

# 调整图像大小
width, height = image.size
aspect_ratio = height / width
new_width = 50
new_height = int(new_width * aspect_ratio * 0.55)  # 调整高度以保持长宽比
image = image.resize((new_width, new_height))

define character set

To convert a picture to ASCII art, you need to define a charset, a set of characters that represent different grayscale values. The following character sets can be used:

CHARS = [' ', '.', ':', '-', '=', '+', '*', '#', '%', '@']

convert pixels to characters

Now, every pixel in a picture can be converted into a character. To do this, iterate through each pixel in the image and convert it to a grayscale value. Then, the gray value is mapped to an index in the character set, replacing the original pixel value with the corresponding character. Finally, stitch all the characters together to create the ASCII art.

# 将每个像素转换为字符,并拼接为字符串
ascii_art = ''
pixels = list(image.getdata())
for i in range(len(pixels)):
    pixel = pixels[i]
    gray = int((pixel[0] + pixel[1] + pixel[2]) / 3)  # 计算灰度值
    index = int(gray / (255 / (len(CHARS) - 1)))  # 映射到字符集中的索引
    ascii_art += CHARS[index]

    if (i + 1) % new_width == 0:
        ascii_art += '\n'  # 每行结束后换行

output ASCII art

Finally, output the ASCII art to the console:

# 输出 ASCII 艺术
print(ascii_art)

After running the code, you will see the generated ASCII art in the console.

full code

Here's the full Python code for converting an image to ASCII art:

from PIL import Image

# 加载 PNG 图像
image = Image.open("qrcode.png").convert('RGB')

# 调整图像大小
width, height = image.size
aspect_ratio = height / width
new_width = 50
new_height = int(new_width * aspect_ratio * 0.55)  # 调整高度以保持长宽比
image = image.resize((new_width, new_height))

# 定义字符集
CHARS = [' ', '.', ':', '-', '=', '+', '*', '#', '%', '@']

# 将每个像素转换为字符,并拼接为字符串
ascii_art = ''
pixels = list(image.getdata())
for i in range(len(pixels)):
    pixel = pixels[i]
    gray = int((pixel[0] + pixel[1] + pixel[2]) / 3)  # 计算灰度值
    index = int(gray / (255 / (len(CHARS) - 1)))  # 映射到字符集中的索引
    ascii_art += CHARS[index]

    if (i + 1) % new_width == 0:
        ascii_art += '\n'  # 每行结束后换行

# 输出 ASCII 艺术到控制台
print(ascii_art)

Please triple if you like, thank you

Guess you like

Origin blog.csdn.net/godnightshao/article/details/130231680