python用字符组成图像代码实例
程序员文章站
2022-06-14 23:19:50
目录一、特效预览二、程序原理三、程序源码总结一、特效预览处理前处理后细节放大后二、程序原理将图片所在的 256 的灰度映射到相应的字符上面也就是 rgb 值转成相应的字符然后再将字符其写入文件即可你听...
一、特效预览
处理前
处理后
细节放大后
二、程序原理
将图片所在的 256 的灰度映射到相应的字符上面
也就是 rgb 值转成相应的字符
然后再将字符其写入文件即可
你听懂了吗
三、程序源码
#!/usr/bin/env python # encoding: utf-8 from pil import image class charsetpicture: ''' this is a main class, the file contains all documents. one document contains paragraphs that have several sentences it loads the original file and converts the original file to new content then the new content will be saved by this class ''' def __init__(self): self.char = list("$@b%8&wm#*oahkbdpqwmzo0qlcjuyxzcvunxrjft/\|()1{}[]?-_+~<>i!li;:,\"^`'. ") self.width = 160 self.height = 60 def hello(self): ''' this is a welcome speech :return: self ''' print('*' * 50) print(' ' * 18 + '图片转换为字符图片') print(' ' * 5 + 'author: autofelix date: 2022-01-07 13:14') print('*' * 50) return self def get_char(self, r, g, b, alpha=256): ''' 将256灰度映射到70个字符上,也就是rgb值转字符的函数 :alpha: 透明度 :return: self ''' if alpha == 0: return ' ' length = len(self.char) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 + 1) / length return self.char[int(gray / unit)] def run(self): ''' the program entry ''' im = image.open('assets/aaa.jpeg') im = im.resize((self.width, self.height), image.nearest) txt = '' for i in range(self.height): for j in range(self.width): txt += self.get_char(*im.getpixel((j, i))) txt += '\n' print(txt) with open('handler.txt', 'w') as f: f.write(txt) if __name__ == '__main__': charsetpicture().hello().run()
总结
到此这篇关于python用字符组成图像代码实例的文章就介绍到这了,更多相关python字符组成图像内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 曾被华为卖掉的业务,将再次拯救华为?