iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python用字符组成图像代码实例
  • 110
分享到

python用字符组成图像代码实例

2024-04-02 19:04:59 110人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录 一、特效预览二、程序原理三、程序源码总结 一、特效预览 处理前 处理后 细节放大后 二、程序原理 将图片所在的 256 的灰度映射到相应的字符上面 也

 一、特效预览

处理前

处理后

细节放大后

二、程序原理

将图片所在的 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字符组成图像内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: python用字符组成图像代码实例

本文链接: https://www.lsjlt.com/news/162140.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作