Nei*_*eil 5 python python-imaging-library binary-image
我想对 png 图像进行二值化。如果可能的话我想使用枕头。我见过使用两种方法:
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
Run Code Online (Sandbox Code Playgroud)
此方法似乎通过抖动图像来处理填充浅色的区域。我不想要这种行为。例如,如果有一个浅黄色圆圈,我希望它变成一个黑色圆圈。
更一般地说,如果像素的 RGB 是 (x,y,z),如果 x<=t OR y<=t OR z<=t 对于某个阈值 0<t<255,我希望像素变黑
我可以将图像转换为灰度或 RGB,然后手动应用阈值测试,但这似乎效率低下。
我见过的第二种方法是这样的:
threshold = 100
im = im2.point(lambda p: p > threshold and 255)
Run Code Online (Sandbox Code Playgroud)
从这里我不知道这是如何工作的,也不知道阈值是什么或在这里做什么以及“and 255”做什么。
我正在寻找如何应用方法 2 的解释或使用 Pillow 的替代方法。
Tim*_*rts 15
我认为你需要转换为灰度,应用阈值,然后转换为单色。
image_file = Image.open("convert_iamge.png")
# Grayscale
image_file = image_file.convert('L')
# Threshold
image_file = image_file.point( lambda p: 255 if p > threshold else 0 )
# To mono
image_file = image_file.convert('1')
Run Code Online (Sandbox Code Playgroud)
表达式“p > threshhold and 255”是一个 Python 技巧。“a和b”的定义是“如果a为假则为a,否则为b”。因此,这将为每个像素生成“False”或“255”,并且“False”将被评估为 0。我的 if/else 以可能更易读的方式执行相同的操作。
| 归档时间: |
|
| 查看次数: |
12879 次 |
| 最近记录: |