pip install Image argparse pillow
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 = 80) #输出字符画宽 parser.add_argument('--height', type = int, default = 80) #输出字符画高 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;:,\"^`'. ") # 将256灰度映射到70个字符上 def get_char(r,g,b,alpha = 256): if alpha == 0: return ' ' length = len(ascii_char) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 + 1)/length return ascii_char[int(gray/unit)] if __name__ == '__main__': im = Image.open(IMG) im = im.resize((WIDTH,HEIGHT), Image.NEAREST) txt = "" #将图片看成由像素点组成的二维数组,i代表每一行,j代表每一列 for i in range(HEIGHT): for j in range(WIDTH): #getpixel()函数的参数是由每个像素点在图片中的相对位置(w,h)组成的元组 #返回值是一个代表图片像素值的(r,g,b,alpha)元组 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)
python .\a.py .\time.jpg -o teaGod.txt --width 80 --height 40
转成视频图
import cv2 import os show_heigth = 30 show_width = 80 ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") #生成一个ascii字符列表 char_len = len(ascii_char) vc = cv2.VideoCapture("v.mkv") #加载一个视频 if vc.isOpened(): #判断是否正常打开 rval , frame = vc.read() else: rval = False frame_count = 0 outputList = [] #初始化输出列表 while rval: #循环读取视频帧 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #使用opencv转化成灰度图 gray = cv2.resize(gray,(show_width,show_heigth))#resize灰度图 text = "" for pixel_line in gray: for pixel in pixel_line: #字符串拼接 text += ascii_char[int(pixel / 256 * char_len )] text += "\n" outputList.append(text) frame_count = frame_count + 1 if frame_count % 100 == 0: print("已处理" + str(frame_count) + "帧") rval, frame = vc.read() print("处理完毕") for frame in outputList: os.system("cls") #清屏 print(frame) print() print()