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

# 将256灰度映射到70个字符上
def get_char(gray):
    if gray == 0:
        return ' '
    length = len(ascii_char)
    unit = (256.0 + 1)/length
    return ascii_char[int(gray/unit)]

if __name__ == '__main__':
    img=cv2.imread("cxk.jpg",0)  #直接读取为灰度图
    h,w=img.shape
    nh=80
    nw=int(nh*w/h)
    img=cv2.resize(img,(nw,nh))

    txt = ""

    for i in range(nh):
        for j in range(nw):
            txt += get_char(img[i,j])
        txt += '\n'
    with open("output.txt",'w') as f:
        f.write(txt)