Guest User

Untitled

a guest
Nov 18th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. from PIL import Image # 导入Pillow的Image模块
  2.  
  3. IMG = "/Users/fanyer/Downloads/b.png" # 需要处理掉的图片路径
  4. filePath = "/Users/fanyer/test/b.txt" # 处理结果的保存路径
  5. ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
  6. height = 45
  7. width = 100
  8.  
  9.  
  10. # 重点。将256灰度映射到70个字符上
  11. def get_char(r, g, b, alpha=256):
  12. if alpha == 0:
  13. return ' '
  14. length = len(ascii_char)
  15. gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) # 灰度转换公式,🉑以自己
  16.  
  17. unit = (256.0 + 1) / length # 比例
  18. inext = int(gray / unit) # 根据灰度求对应的index
  19. return ascii_char[inext]
  20.  
  21.  
  22. if __name__ == '__main__':
  23.  
  24. im = Image.open(IMG) # 读取图片
  25. im = im.resize((width, height), Image.NEAREST) # 调整图片的大小
  26.  
  27. txt = ""
  28. for i in range(height): # 遍历图片的像素点,获取每一个像素点的rgbA值
  29. for j in range(width):
  30. txt += get_char(*im.getpixel((j, i))) # 获得相应位置像素点的值组元(a,g,b,a)
  31. txt += '\n' # 换行
  32.  
  33. print(txt)
  34.  
  35. # 字符图输出到文件
  36. with open(filePath, 'w') as f: # 输出到指定文件
  37. f.write(txt)
Add Comment
Please, Sign In to add comment