Home > Article > Backend Development > What is the code for converting python images to character drawings?
Python picture to character drawing code: first calculate the grayscale value corresponding to the color of the picture; then according to the grayscale value, obtain the character corresponding to each pixel in the picture from the character set, the code is [args = parser .parse_args()].
The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer. This method is suitable for all brands of computers.
Related free learning recommendations: python video tutorial
Principle
1. Calculate the grayscale value corresponding to the color of the picture. The calculation formula is as follows
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
2. According to the grayscale value, obtain the characters corresponding to each pixel in the image from the character set
Code
# !/usr/bin/env python # -*- coding:utf-8 -*- from PIL import Image import argparse #命令行输入参数处理 parser = argparse.ArgumentParser() parser.add_argument('file') #输入文件 parser.add_argument('-o', '--output') #输出文件 parser.add_argument('--width', type = int, default = 50) #输出字符画宽 parser.add_argument('--height', type = int, default = 50) #输出字符画高 #获取参数 args = parser.parse_args() IMG = args.file WIDTH = args.width HEIGHT = args.height OUTPUT = args.output # 字符画使用的字符集 ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") def get_char(r,g,b,alpha = 256): """将256灰度映射到70个字符上""" if alpha == 0: return ' ' length = len(ascii_char) # 计算灰度的公式 gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 + 1)/length index=int(gray/unit) return ascii_char[index] if __name__ == '__main__': im = Image.open(IMG) im = im.resize((WIDTH,HEIGHT), Image.NEAREST) txt = "" # 获取每个像素点对应的字符 for i in range(HEIGHT): for j in range(WIDTH): txt += get_char(*im.getpixel((j,i))) txt += '\n' print(txt) #字符画输出到文件 if OUTPUT: with open(OUTPUT,'w') as f: f.write(txt) else: with open("output.txt",'w') as f: f.write(txt)z
Running results
The above is the detailed content of What is the code for converting python images to character drawings?. For more information, please follow other related articles on the PHP Chinese website!