这次又带来一个关于python的小操作哈

首先什么是图像字符化呢,就是将一幅图片用各种字符进行显示,下面是个例子:

python实现图像字符化      →        python实现图像字符化

看起来蛮高大上的样子,其实很容易实现啦,代码如下:

# 导入模块
from PIL import Image

# 转换函数
def convert(img):
    # 要索引的字符列表
    ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

    # 字符长度
    length = len(ascii_char)
    # 读取图像文件
    img = Image.open(img)    
    # 获得图片的宽和高
    (width,height) = img.size
    # 对图像进行一定缩小
    img = img.resize((int(width*0.1),int(height*0.05)))
    # 转为灰度图像
    img = img.convert("L")  
    txt = ""
    for i in range(img.size[1]):
        for j in range(img.size[0]):
            # 获取每个坐标像素点的灰度
            gray = img.getpixel((j, i))  
            # 获取对应坐标的字符值
            unit = 256.0 / length
            txt += ascii_char[int(gray / unit)] 
        txt += '\n'
    return  txt

# 传入需要转换的原始图片
txt = convert('haizei.jpg')
# 把转换后的字符存入txt文件
f = open("convert.txt","w")
f.write(txt)            
f.close()

就一个PIL模块就实现啦,是不是很简单呢

相关文章:

  • 2022-12-23
  • 2021-08-25
  • 2022-12-23
  • 2022-12-23
  • 2021-11-19
  • 2021-10-06
  • 2021-05-04
猜你喜欢
  • 2021-06-14
  • 2022-03-08
  • 2021-12-26
  • 2021-12-27
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案