python生成字符画

python生成字符画

这个idea来自于实验楼,非常适合练习PIL的像素处理,更重要的是非常有意思。

环境配置

依赖的第三方库就是PIL(Python Image Library),可以直接使用pip安装

pip install pillow

测试安装是否成功

>>> from PIL import Image

原理

原理其实很简单,主要分为三步:

  1. 导入图片,做预处理
  2. 把图片二值化,转化成灰度图,在把灰度映射到字符上,用一个字符表示一个像素,返回一个文本
  3. 把文本写入文件

以下是main函数

def main():
    img = loadImage('./a.jpg')
    text = convert(img)
    store(text)    
    print "finish!"

导入图片

#打开图片,还可以做预处理如resize
def loadImage(fileName):
    img = Image.open(fileName)
    return img

把图片转成文本

#核心函数,把image对象转换成文本
def convert(img):
    color = "MNHQ$OC?7>!:-;." #自定义字符集
    length = len(color)
    w,h = img.size
    grey = img.convert('L') #转化为灰度图
    text = ''
    #依次遍历每个像素,把灰度图转化成文本
    for x in xrange(h):
        for y in xrange(w):
            pixel = grey.getpixel((y,x))
            if pixel==0:
                text += ' '
            else:  
                text += color[(pixel*length)/255-1] #减1是为了防止字符串越界
        text += '
'
    return text

写入文件,这里采用HTML形式

#写文件,这里把结果用HTML呈现
def store(text):
    head= '''
            <html>
              <head>
                <style type="text/css">
                  body {font-family:Monospace; font-size:5px;}
                </style>
              </head>
            <body> '''
    tail = '</body></html>'
    html = head + text.replace('
','<br>') + tail 
    #写文件
    f = open('out.html','w')
    f.write(html)
    f.close()

完整代码

#coding=utf-8
from PIL import Image

#打开图片,还可以做预处理如resize
def loadImage(fileName):
    img = Image.open(fileName)
    return img

#核心函数,把image对象转换成文本
def convert(img):
    color = "MNHQ$OC?7>!:-;." #自定义字符集
    length = len(color)
    w,h = img.size
    grey = img.convert('L') #转化为灰度图
    text = ''
    #依次遍历每个像素,把灰度图转化成文本
    for x in xrange(h):
        for y in xrange(w):
            pixel = grey.getpixel((y,x))
            if pixel==0:
                text += ' '
            else:  
                text += color[(pixel*length)/255-1] #减1是为了防止字符串越界
        text += '
'
    return text

#写文件,这里把结果用HTML呈现
def store(text):
    head= '''
            <html>
              <head>
                <style type="text/css">
                  body {font-family:Monospace; font-size:5px;}
                </style>
              </head>
            <body> '''
    tail = '</body></html>'
    html = head + text.replace('
','<br>') + tail 
    #写文件
    f = open('out.html','w')
    f.write(html)
    f.close()

def main():
    img = loadImage('./a.jpg')
    text = convert(img)
    store(text)    
    print "finish!"
if __name__=="__main__":
    main()

运行结果

a.jpg


out.html

效果非常理想,字符图还别有美感呢。

原文地址:https://www.cnblogs.com/fanghao/p/7441451.html