Quantcast
Channel: C++博客-所有随笔
Viewing all articles
Browse latest Browse all 7882

用python把图形转换为文本输出

$
0
0
关键字: png bmp txt pil 

下面的代码可以把图像转换成文本, 是从网上的一段程序改的, 本来是想在控制台使用的, 但输出的文本过大, 缩放过小又会造成像素丢失的情况。
先贴出来. 这个版本适用于文件输出, 可以保持更好的显示效果
from PIL import Image
import os
def PngToTxt(f):
    Palette={'000':'#'#榛�
    ,'010':'@'#鏆楃豢
    ,'020':'/'#缁�
    ,'001':'$'#娣辫摑
    ,'011':'<'#闈�
    ,'021':'"'#浜�豢鑹�
    ,'002':'='#钃�
    ,'012':'\\'#闂�摑鑹�
    ,'022':'_'#娴呯豢
    ,'100':'>'#鏆楃孩
    ,'110':'*'#鏆楅粍
    ,'120':'~'#榛勭豢鑹�
    ,'101':'%'#鏆楃传
    ,'111':'+'#鐏�
    ,'121':'^'#娴呯豢鑹�
    ,'102':'|'#绱�綏鍏�
    ,'112':'!'
    ,'122':'-'
    ,'200':'&'#绾�
    ,'210':';'#姗欒壊
    ,'220':"'"#榛�
    ,'201':')'#娣辩矇鑹�
    ,'211':'.'#绮夌孩鑹�
    ,'221':'`'
    ,'202':']'#绱�
    ,'212':','
    ,'222':' '#鐧�
    }    
    img = Image.open(f)
    if 0: img = Image.Image
    #缩小, 结果比较模糊, 还是用原比例较好
    #img = img.resize((80,60))
    w,h = img.size[:2]
    print w,h
    result = []
    for i in range(h):
        result1 = []
        for j in range(w):
            pixel = img.getpixel((j,i))[:3]
            result1.append(Palette[''.join([str(int(x//85.3)) for x in pixel])])
        result.append(result1)
    r="\n".join(["".join(x) for x in result])
    print r
    object_file=os.path.splitext(f)[0]+".txt"
    open(object_file,'w').write(r)    



经过一些改进, 下面的代码可以适用于控制台输出

def PngToTxt(f):
    Palette={'000':'#'#榛�
    ,'010':'@'#鏆楃豢
    ,'020':'/'#缁�
    ,'001':'$'#娣辫摑
    ,'011':'<'#闈�
    ,'021':'"'#浜�豢鑹�
    ,'002':'='#钃�
    ,'012':'\\'#闂�摑鑹�
    ,'022':'_'#娴呯豢
    ,'100':'>'#鏆楃孩
    ,'110':'*'#鏆楅粍
    ,'120':'~'#榛勭豢鑹�
    ,'101':'%'#鏆楃传
    ,'111':'+'#鐏�
    ,'121':'^'#娴呯豢鑹�
    ,'102':'|'#绱�綏鍏�
    ,'112':'!'
    ,'122':'-'
    ,'200':'&'#绾�
    ,'210':';'#姗欒壊
    ,'220':"'"#榛�
    ,'201':')'#娣辩矇鑹�
    ,'211':'.'#绮夌孩鑹�
    ,'221':'`'
    ,'202':']'#绱�
    ,'212':','
    ,'222':' '#鐧�
    }    
    img = Image.open(f)
    if 0: img = Image.Image
    #缩小, 结果比较模糊, 还是用原比例较好
    img = img.resize((60,20))
    w,h = img.size[:2]
    #print w,h
    result = []
    for i in range(h):
        result1 = []
        is_empty_line = True
        for j in range(w):
            pixel = img.getpixel((j,i))[:3]
            #result1.append(Palette[''.join([str(int(x//85.3)) for x in pixel])])
            if pixel==(255,255,255):
                s = '222'
            else:
                s = '110'
                is_empty_line = False
            result1.append(Palette[s])
        #去除空行
        if is_empty_line == False:
            result.append(result1)
    r="\n".join(["".join(x) for x in result])
    print r
    object_file=os.path.splitext(f)[0]+".txt"
    open(object_file,'w').write(r)

图例:




wangkang 2014-03-20 09:36 发表评论

Viewing all articles
Browse latest Browse all 7882

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>