溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python用字符組成圖像代碼怎么寫

發(fā)布時(shí)間:2022-01-11 11:20:16 來源:億速云 閱讀:161 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“python用字符組成圖像代碼怎么寫”,在日常操作中,相信很多人在python用字符組成圖像代碼怎么寫問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”python用字符組成圖像代碼怎么寫”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

 一、特效預(yù)覽

python用字符組成圖像代碼怎么寫

處理前

python用字符組成圖像代碼怎么寫

處理后

python用字符組成圖像代碼怎么寫

細(xì)節(jié)放大后

二、程序原理

將圖片所在的 256 的灰度映射到相應(yīng)的字符上面

也就是 RGB 值轉(zhuǎn)成相應(yīng)的字符

然后再將字符其寫入文件即可

你聽懂了嗎 

三、程序源碼

#!/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 + '圖片轉(zhuǎn)換為字符圖片')
        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個(gè)字符上,也就是RGB值轉(zhuǎn)字符的函數(shù)
        :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()

到此,關(guān)于“python用字符組成圖像代碼怎么寫”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI