关于原始问题,这是最短的版本,对我有用:
Image.fromarray(255 * np.ones((100, 100), np.uint8), '1')
我得到了正确的全白图像。
正如前面指出的 https://stackoverflow.com/a/59082917/11089932,当转换为模式“1”时,抖动 https://en.wikipedia.org/wiki/Dither默认情况下已激活。所以,也许模式“1”的目的正是:提供一种快速创建抖动图像的方法。让我们看这个简短的例子:
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
plt.figure(1, figsize=(15, 5))
# Open some image
img = Image.open('path/to/your/image.png')
plt.subplot(1, 3, 1), plt.imshow(img)
# Convert to '1'; dithering activated by default
plt.subplot(1, 3, 2), plt.imshow(img.convert('1'))
# Convert to '1'; dithering deactivated
plt.subplot(1, 3, 3), plt.imshow(img.convert('1', dither=Image.NONE))
plt.tight_layout()
plt.show()
这就是输出:
当抖动图像足够小时,它看起来很像普通的灰度图像。当禁用抖动时(右图),您实际上会得到一个阈值图像,其中所有 >= 128 的值都设置为白色,否则设置为黑色。
希望有帮助!
-----------------------
System information
-----------------------
Python: 3.8.1
Matplotlib: 3.2.0rc1
NumPy: 1.18.1
Pillow: 7.0.0
-----------------------