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

如何使用Python检测扫描得到的PNG页面是否为空?

检测PNG空白扫描页的Python方法

以下是两种简单有效的实现方案,适配不同扫描场景:

方法一:使用Pillow库(轻量快速)

Pillow是Python最常用的图像处理库,适合快速实现基础空白页检测。核心逻辑是:空白页的像素值分布高度集中(几乎全白),因此通过像素方差(衡量离散程度)和均值(衡量整体亮度)即可判断。

  • 先安装依赖:pip install pillow
  • 代码实现:
from PIL import Image
import numpy as np

def is_blank_page_pillow(image_path, var_threshold=10, mean_threshold=245):
    with Image.open(image_path) as img:
        # 转为灰度图简化计算
        gray_img = img.convert('L')
        pixel_arr = np.array(gray_img)
        # 计算像素方差和均值
        pixel_var = np.var(pixel_arr)
        pixel_mean = np.mean(pixel_arr)
        # 方差越小说明像素越一致,均值越高说明越接近纯白
        return pixel_var < var_threshold and pixel_mean > mean_threshold

# 测试
print(is_blank_page_pillow("blank_scan.png"))  # 空白页返回True
print(is_blank_page_pillow("content_scan.png"))  # 非空白返回False
  • 参数调整建议:若扫描页有轻微噪点,可把var_threshold调高到20;若纸张偏黄,把mean_threshold调低到230。

方法二:使用OpenCV库(适配带噪点/阴影的扫描页)

如果扫描页存在轻微阴影、斑点噪点,OpenCV的二值化处理能更精准过滤干扰,通过统计非白色像素数量判断是否空白。

  • 先安装依赖:pip install opencv-python
  • 代码实现:
import cv2
import numpy as np

def is_blank_page_cv2(image_path, non_white_limit=100):
    img = cv2.imread(image_path)
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 二值化:将接近白色的像素置为255,其余为0
    _, binary_img = cv2.threshold(gray_img, 240, 255, cv2.THRESH_BINARY)
    # 统计非白色像素的总数
    non_white_count = np.sum(binary_img == 0)
    # 非白色像素极少则判定为空白页
    return non_white_count < non_white_limit

# 测试
print(is_blank_page_cv2("blank_scan.png"))  # 空白页返回True
print(is_blank_page_cv2("content_scan.png"))  # 非空白返回False
  • 参数调整建议:若扫描页阴影明显,把二值化阈值240调低到220;若噪点多,把non_white_limit调高到500。

实用提示

  • 批量处理时,可遍历文件夹中的PNG文件,逐个调用检测函数。
  • 若扫描页有固定边框,可先裁剪边框区域再检测,避免边框干扰结果。
  • 建议用一批实际的空白/非空白扫描页测试,调整到最适合自己场景的参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:45:33