Tom*_*Tom 39 python opencv numpy python-imaging-library
我如何在Python中拍摄RGB图像并将其转换为黑色或白色?不是灰度,我希望每个像素都是全黑(0,0,0)或全白(255,255,255).
在流行的Python图像处理库中是否有任何内置功能?如果没有,那么最好的方法就是循环每个像素,如果它接近白色则将其设置为白色,如果它接近黑色则将其设置为黑色?
Kyl*_*ley 87
转换为灰度,然后缩放为白色或黑色(以最接近的为准).
原版的:

结果:

pillow如果您还没有安装:
$ pip install 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:
$ 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")
使用枕头,您可以直接将其转换为黑色和白色.看起来它有灰色阴影,但你的大脑却在欺骗你!(黑色和白色彼此看起来像灰色)
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')
我建议转换为灰度,然后简单地对其应用阈值(一半,或者平均值或中值,如果您选择的话)。
from PIL import Image
col = Image.open('myimage.jpg')
gry = col.convert('L')
grarray = np.asarray(gry)
bw = (grarray > grarray.mean())*255
imshow(bw)
| 归档时间: | 
 | 
| 查看次数: | 58668 次 | 
| 最近记录: |