01-Python 图片转字符画

复制代码
from PIL import Image

"""
    将图片转换为字符画

    图片转字符画是将一张图片转换成由字符组成的图像,通常用于在命令行界面或者文本编辑器中显示。这个过程主要包括以下几个步骤:

    - 读取图片文件
    - 将图片转换为灰度图像
    - 调整图片的尺寸以适应字符画的宽度和高度
    - 将灰度值映射到字符集上,生成字符画


    参考链接:
     - [Image Module](https://pillow.readthedocs.io/en/stable/reference/Image.html)
     - https://blog.csdn.net/m0_73511684/article/details/137026540
     - https://zhuanlan.zhihu.com/p/687097277

    说明:
     - pip install PIL 安装不了,安装 Pillow,该库与PIL接口兼容,可以满足你的图像处理需求。导入使用 from PIL import Image
"""

class ASCIIart(object):
    def __init__(self, file):
        """
         - file图片文件的名字, 传入参数为文件名进行一个赋值方便后续调用, 
         - codelist用于存储字符集,用于替换每像素点的灰度值
         - img是PIL库中Image实例出来的对象,调用open方法打开文件file
         - count用于保存字符集的长度
        """
        self.file = file
        self.codelist = """$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. """
        self.img = Image.open(file)
        self.count = len(self.codelist)
 
    def get_char(self, r, g, b, alpha=256):
        """
        用来处理灰度值和字符集的关系
        :return:
        """
        if alpha == 0:
            return " "
        length = self.count  # 获取字符集的长度
        gary = 0.2126 * r + 0.7152 * g + 0.0722 * b  # 将RGB值转为灰度值
        unit = 265 / length
        return self.codelist[int(gary / unit)]
 
    def get_new_img(self):
        """
        用于处理图片是转换的字符画不至于失真
        :return:
        """
        w, h = self.img.size
        print(f"图片的原始宽度和高度为:{w},{h}")
        if not w or not h:
            pass
        else:
            if w <= 299 or h <= 299:
                w = int(w / 1.4)
                h = int(h / 1.4)
            if 300 <= w <= 500 or 300 <= h <= 500:
                w = int(w / 2)
                h = int(h / 2)
            if 500 < w < 1000 or 500 < h < 1000:
                w = int(w / 3.8)
                h = int(h / 3.8)
            if 1000 <= w or 1000 <= h:
                w = int(w / 10)
                h = int(h / 10)
            print(f"修改后图片的宽度和高度为:{w},{h}")
            """
                https://pillow.readthedocs.io/en/stable/handbook/concepts.html#filters
                
                Image.NEAREST: 低质量
                Image.BILINEAR: 双线性
                Image.BICUBIC: 三次样条插值
            """
            im = self.img.resize((w, h), Image.Resampling.LANCZOS)
            return im
 
    def get_str_img(self, im, output=None):
        """
        获取字符串图片
        :return:
        """
        w, h = im.size
        txt = ""
        for i in range(h):
            for j in range(w):
                txt += self.get_char(*im.getpixel((j, i)))
            txt += "\n"
        # 字符画输出到文件
        if output:
            with open(output, "w") as file:
                file.write(txt)
        else:
            with open("output/output3.txt", "w") as file:
                file.write(txt)
 
 
if __name__ == '__main__':
    file = "image/thing.jpg"
    img = ASCIIart(file)
    im = img.get_new_img()
    img.get_str_img(im)
复制代码

 

posted @   一杯热水  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· 大模型工具KTransformer的安装
· [计算机/硬件/GPU] 显卡
点击右上角即可分享
微信分享提示