做了個Python的小練習,網上有人是利用PIL中的Image來實現的,覺得Opencv庫挺方便的,於是利用Opencv庫來實現了一下,代碼如下:
# -*- coding: utf-8 -*-
# feimengjuan
# 實現將圖片轉爲字符畫
import cv2
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# 將灰度值轉爲字符
def get_char(gray_number):
length = len(ascii_char)
unit = (256.0 + 1)/length
return ascii_char[int(gray_number/unit)]
if __name__ == '__main__':
image1 = cv2.imread('8.jpg')
image = cv2.resize(image1,(85,110))
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
txt = ""
for i in range(image.shape[0]):
for j in range(image.shape[1]):
# 對打開的圖片的每個座標的灰度值做判斷,
# 用get_char()獲取該顏色灰度值對應的字符,然後拼接成字符串txt
txt += get_char(gray[i,j])
txt += '\n'
print txt
#字符畫輸出到文件中
f = open('output.txt','w')
f.write(txt)
結果是:
原圖片:
結果: