5 Star 50 Fork 0

Gitee Community / 码力传递:晒代码赢奖品

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
图片转字符画.md 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
封尘 提交于 2020-05-27 15:08 . add 图片转字符画.md.
"""
图片转字符画
版本: python version >= 3 
扩展:
pip install --upgrade pip
pip install --user matplotlib
pip install pillow
"""

import matplotlib.pyplot as plt
#显示区域的长宽
show_width = 150
show_height = 50    

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

# 读取图片,这里要指定图片路径
pic = plt.imread("E:/1.jpg")
pic_height ,pic_width,_ = pic.shape
#获取图像的高、宽

gray = 0.2126 * pic[:,:,0] + 0.7152 * pic[:,:,1] + 0.0722 * pic[:,:,2]
#RGB转灰度图的公式 gray = 0.2126 * r + 0.7152 * g + 0.0722 * b

#思路就是根据灰度值,映射到相应的ascii_char
for i in range(show_height):
    #根据比例映射到对应的像素
    y = int(i * pic_height / show_height )
    text = ""
    for j in range(show_width):
        x = int(j * pic_width / show_width)
        text += ascii_char[int(gray[y][x] / 256 * char_len)]
    print(text)

截图

1
https://gitee.com/gitee-community/gitee-7th-event-3.git
git@gitee.com:gitee-community/gitee-7th-event-3.git
gitee-community
gitee-7th-event-3
码力传递:晒代码赢奖品
master

搜索帮助