如何用python把图片字符画

Python017

如何用python把图片字符画,第1张

python字符画是一个简单有趣的小程序,非常适合初学者进行学(zhuang)习(bi)。python字符画生成的原理及其简单,一句话概括就是----将图片像素点用不同字符代替,从而将像素组成的图片转变成用字符组成的字符画为了尽可能的使得字符画展示效果与图片相同

# -*- coding: utf-8 -*-from PIL import Image

codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI:,"^`'. '''#生成字符画所需的字符集count = len(codeLib)def transform1(image_file):

image_file = image_file.convert("L")#转换为黑白图片,参数"L"表示黑白模式

codePic = ''

for h in range(0,image_file.size[1]): #size属性表示图片的分辨率,'0'为横向大小,'1'为纵向

for w in range(0,image_file.size[0]):

gray = image_file.getpixel((w,h)) #返回指定位置的像素,如果所打开的图像是多层次的图片,那这个方法就返回一个元组

codePic = codePic + codeLib[int(((count-1)*gray)/256)]#建立灰度与字符集的映射

codePic = codePic+'\r\n'

return codePicdef transform2(image_file):

codePic = ''

for h in range(0,image_file.size[1]):for w in range(0,image_file.size[0]):

g,r,b = image_file.getpixel((w,h))

gray = int(r* 0.299+g* 0.587+b* 0.114)

codePic = codePic + codeLib[int(((count-1)*gray)/256)]

codePic = codePic+'\r\n'

return codePic

fp = open(u'暴走.jpg','rb')

image_file = Image.open(fp)

image_file=image_file.resize((int(image_file.size[0]*0.75), int(image_file.size[1]*0.5)))#调整图片大小print u'Info:',image_file.size[0],' ',image_file.size[1],' ',count

tmp = open('tmp.txt','w')

tmp.write(transform1(image_file))

tmp.close()

python是数据统计分析软件,也只能用来对统计分析的结果数据进行绘图,以展示数据的某种趋势或数据项的分布(如折线图、直方图、饼图、散点图)。

你所说的字符画是一种什么样的图形?什么样的画?

你想要实现什么样的目标?