python用字符组成图像代码实例
作者:autofelix 时间:2023-09-15 02:12:04
一、特效预览
处理前
处理后
细节放大后
二、程序原理
将图片所在的 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()
来源:https://blog.csdn.net/weixin_41635750/article/details/122416621
标签:python,字符,图
0
投稿
猜你喜欢
XML 问题: 超越DOM(轻松使用 DOM 的技巧和诀窍)
2008-09-05 17:12:00
5种禁用html页面的缓存方法
2007-09-30 12:12:00
怎样在不同版本SQL Server中存储数据
2009-01-20 13:11:00
javascript同步服务器时间和同步倒计时小技巧
2023-08-27 22:10:58
文字适度阅读的宽度或者字数
2007-10-26 07:31:00
如何用表单在线建立目录?
2010-06-16 09:49:00
浅谈python中的面向对象和类的基本语法
2023-06-27 11:36:45
SQL Server中的执行引擎入门 图解
2012-06-06 20:08:26
剖析网页设计中的几何圆
2010-10-19 12:27:00
Golang实现断点续传功能
2023-07-24 08:19:26
自定义数据库自动编号初始值和步进值
2009-05-19 10:00:00
asp如何建立和删除文件夹?
2009-11-26 20:34:00
win10子系统python开发环境准备及kenlm和nltk的使用教程
2023-07-31 01:48:28
修改mysql最大连接数的方法
2010-03-09 13:57:00
详解Python数据可视化编程 - 词云生成并保存(jieba+WordCloud)
2023-08-22 18:03:06
JS实现合并json对象的方法
2023-08-29 15:09:30
智能录入表格[适合BS模式项目的录入页面]
2008-03-09 19:02:00
在ASP.NET 2.0中操作数据之五十五:编辑和删除现有的二进制数据
2023-07-10 02:05:43
解决PyCharm同目录下导入模块会报错的问题
2023-06-12 22:39:55
自动定时备份sqlserver数据库的方法
2011-11-03 17:28:17