Created
November 19, 2018 03:45
-
-
Save fanyer/8ab2338c84e2b30f1a677cf4ba24090f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image # 导入Pillow的Image模块 | |
IMG = "/Users/fanyer/Downloads/b.png" # 需要处理掉的图片路径 | |
filePath = "/Users/fanyer/test/b.txt" # 处理结果的保存路径 | |
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") | |
height = 45 | |
width = 100 | |
# 重点。将256灰度映射到70个字符上 | |
def get_char(r, g, b, alpha=256): | |
if alpha == 0: | |
return ' ' | |
length = len(ascii_char) | |
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) # 灰度转换公式,🉑以自己 | |
unit = (256.0 + 1) / length # 比例 | |
inext = int(gray / unit) # 根据灰度求对应的index | |
return ascii_char[inext] | |
if __name__ == '__main__': | |
im = Image.open(IMG) # 读取图片 | |
im = im.resize((width, height), Image.NEAREST) # 调整图片的大小 | |
txt = "" | |
for i in range(height): # 遍历图片的像素点,获取每一个像素点的rgbA值 | |
for j in range(width): | |
txt += get_char(*im.getpixel((j, i))) # 获得相应位置像素点的值组元(a,g,b,a) | |
txt += '\n' # 换行 | |
print(txt) | |
# 字符图输出到文件 | |
with open(filePath, 'w') as f: # 输出到指定文件 | |
f.write(txt) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment