前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python将图片转化成文字

Python将图片转化成文字

作者头像
我被狗咬了
发布2019-09-23 10:43:49
2.4K0
发布2019-09-23 10:43:49
举报
文章被收录于专栏:Python乱炖Python乱炖

我们之前学过词云能将数据变成图片展示出来,那么今天我们就来看个不同的,将图片变成字符输出。

看个效果图:

文字输出:

那么下面我们来看看代码吧!

代码语言:javascript
复制
import argparse
from PIL import Image
 # 命令行输入参数处理
parser = argparse.ArgumentParser()
# 输入图片
parser.add_argument('file', 
                    help='the input file')
# 输出文件
parser.add_argument('-o', '--output', 
                    help='the output text file')
# 输出字符画宽度
parser.add_argument('-w', '--width',
                    type=int, default=40,
                    help='the width of the output, default is 40')
# 输出字符画高度
parser.add_argument('--height', 
                    type=int, default=40,
                    help='the height of the output, default is 40')
# 获取参数
args = parser.parse_args()
IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output
str = "$@B%8&WM#*oahkbdpqw" \
      "mZO0QLCJUYXzcvunxrjft/\|()" \
      "1{}[]?-_+~<>i!lI;:,\"^`'. "
ascii_char = list(str)
 # 将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)
     # 每个字符对应的 gray 值区间宽度
    unit = (256.0+1)/length
     # gray值对应到 char_string 中的位置(索引值)
    index = int(gray/unit)
    return ascii_char[index]
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)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-11-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python乱炖 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档