python用字符組成圖像代碼實例

 一、特效預覽

處理前

處理後

細節放大後

二、程序原理

將圖片所在的 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字符組成圖像內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: