学习了下python图片转字符画,学习连接:Python 图片转字符画,觉得还挺有趣,不过图片的颜色和细节不能太多,不然效果比较差,代码如下:
from PIL import Image
import argparse
def get_char(r,g,b,alpha=256):
gary=(2126*r+7152*g+722*b)/10000
ascii_char=list(r"$@&%B#=-. ")
x=int((gary/(alpha+1.0))*len(ascii_char))
return ascii_char[x]
def main(file_name='1.png',width=50,height=50,out_file_name="out_file"):
text=""
im=Image.open(file_name)
im=im.resize((width,height),Image.NEAREST)
for i in range(height):
for j in range(width):
content=im.getpixel((j,i))
text+=get_char(*content)
text+="\n"
write_file(out_file_name,text)
def write_file(out_file_name,content):
with open(out_file_name,"w") as f:
f.write(content)
def parse_param():
parser=argparse.ArgumentParser()
parser.add_argument("input_file")
parser.add_argument("output_file")
parser.add_argument("--width",type=int,default=50)
parser.add_argument("--height",type=int,default=50)
args=parser.parse_args()
width,height,in_file,out_file=args.width,args.height,args.input_file,args.output_file
return width,height,in_file,out_file
if __name__=='__main__':
width,height,in_f,out_f=parse_param()
main(file_name=in_f,width=width,height=height,out_file_name=out_f)
学习笔记:
1、原理其实比较简单,就是里利用Image类里getpixel()方法返回图片的RGB值,再同比例找list里的值。
2、pillow库,python的图像处理库,还有pillow中最重要的Image类。
3、python的命令行选项和参数解析的模块,argparse模块。