python将照片转文字_Python将图片转化成文字
我們之前學過詞云能將數據變成圖片展示出來,那么今天我們就來看個不同的,將圖片變成字符輸出。
看個效果圖:
文字輸出:
那么下面我們來看看代碼吧!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)
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python将照片转文字_Python将图片转化成文字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 柱状图给特定的柱子上的_p
- 下一篇: 栈判断字符串是否为中心对称_数据结构和算