Skip to content

Instantly share code, notes, and snippets.

@Jamesits
Last active April 12, 2017 15:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Jamesits/ff2d0d39e85118c2ce5621dc84f068d9 to your computer and use it in GitHub Desktop.
Python 3 Pillow 把图像转换成灰度
#!/usr/bin/env python3
import sys
from PIL import Image
# 载入图像
im = Image.open(sys.argv[1])
im.show()
def makeGrayscale(im: 'Image.Image') -> 'Image.Image':
'''Reads a Pillow image and convert it to grayscale using brightness'''
# 获取图像长宽
width, height = im.size
# 复制一份图像
dest = im.copy()
# RGB 到亮度
def rgb2brightness(r: int, g: int, b: int) -> int:
'''Converts R, G, B value to brightness'''
return int(0.3 * r + 0.59 * g + 0.11 * b)
# 遍历图像的每一个像素
for i in range(width):
for j in range(height):
# 获取 RGB 各通道的值
# Tuple unpack 的时候最后写 *_ 表示忽略多出来的所有值
# 有些图像有超过三个通道(比如 PNG),不写的话会报
# ValueError: too many values to unpack
r, g, b, *_ = im.getpixel((i, j))
# 转换当前像素
brightness = rgb2brightness(r, g, b)
# 写到目标图片
dest.putpixel((i, j), (brightness, brightness, brightness))
return dest
im = makeGrayscale(im)
im.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment