运行环境
Python版本:Python3.8
开发软件:Sublime
1、实验准备
安装pillow库
Pillow是Python里的图像处理库,是PIL派生的一个分支,主要用来替换PIL库。这是因为PIL只支持Python2的版本;而在Python3中使用的则是Pillow。
操作步骤:
(1)Win+R,输入cmd,打开Windows的命令行。
(2)输入:pip install pillow,等待安装完成。
如果安装过程不顺利,请百度找到原因,直到安装成功为止。
2、完整代码
#作者:皆昌
from PIL import Image
img = Image.open("D:/python/charpicture/jie.jpg") # 打开
out = img.convert("L") # 灰度
width, height = out.size # 赋值
out = out.resize((int(width * 0.5),int(height * 0.375))) # 改变图像的大小
width, height = out.size # 赋值
asciis = "@%#*+=-. "
texts = ""
for row in range(height):
for col in range(width):
gray = out.getpixel((col,row))
texts += asciis[int(gray / 255 * 8)]
texts += "\n"
with open("D:/python/charpicture/jie.txt","w") as file:
file.write(texts)
也可以参考如下图片:
3、实验效果
原图:
效果:
源代码链接:https://download.csdn.net/download/weixin_42067188/12518605