缩放为黑白
转换为灰度,然后缩放为白色或黑色(以最接近的为准)。
原来的:

结果:

纯枕头实现
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')
原来的:

转换:

黑白使用枕头,没有抖动
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')