draw.py
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;:,\"^`'. ")
def get_char(r,b,g,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 = ""
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)
使用上面的代码,
python draw.py image.png
我可以得到这样的ascii图像:
现在我想把它变成一个模型,所以我可以导入它,然后我在同一个路径中用image.jpg(或bmp,png ....)创建一个ascii图像,只使用一个函数,它可以打印出来,并将其写入txt文件
答案 0 :(得分:1)
draw.py
from PIL import Image
ASCII_CHAR = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
def get_char(r,b,g,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)]
def get_ascii_image(im, width, height):
if isinstance(im, basestring):
im = Image.open(im)
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'
return txt
def save(txt, output):
if output:
with open(output, 'w') as f:
f.write(txt)
else:
with open("output.txt", 'w') as f:
f.write(txt)
if __name__ == '__main__':
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
txt = get_ascii_image(IMG, WIDTH, HEIGHT)
print txt
save(txt, OUTPUT)
other_python_file.py
import draw
txt = draw.get_ascii_image("PATH", width=80, height=80)
draw.save(txt, "DESTINATION_PATH")