将 RGB 转换为黑色或白色 [英] Convert RGB to black OR white

查看:87
本文介绍了将 RGB 转换为黑色或白色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中获取 RGB 图像并将其转换为黑色或白色?不是灰度,我希望每个像素要么全黑(0、0、0)要么全白(255、255、255).

How would I take an RGB image in Python and convert it to black OR white? Not grayscale, I want each pixel to be either fully black (0, 0, 0) or fully white (255, 255, 255).

在流行的 Python 图像处理库中是否有任何内置功能?如果不是,最好的方法是循环遍历每个像素,如果它更接近白色将其设置为白色,如果它更接近黑色将其设置为黑色?

Is there any built-in functionality for this in the popular Python image processing libraries? If not, would the best way be just to loop through each pixel, if it's closer to white set it to white, if it's closer to black set it to black?

推荐答案

缩放到黑白

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

Scaling to Black and White

Convert to grayscale and then scale to white or black (whichever is closest).

原文:

结果:

如果您还没有安装 pillow:

$ pip install pillow

Pillow(或 PIL)可以帮助您有效地处理图像.

Pillow (or PIL) can help you work with images effectively.

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麻木.

Alternatively, you can use Pillow with numpy.

您需要安装 numpy:

You'll need to install numpy:

$ pip install numpy

Numpy 需要一个数组的副本来操作,但结果是一样的.

Numpy needs a copy of the array to operate on, but the result is the same.

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 的黑白,带有抖动

使用枕头,您可以将其直接转换为黑白.它看起来像是有灰色阴影,但你的大脑在欺骗你!(黑白相近的看起来像灰色)

Black and White using Pillow, with dithering

Using pillow you can convert it directly to black and white. It will look like it has shades of grey but your brain is tricking you! (Black and white near each other look like grey)

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')

这篇关于将 RGB 转换为黑色或白色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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