You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python PIL:修改Image.convert()从L转1模式的阈值(默认127)

自定义阈值将灰度图转为纯黑白"1"模式

直接使用convert("1")时,PIL默认以127作为阈值划分黑白,要改成220的话,可以通过两种方式实现:

  • 方法一:使用ImageOps的阈值工具
    借助ImageOps.threshold()可以直接指定阈值,将灰度图中高于阈值的像素转为白色,低于的转为黑色,再转为"1"模式即可:

    from PIL import Image, ImageOps
    
    img = Image.open("img.jpg")
    # 设置阈值为220
    thresholded_img = ImageOps.threshold(img, 220)
    result = thresholded_img.convert("1")
    result.save("result.jpg")
    
  • 方法二:用point函数自定义像素映射
    通过lambda表达式手动定义灰度值的转换规则,再转为"1"模式:

    from PIL import Image
    
    img = Image.open("img.jpg")
    threshold = 220
    # 灰度值>=220转为白色(255),否则转为黑色(0)
    result = img.point(lambda x: 255 if x >= threshold else 0).convert("1")
    result.save("result.jpg")
    

两种方法都能实现仅保留灰度值≥220的最亮像素为白色,其余转为黑色的效果。

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 08:36:30