缩放为黑白
转换为灰度,然后缩放为白色或黑色(以最接近的为准)。
原文:
结果:
Pure Pillow 实现
如果您还没有安装pillow:
$ pip install pillow
Pillow(或 PIL)可以帮助您有效地处理图像。
from PIL import Image
col = Image.open("cat-tied-icon.png")
gray = col.convert('L')
bw = gray.point(lambda x: 0 if x<128 else 255, '1')
bw.save("result_bw.png")
或者,您可以将Pillow 与numpy 一起使用。
Pillow + Numpy 位掩码方法
你需要安装 numpy:
$ pip install numpy
Numpy 需要一个数组的副本来操作,但是结果是一样的。
from PIL import Image
import numpy as np
col = Image.open("cat-tied-icon.png")
gray = col.convert('L')
# Let numpy do the heavy lifting for converting pixels to pure black or white
bw = np.asarray(gray).copy()
# Pixel range is 0...255, 256/2 = 128
bw[bw < 128] = 0 # Black
bw[bw >= 128] = 255 # White
# Now we put it back in Pillow/PIL land
imfile = Image.fromarray(bw)
imfile.save("result_bw.png")
黑白使用枕头,抖动
使用pillow 可以直接将其转换为黑白。它看起来像有灰色阴影,但你的大脑在欺骗你! (黑白相近看起来像灰色)
from PIL import Image
image_file = Image.open("cat-tied-icon.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('/tmp/result.png')
原文:
转换:
黑白使用 Pillow,无抖动
from PIL import Image
image_file = Image.open("cat-tied-icon.png") # open color image
image_file = image_file.convert('1', dither=Image.NONE) # convert image to black and white
image_file.save('/tmp/result.png')