Python实现图片转字符画


from PIL import Image


def get_char(r, g, b, alpha=256):
    ascii_char = '''$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. '''
    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)]


def get_img(img: str):
    im = Image.open(img)
    height = int(im.size[1]/1.5)
    width = int(im.size[0]/1.5)

    im = im.resize((width, height), Image.NEAREST)
    txt = ""
    for h in range(height):
        for w in range(width):
            txt += get_char(*im.getpixel((w, h)))
        txt += "\n"
    return txt


def main(image_name: str, art_name: str):
    txt = get_img(image_name)
    with open(art_name, "w", encoding="utf-8") as f:
        f.write(txt)


if __name__ == '__main__':
    main(r"C:\Users\Administrator\Desktop\1.png", r"C:\Users\Administrator\Desktop\1.txt")

  

智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告