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
相关产品推荐
相关产品推荐

