from PIL import Image
import argparse
# parameter analysis
parser = argparse.ArgumentParser()
parser.add_argument('file') # Input file
parser.add_argument('-o', '--output') # Output file
# parser.add_argument('-shortname','--fullname')#存在简称和全程的格式在输入时可有可无
# parser.add_argument('--fullnage',type=?,default=?)#当然不使用简称也是可以的
parser.add_argument('--width', type = int, default = 80) # output alphabet width
parser.add_argument('--height', type = int, default = 80) # output alphabet height
# get parameters
args = parser.parse_args()
IMG = args.file
WIDH = args.width
HEIGHT = args.height
OUTPUT = args.output
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# Map 256 grayscale to 70 characters
def get_char(r,g, b, alpha = 256):
if alpha == 0:
return
# Gets the character set length, which is 70
length = len(ascii_char)
# Convert the RGB value to a gray value with a range of 0-255
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
# The grayscale range is 0-255, and the character set is only 70
# You need to do the following to map the grayscale value to the specified character
unit = (256.0 + 1 ) / length
# Returns the character corresponding to the grayscale value
# # gray值对应到char_string中的位置(索引值)
return ascii_char[int(gray / unit)]
if __name__ == '__main__':
im = Image.open(IMG)
im = im.resize((WIDH, HEIGHT), Image.NEAREST) # 注意这个函数第二个参数使用 Image.NEAREST,表示输出低质量的图片
# 初始化字符串
txt = ""
# Iterate through each line in the picture
for i in range(HEIGHT):
# iterates through each column in the row
for j in range(WIDH):
# 将 (j,i) 坐标的 RGB 像素转为字符后添加到 txt 字符串
txt += get_char(*im.getpixel((j, i)))
#获取得到坐标 (i,j) 位置的 RGB 像素值(有的时候会包含 alpha 值),
# 返回的结果是一个元组,例如 (1,2,3) 或者 (1,2,3,0)。
# 我们使用 * 可以将元组作为参数传递给 get_char,同时元组中的每个元素都对应到 get_char 函数的每个参数。
# 遍历完一行后需要增加换行符
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()
运行问题
Traceback (most recent call last):
File “picturee.py”, line 54, in
txt += get_char(*im.getpixel((j, i)))
TypeError: get_char() argument after * must e an iterable, not int
解决办法:
需要将 im 转换为 RGB 格式,因为 getpixel 获取的是 RGB 的像素。
所以在 im = Image.open(IMG)之后加 im = im.convert(‘RGB’) 就可以了