图片转换成字符图
因为之前写到了一些好玩的注释模板,当然网上有很多很多好玩的图片,我们不可能完全收集过来,当然也不可能正好有你自己所需要的图片,所以我们需要一个自己将图片转换成字符图的一个代码,这样我们就可以很方便的得到自己想得到的一些字符图。
参考网址
实验楼有该教程,个人觉得不错,还给了源码,所以摘抄代码下来学习
https
://www
.shiyanlou
.com
/courses
/370
python实现源码
编写
ascii.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
,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
= ""
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
ascii.py ascii_dora
.png
根据实验楼的效果展示
转载请注明原文地址: https://mac.8miu.com/read-493912.html