【Python】用字母生成图像

用字母生成图像会用到matplotlib.pyplot库

所以需要安装这个库

pip install matplotlib 

等待安装完成即可

ps:由于网络原因,会出现多次的timeout,可以使用国内的python库,我比较习惯使用清华的python

pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple

-i后面指定国内的python库的url即可。

import matplotlib.pyplot as plt
show_heigth = 50
show_width = 110
#这两个数字是调出来的

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

pic = plt.imread("D:\\66666.jpg")
#使用plt.imread方法来读取图像,对于彩图,返回size = heigth*width*3的图像
#matplotlib 中色彩排列是R G B
#opencv的cv2中色彩排列是B G R

pic_heigth,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_heigth):
    #根据比例映射到对应的像素
    y = int(i * pic_heigth / show_heigth)
    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)

其中的长宽高还有图片存放位置,都需要根据实际情况调整

代码来自:https://www.cnblogs.com/youmuchen/p/8299109.html 

生成效果示意图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值