Transfer from laboratory building: https://www.shiyanlou.com/courses/370/learning/?id=1191
Code:
# - * - Coding: UTF-. 8 - * - from the PIL Import Image Import argparse # Create instance ArgumentParser Parser = argparse.ArgumentParser () # define input file, an output file, the output character width and height of the draw parser.add_argument ( ' File ' ) # mandatory parameters. 1 parser.add_argument ( ' -o ' , ' --output ' ) # optional parameter 2 parser.add_argument ( ' --width ' , = int type, default = 80) # optional parameters 3 parser.add_argument ( ' --height' , = Int type, default = 80) # optional parameters 4 # parse and obtain the parameter args = parser.parse_args () # input image file path to the IMG = args.file # input character painting width WIDTH = args.width # Videos input character height hEIGHT = args.height # output path character painting the oUTPUT = args.output # first gradation values into RGB values, and then use the gray value is mapped to a character in the character list ascii_char = list ( " $ @ B%. 8 & the WM # * oahkbdpqwmZO0QLCJUYXzcvunxrjft / \ | (). 1 {} [] -_ + ~ <> I lI;:?!, \." ^ ` ' " ) DEF GET_CHAR (R & lt, G, B, Alpha = 256 ): # Analyzing alpha value IF alpha ==0: return ' ' # Get the length of the character set length = len (ascii_char) # RGB values into gray, gray value range of 0-255 Gray = int (R & lt 0.2126 * 0.7152 * G + 0.0722 * + B) # gray value range of 0-255, but only 70 characters # require a process to the gradation value to the developed character map uint = (256.0 +. 1) / length # return gradation values corresponding to the characters return ascii_char [ int (Gray / uint)] IF the __name__ == ' __main__ ' : # open and adjust the width and height of the image IM = Image.open (the IMG) IM = im.resize ((wIDTH, HEIGHT), Image.NEAREST) #Initialization string output TXT = "" # traverse each line in the picture for I in Range (HEIGHT): for J in Range (WIDTH): TXT + = GET_CHAR (* im.getpixel ((J, I))) # after through each row need to add a line break TXT + = ' \ n- ' # output to screen Print (TXT) # character painting output to a file IF the oUTPUT: with Open (the oUTPUT, ' W ' ) AS F: f.write (TXT ) the else : with Open ( " output.txt ",'w') as f: f.write(txt)
operation result: