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 += '\n'
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('\n','<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 += '\n'
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('\n','<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

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

最新文章

  1. BPM配置故事之案例14-数据字典与数据联动
  2. plsql配置数据库连接
  3. 基础笔记10(IO 1.7try-with-resource) 装饰模式
  4. Firebird数据库的Select语句
  5. javascript基础之打印乘法表
  6. 一个null引发的错误
  7. linux库列表
  8. [Xamarin.Android] ActionBar Tips
  9. (转载)Apache下error.log文件太大的处理
  10. ios开发之数据的持久化存储机制
  11. C#程序员整理的Unity 3D笔记(十):Unity3D的位移、旋转的3D数学模型
  12. 329. Longest Increasing Path in a Matrix
  13. careercup-链表 2.7
  14. GeoHash核心解析
  15. [bzoj3124] [Sdoi2013]直径
  16. PHP 5 MySQLi 函数
  17. Gradle笔记——关于Gradle 1.12
  18. PyCharm 如何远程连接服务器编写程序
  19. pg数据库查询表大小
  20. zepto中的属性设置

热门文章

  1. office web apps搭建与解决方案
  2. gradle构建时跳过指定tests
  3. jquery toast插件
  4. [转] Node.js中package.json中库的版本号详解(^和~区别)
  5. delphi TreeView 从数据库添加节点的四种方法
  6. bzoj 4621: Tc605 动态规划
  7. C# 之 提高WebService性能大数据量网络传输处理
  8. js,JQuery 生成二维码
  9. 052 kafka对topic的增删改查操作
  10. Noj - 在线强化训练4