实现图片转换成字符画

python小程序:实现图片转换成字符画

看到网上有很多这样的小程序,自己动手做一个

内附详细说明~

先附上效果图

实现图片转换成字符画_第1张图片

部分解释

运行平台: Win10
Python版本: Python3.9 
IDE: Pychram

Image模块:Image模块在PIL库中,python3安装PIL库需要安装pillow-pil,在Pychram中操作为File | Settings | Project: xxx | Python Interpreter,点击左下角加号,搜索pillow-pil安装,提示安装成功即可,使用  from PIL import Image 导入;

Image模块的用法详情可见https://blog.csdn.net/yjwx0018/article/details/52852067

灰度图:定义自行百度。导入的图片一般是RBG模式的,使用Image模块中的convert('L')将其转换成灰度图方便操作;

getpixel函数:得到每一个像素的灰度级别,参数是一个坐标点,返回值随着图像模式的不同而不同,灰度图的返回值为一个0~255的整数。

代码

from PIL import Image           # 导入Image模块

"""
创建64个字符的list,目的是让256级灰度每四级对应一个字符
由于纯白的灰度级别为255,为了将白色和几乎为白色的像素点在字符图里面为空白,list的后四位为空格(即16级灰度)
"""
lst = list("@$#%&WASGHKBMRDFZXNVCJLQOTPYEUIab987654321~?!^*()<>+-=[]{},.    ")


def get_char(pixel_Tvalue):
    return lst[pixel_Tvalue // 4]


if __name__ == '__main__':
    img = Image.open(r"D:\Temp\pika.jfif").convert("L")        # 打开图片并转换为灰度图
    wide, high = img.size                                      # 得到原图片的宽和高
    wide, high = wide // 4, high // 4
    img = img.resize((wide, high))                             # 将图片缩小到原来的四倍,可以自行修改测试
    text0 = ""
    for i in range(high):
        for j in range(wide):
            text0 += get_char(img.getpixel((j, i)))            # 利用getpixel得到灰度级别
        text0 += '\n'

    with open(r"D:\Temp\字符图.txt", "w") as f:
        f.write(text0)

 

 

你可能感兴趣的:(python小程序,python,经验分享)