Last active
April 12, 2017 15:02
Star
You must be signed in to star a gist
Python 3 Pillow 把图像转换成灰度
This file contains 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
#!/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