python 使图片变灰
参考博客: https://www.cnblogs.com/zhangjiansheng/p/6925722.html
# coding=gbk from PIL import Image # 灰度策略 def strategy_avg(r, g, b): return int((r + g + b) / 3) def strategy_seven(r, g, b): return int((r*38 + g*75 + b*15) >> 7) # 灰度转换 def imageToGray(strategy): # 读取图片 im = Image.open("test.jpg") width = im.size[0] height = im.size[1] im = im.convert('RGB') for x in range(width): for y in range(height): r, g, b = im.getpixel((x, y)) # 灰度策略 avg = strategy(r, g, b) im.putpixel((x, y), (avg, avg, avg)) # 展示转换结果 im.show() imageToGray(strategy_seven)
原图:(来自网图)
灰度后: