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

如何用Python检测上传PDF文件中的缺失签名

检测PDF必填签名缺失的实现方案

针对你的需求,核心是实现is_signature_box_filled函数判断签名框是否有内容,再通过状态检查返回指定结果。以下是完整的实现代码和说明:

核心检测函数实现

签名框为空时通常是纯色(比如白色),有签名则会有更多像素变化。可以通过灰度化+计算非空白像素占比的方式判断:

from PIL import Image
import numpy as np

def is_signature_box_filled(cropped_image, threshold=0.02):
    # 转换为灰度图,简化像素计算
    gray_img = cropped_image.convert('L')
    # 转为numpy数组,方便统计像素
    pixel_array = np.array(gray_img)
    # 统计非白色(像素值<255)的像素数量
    non_white_count = np.sum(pixel_array < 255)
    # 计算非白色像素占总像素的比例
    fill_ratio = non_white_count / pixel_array.size
    
    # 占比超过阈值则判定为已签名
    return fill_ratio > threshold

完善完整逻辑

把你的代码补充完整,添加最终的缺失判断逻辑:

from PIL import Image
import numpy as np
from pdf2image import convert_from_path

def is_signature_box_filled(cropped_image, threshold=0.02):
    gray_img = cropped_image.convert('L')
    pixel_array = np.array(gray_img)
    non_white_count = np.sum(pixel_array < 255)
    fill_ratio = non_white_count / pixel_array.size
    return fill_ratio > threshold

def check_pdf_signatures(pdf_path):
    fields = {}
    try:       
        images = convert_from_path(pdf_path, dpi=200)
        print(f"[DEBUG] PDF has {len(images)} pages")

        if len(images) >= 1:
            target_page_index = 0  # 根据实际PDF调整目标页码
            page_image = images[target_page_index]
            page_image.save("debug_page0.png")

            # 签名区域坐标(根据debug图片确认后调整)
            inspector_sig_area = (510, 590, 650, 630)
            reviewer_sig_area  = (510, 640, 650, 680)

            inspector_crop = page_image.crop(inspector_sig_area)
            reviewer_crop  = page_image.crop(reviewer_sig_area)

            inspector_crop.save("debug_inspector_box.png")
            reviewer_crop.save("debug_reviewer_box.png")

            fields["Inspector Signed"] = is_signature_box_filled(inspector_crop)
            fields["Reviewer Signed"] = is_signature_box_filled(reviewer_crop)
            
            # 检查是否存在未签名的情况
            if not all(fields.values()):
                return "Signature missing."
            return "All signatures are present."
        else:
            print("[!] No pages found in PDF!")
            return "Signature missing."

    except Exception as e:
        print(f"[!] Signature box check failed: {e}")
        return "Signature missing."

# 调用示例
# result = check_pdf_signatures("your_target_pdf.pdf")
# print(result)

关键注意点

  • 阈值调整:threshold参数可以根据你的PDF签名框实际情况微调,空框的非空白像素占比通常很低,有签名时会明显上升。
  • 坐标校准:通过生成的debug_*.png图片确认签名区域坐标是否准确,确保裁剪范围覆盖完整的签名框。
  • 异常处理:所有异常分支都返回“Signature missing.”,符合需求中缺失签名时的返回要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:42:15