图片转字符画实现

这次会用到:

      Python基础,Pillow库的使用,Argparse库的使用

首先,PIL是一个Python图像处理库,是这次联系将要用到的重要工具,所以需要安装.

Linux安装PIL库:

sudo pip3 install pillow

Windows:

pip3 install pillow

字符画就是一个字符代表一种颜色,字符的种类越多代表的颜色就越丰富,图画更有层次感.

如果转换一张图片,怎么把图片转换到对应的单个的字符上呢?这里需要介绍灰度值概念:

 灰度值:指黑白图像中点的颜色深度,范围一般从0到255,白色为255,黑色为0,故黑白图片也称灰度图像

灰度值公式将像素的 RGB 值映射到灰度值:

gray = 0.2126 * r + 0.7152 * g + 0.0722 * b

我们可以创建一个不重复的字符列表,灰度值小(暗)的用列表开头的符号,灰度值大(亮)的用列表末尾的符号

这里用linux演示:

创建 ascii.py 文件进行编辑

vim ascii.py

导入必要的库,argparse 库是用来管理命令行参数输入的

from PIL import Image
import argparse

下面是我们的字符画所使用的字符集,一共有 70 个字符,字符的种类与数量可以自己根据字符画的效果反复调试

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

RGB值转字符的函数:

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)]

完整代码:

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;:,\"^`'. ")

# 将256灰度映射到70个字符上
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)

下载用来测试的文件:

wget http://路径

wget http://labfile.oss.aliyuncs.com/courses/370/ascii_dora.png

ascii_dora.png

使用刚刚编写的 ascii.py 来将下载的 ascii_dora.png 转换成字符画。

python3 ascii.py ascii_dora.png

然后使用 vim 打开 output.txt 文件

vim output.txt

就可以看到图片了.

猜你喜欢

转载自www.cnblogs.com/425500828zjy/p/8907316.html