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

查看:595
本文介绍了将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:

Install pillow if you haven't already:

$ pip install 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")

或者,您可以将枕头 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")

使用枕头的黑色和白色,并带有抖动

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

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天全站免登陆