初學(xué)Python,在網(wǎng)上看到Python圖片轉(zhuǎn)字符畫的教程,我也來嘗試下。
首先我們要用到Python的PIL庫的Image模塊,PIL(Python Imaging Library)庫是Python的一個(gè)圖像處理庫。想了解PIL的詳細(xì)功能介紹,可參考PIL的官方文檔(雖然我也沒看過,不過還是貼上來):http://effbot.org/imagingbook/
圖片轉(zhuǎn)字符畫的關(guān)鍵思想是將圖片的灰度值與你自己設(shè)定的字符集之間建立映射關(guān)系,不同區(qū)間的灰度值對(duì)應(yīng)不同的字符,之后將圖片每一個(gè)像素對(duì)應(yīng)的字符打印出來就是我們要的字符畫啦~
這里提供兩種方法:
先將彩色圖片轉(zhuǎn)換為黑白圖片,然后直接將每個(gè)像素點(diǎn)的灰度值與字符集建立映射。
獲取圖片的RGB值,利用公式:
1
|
Gray = R * 0.299 + G * 0.587 + B * 0.114 |
計(jì)算可得每個(gè)像素點(diǎn)的灰度值,之后再建立映射即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# -*- coding: utf-8 -*- from PIL import Image codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. ''' #生成字符畫所需的字符集 count = len (codeLib) def transform1(image_file): image_file = image_file.convert( "L" ) #轉(zhuǎn)換為黑白圖片,參數(shù)"L"表示黑白模式 codePic = '' for h in range ( 0 ,image_file.size[ 1 ]): #size屬性表示圖片的分辨率,'0'為橫向大小,'1'為縱向 for w in range ( 0 ,image_file.size[ 0 ]): gray = image_file.getpixel((w,h)) #返回指定位置的像素,如果所打開的圖像是多層次的圖片,那這個(gè)方法就返回一個(gè)元組 codePic = codePic + codeLib[ int (((count - 1 ) * gray) / 256 )] #建立灰度與字符集的映射 codePic = codePic + '\r\n' return codePic def transform2(image_file): codePic = '' for h in range ( 0 ,image_file.size[ 1 ]): for w in range ( 0 ,image_file.size[ 0 ]): g,r,b = image_file.getpixel((w,h)) gray = int (r * 0.299 + g * 0.587 + b * 0.114 ) codePic = codePic + codeLib[ int (((count - 1 ) * gray) / 256 )] codePic = codePic + '\r\n' return codePic fp = open (u '暴走.jpg' , 'rb' ) image_file = Image. open (fp) image_file = image_file.resize(( int (image_file.size[ 0 ] * 0.75 ), int (image_file.size[ 1 ] * 0.5 ))) #調(diào)整圖片大小 print u 'Info:' ,image_file.size[ 0 ], ' ' ,image_file.size[ 1 ], ' ' ,count tmp = open ( 'tmp.txt' , 'w' ) tmp.write(transform1(image_file)) tmp.close() |
原圖
轉(zhuǎn)換為字符畫(注:在記事本打開時(shí)記得取消自動(dòng)換行,下圖字體:宋體 字號(hào):小六)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/wait_nothing_alone/article/details/52901531