#在PIL中,从模式“RGB”转换为“L”模式(灰度模式) Gray = 0.299R+0.587G+0.114B
[0.0, 9.8)这|a [9.8, 19.6)|b [19.6, 29.4)|c ...|... [225.6, 235.4]|x [235.4, 245.2]|y [245.2, 255.0]|z
char_string = 'abcdefghijklmnopqrstuvwxyz' def rgb2char(r, g, b): length = len(char_string) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) # 每个字符对应的gray值区间宽度 unit = (256.0 + 1) / length # gray值对应到char_string中的位置(索引值) idx = int(gray / unit) return char_string[idx]
from PIL import Image
#预处理(将图片尺寸压缩,并转为灰度图)
def preprocess(img_path,delta=100):
img = Image.open(img_path)
# 获取图片尺寸
width, height = img.size
# 获取图片最大边的长度 if width > height:
max = width
else:
max = height
# 伸缩倍数scale
scale = max / delta
width, height = int(width / scale), int(height / scale)
img = img.resize((width, height))
return img def img2char(img_obj, savepath):
txt = ''
width, height = img_obj.size
# 获取像素点的rgb元组值,如(254, 0, 0),并将其转化为字符
for i in range(height):
line = ''
for j in range(width):
line += rgb2char(*img_obj.getpixel((j, i)))
txt = txt + line + '\n'
# 保存字符画
with open(savepath, 'w+', encoding='utf-8') as f:
f.write(txt)
img_obj = preprocess(img_path)
img2char(img_obj, savepath) 插入图片
更改char_string,变换你想要的效果
以上就是如何利用Python实现图片转字符画详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于如何利用Python实现图片转字符画详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did81783