Turn from: 78447714
Project Link: https://www.shiyanlou.com/courses/370/labs/1191/document
From PIL import Image #从PIL模块中引入Image这个类
Import argparse #引入argparse这个模块 (Argparse Library is used to manage command-line parameter input)
Parser = Argparse. Argumentparser () #创建一个解析对象
Parser.add_argument (' file ') #添加命令行参数和或选项: Input file
Parser.add_argument ('-O ', '--output ') #输出文件
Parser.add_argument ('--width ', type = int, default = $) #输出字符画宽
Parser.add_argument ('--height ', type = int, default = $) #输出字符画高
args = Parser.parse_args () #解析
IMG = Args.file
WIDTH = Args.width
HEIGHT = Args.height
OUTPUT = Args.output
#定义一个ascii的列表 so that the grayscale on the picture corresponds to the character
Ascii_char = List ("[Email protected]%8&wm#*oahkbdpqwmzo0qlcjuyxzcvunxrjft/\| () 1{}[]?-_+~<>i!1i;:,\ "^". ")
#将256灰度映射到70个字符上
def get_char (R,g,b,alpha =): #这个调用跟im. getpixel function, this function is based on the horizontal ordinate of the picture, the image is parsed into
#R,g,b,alpha (grayscale)
If alpha = = 0: #如果灰度是0, it means there are no pictures here
Return '
length = Len (Ascii_char) #计算这些字符的长度
Gray = Int (0.2126 * r + 0.7152 * g + 0.0722 * b) #把这些图片的RGB值转换成灰度值
Unit = (256.0 + 1)/length
Return Ascii_char[int (gray/unit)] #选出了灰度与哪个字符相对应
if __name__ = = ' __main__ ': #如果是本程序调用, execute the following program
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))) #把图片按照横纵坐标解析成RGBAlpha这几个参数, and then call Get_char
#函数, convert the corresponding image to grayscale value, the corresponding value of the character into txt
txt + = ' \ n '
Print (TXT) #在界面打印txt文件
If OUTPUT:
With open (OUTPUT, ' W ') as F: #文件输出
F.write (TXT)
Else
With open ("Xx.txt", ' W ') as F: #文件输出
F.write (TXT)
Python Learning---50 lines of code to achieve picture-to-character painting 1