python图片转彩色字符代码_python 图片转字符(然并卵)

python 图片转字符(然并卵)

代码非常非常简单不做详细说明。

主要逻辑就是将图片转为灰度图,然后遍历像素获取灰度值匹配对应的字符,将拼接好的字符串输出到记事本文件。

(代码提供了两个方法,其实都差不多;记事本打开时要去掉自动换行,缩小字体大小,我打开是用宋体打开的)

1.[代码][Python]代码

from PIL import Image

import os

serarr=['@','#','$','%','&','?','*','o','/','{','[','(','|','!','^','~','-','_',':',';',',','.','`',' ']

count=len(serarr)

def toText(image_file):

image_file=image_file.convert("L")#转灰度

asd =''#储存字符串

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

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

gray =image_file.getpixel((w,h))

asd=asd+serarr[int(gray/(255/(count-1)))]

asd=asd+'\r\n'

return asd

def toText2(image_file):

asd =''#储存字符串

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

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

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

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

asd=asd+serarr[int(gray/(255/(count-1)))]

asd=asd+'\r\n'

return asd

image_file = Image.open("convert.jpg") # 打开图片

image_file=image_file.resize((int(image_file.size[0]*0.9), int(image_file.size[1]*0.5)))#调整图片大小

print u'Info:',image_file.size[0],' ',image_file.size[1],' ',count

try:

os.remove('./tmp.txt')

except WindowsError:

pass

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

tmp.write(toText2(image_file))

tmp.close()

2.[图片] convert.jpg

18110707_1rKb.jpg

3.[图片] 111.png

18110707_vn2b.png

4.[代码]话说灰度值是0~256吗?!改了一下。反正我这里没问题。

#!/usr/bin/python

# -*- coding: UTF-8 -*-

from PIL import Image

import os

serarr='''@#$%&?*aeoc=

count=len(serarr)

def toText(image_file):#此函数不能输入 gif 文件

image_file=image_file.convert("L")#转灰度

asd =''#储存字符串

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

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

gray =image_file.getpixel((w,h))

asd=asd+serarr[int(gray/(256/(count)))]

asd=asd+'\r\n'

return asd

def toText2(image_file):

asd =''#储存字符串

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

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

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

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

asd=asd+serarr[int(gray/(256/(count)))]

asd=asd+'\r\n'

return asd

image_file = Image.open("hehe.jpg") # 打开图片

image_file=image_file.resize((int(image_file.size[0]*0.9), 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(toText(image_file))

tmp.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值