有没有一种方法可以将图像逐像素转换为黑白像素? [英] Is there a way to convert an image to black and white pixel by pixel?

查看:344
本文介绍了有没有一种方法可以将图像逐像素转换为黑白像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在非常浅的灰色上使用image = image.convert("1")时,它将添加少量黑色像素以将其平均"出来.我正在寻找一种可以查看每个像素并确定该像素是更接近黑色还是接近白色的东西.

When using image = image.convert("1") on a very light grey, it'll add little black pixels to "average" it out. I'm looking for something that just looks at every individual pixel and determines whether that pixel is closer to black or to white.

推荐答案

请注意

将灰度("L")或"RGB"图像转换为双级(模式"1")图像的默认方法是使用Floyd-Steinberg抖动来近似原始图像的亮度水平.如果dither为NONE,则将所有大于128的值设置为255(白色),将所有其他值设置为0(黑色).要使用其他阈值,请使用 point() 方法.

The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all values larger than 128 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the point() method.

因此,您实际上不希望抖动,并且在转换时必须显式设置此选项:

So, you actually want no dithering and must set this option explicitly when converting:

from matplotlib import pyplot as plt
import numpy as np
from PIL import Image

# Grayscale image as NumPy array with values from [0 ... 255]
image = np.reshape(np.tile(np.arange(256, dtype=np.uint8), 256), (256, 256))

# PIL grayscale image with values from [0 ... 255]
image_pil = Image.fromarray(image, mode='L')

# PIL grayscale image converted to mode '1' without dithering
image_pil_conv = image_pil.convert('1', dither=Image.NONE)

# Threshold PIL grayscale image using point with threshold 128 (for comparison)
threshold = 128
image_pil_thr = image_pil.point(lambda p: p > threshold and 255)

# Result visualization
plt.figure(1, figsize=(9, 8))
plt.subplot(2, 2, 1), plt.imshow(image, cmap=plt.gray()), plt.ylabel('NumPy array')
plt.subplot(2, 2, 2), plt.imshow(image_pil, cmap=plt.gray()), plt.ylabel('PIL image')
plt.subplot(2, 2, 3), plt.imshow(image_pil_conv, cmap=plt.gray()), plt.ylabel('PIL image converted, no dithering')
plt.subplot(2, 2, 4), plt.imshow(image_pil_thr, cmap=plt.gray()), plt.ylabel('PIL image thresholded')
plt.tight_layout()
plt.show()

文档也不精确:实际上,对于convertpoint来说,所有大于OR EQUAL 128的值都设置为白色.这很有意义,因为[0 ... 127]是128个值,而[128 ... 255]是128个值.

The documentation is also imprecise: Actually, all values greater than OR EQUAL 128 are set to white, both for convert as well as for point – which makes sense, since [0 ... 127] are 128 values, and [128 ... 255] are 128 values.

希望有帮助!

这篇关于有没有一种方法可以将图像逐像素转换为黑白像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆