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

如何用Python库移除灰度图像阈值以下像素以保留前景文字

过滤灰度图背景文字保留前景的实现方案

优先使用PIL的方案(结合scikit-image自动阈值)

PIL本身没有内置自动阈值计算功能,我们可以结合scikit-image的Otsu自动阈值算法实现需求,全程无需手动设置像素值:

  1. 安装依赖:
pip install pillow scikit-image numpy
  1. 实现代码:
from PIL import Image
import numpy as np
from skimage.filters import threshold_otsu

# 打开图像并转为灰度图(若原图已是灰度图,convert("L")可省略)
img = Image.open("jFmbt.jpg").convert("L")
# 转换为numpy数组以便处理
img_array = np.array(img)

# 自动计算最佳分割阈值(Otsu算法)
threshold = threshold_otsu(img_array)
# 根据阈值生成二值图:若前景文字灰度高于背景,将`<`改为`>`即可
binary_array = img_array < threshold
# 转回PIL图像并保存/显示
result_img = Image.fromarray((binary_array * 255).astype(np.uint8))
result_img.save("filtered_result.jpg")
result_img.show()

Otsu算法会自动分析图像灰度直方图,找出能最大化前景与背景类间方差的阈值,无需手动调整参数。

更简便的OpenCV方案

若能接受其他库,OpenCV内置了Otsu阈值实现,代码更简洁:

  1. 安装依赖:
pip install opencv-python
  1. 实现代码:
import cv2

# 直接读取为灰度图
gray_img = cv2.imread("jFmbt.jpg", cv2.IMREAD_GRAYSCALE)
# 自动执行Otsu阈值二值化,返回值分别为计算出的阈值、二值化图像
_, binary_img = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 保存结果
cv2.imwrite("filtered_result_opencv.jpg", binary_img)
# 显示结果
cv2.imshow("Filtered Result", binary_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

注意事项

如果自动阈值结果不理想(比如前景背景灰度差异过小),可先做降噪处理:

  • PIL可使用img.filter(ImageFilter.MedianFilter(size=3))
  • OpenCV可使用cv2.medianBlur(gray_img, 3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:30:55