Python项目:图片转字符画

该项目是我跟着实验楼练手的一个小项目,在Linux环境下运行,建议各位读者可以将所有的工作都移到linux环境下使用,这样锻炼Linux的使用,我现在就觉得linux比windows使用顺手。。。

首先安装PIL库,它 是一个 Python 图像处理库,使用pip安装:sudo pip3 install pillow
我们是要转换一张彩色的图片,这么多的颜色,要怎么对应到单色的字符画上去?如作者所言,使用灰度值
灰度值:指黑白图像中点的颜色深度,范围一般从0到255,白色为255,黑色为0,故黑白图片也称灰度图像
我们可以使用灰度值公式将像素的 RGB 值映射到灰度值:
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
下面是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)]
下载所用的图片:wget http://labfile.oss.aliyuncs.com/courses/370/ascii_dora.png

ascii.py完整的代码如下:

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)
实验截图如下: 来源: 实验楼
链接: https://www.shiyanlou.com/courses/370

猜你喜欢

转载自blog.csdn.net/weixin_40602516/article/details/81064871