[关闭]
@sevenup233 2019-03-03T13:09:19.000000Z 字数 1074 阅读 595

Python PIL库

PY


图像处理库:PIL(Python Imaging Library)
官方教程:http://www.effbot.org/imagingbook/

功能

对整体:打开,保存,调色,变形(简单功能的PS)
对单点:获取每个像素信息,逐一修改

案例(图片转字符画)

流程:
【黑白可输出txt】打开图像--》获取图片每个像素的灰度--》根据灰度输出字符到txt文件
【彩色只能输出图片】打开图像--》获取图片每个像素的灰度&颜色--》根据灰度输出字符到txt文件--》根据颜色吧字符绘制成图片文件
【彩色也可能输出txt】但是py的word插件没有找到设定输出文本颜色的功能

  1. #定义输出的字符
  2. ascii_char = list("@&*.o ")
  3. #读取图片的信息(名称、宽高)
  4. IM=Image.open(xxx)
  5. WIDTG=im.size[0]
  6. HEIGHT=im.size[1]
  7. #灰度与字符对应
  8. def get_char(r,g,b,alpha = 256):
  9. #透明
  10. if alpha == 0:
  11. return ' '
  12. length = len(ascii_char)
  13. #灰度计算
  14. gray = int(0.2126*r+0.7152*g+0.0722*b)
  15. #灰度区间
  16. unit = (256.0+1)/length
  17. #返回这个像素对应的灰度对应的字符
  18. return ascii_char[int(gray/unit)]
  19. #暂存文本
  20. txt = ""
  21. #暂存颜色
  22. colors = []
  23. #遍历每个像素,记录像素颜色信息和对应灰度的字符
  24. for i in range(HEIGHT):
  25. for j in range(WIDTH):
  26. pixel = im.getpixel((j,i))
  27. txt += get_char(*pixel
  28. #记录像素颜色信息
  29. colors.append((pixel[0],pixel[1],pixel[2]))
  30. txt += '\n'
  31. colors.append((0,0,0))
  32. #只要字符可以用文本模块输出txt到txt
  33. #需要上色用ImageDraw为每个字符进行上色
  34. #字符大小
  35. font_h=12
  36. font_w=12
  37. #上色,输出图片
  38. dr = ImageDraw.Draw(newim)
  39. newim = Image.new("RGB",(940,400),(0,0,0))
  40. for i in range(len(txt)):
  41. if(txt[i]=='\n'):
  42. x+=font_h
  43. y=-font_w
  44. dr.text([y,x],txt[i],colors[i])
  45. y+=font_w
  46. newim.save("output.png", encoding='utf-8')
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注