在Python中将图像转换为黑白与将图像转换为单色(灰度)

时间:2020-04-16 15:39:15

标签: python python-3.x image image-processing

我在filename = '1.png'下面有图片:

enter image description here

每当我尝试使用下面的代码将其转换为单色时,图像都与输入图像相同。

image_counter = 1
path = 'sample/' + str(image_counter) + '.png'
image = Image.open(path).convert('L')  # Convert it into monochrome.
image = Image.fromarray(image)
image.save('monochrome.png')  

单色输出:

enter image description here

但是当我将其转换为黑白图像时,输出会有所不同,并且不会产生直线边框。

image_counter = 1
path = 'sample/' + str(image_counter) + '.png'
image = Image.open(path).convert('1')  # Convert it into black and white.
image = Image.fromarray(image)
image.save('blackandwhite.png') 

enter image description here

放大后,您可以真正观察到不直的边框。

enter image description here

为什么?

1 个答案:

答案 0 :(得分:2)

将灰度(“ L”)或“ RGB”图像转换为 两级(模式“ 1”)图像使用Floyd-Steinberg抖动进行近似 原始图像的亮度水平。如果dither为NONE,则所有非零 值设置为255(白色)。

抖动方法,从模式“ RGB”转换为“ P”或从模式转换时使用 “ RGB”或“ L”到“ 1”。可用的方法为NONE或FLOYDSTEINBERG (默认)。