欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python黑色的_python – 将RGB转换为黑色或白色

发布时间:2025/3/15 python 56 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python黑色的_python – 将RGB转换为黑色或白色 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

缩小到黑白

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

原版的:

结果:

纯枕实施

如果您还没有安装枕头:

$ pip install pillow

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

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 Bitmasks方法

你需要安装numpy:

$ pip install numpy

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

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可以将其直接转换为黑白。它会看起来像灰色阴影,但你的大脑欺骗你! (黑色和白色附近看起来像灰色)

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

总结

以上是生活随笔为你收集整理的python黑色的_python – 将RGB转换为黑色或白色的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。