一个去掉PDF背景水印的思路

起因

昨天测试 使用"https://github.com/VikParuchuri/marker" 将 pdf 转 Markdown的过程中,发现转换后的文件中会保护一些背景图片,是转换过程中,程序把背景图识别为了内容。于是想着怎么把背景图片去掉。

背景水印图片的特征

我这里拿到的PDF图片都是文字类型的,背景水印应该都是后期加进去的。

总结出两个特征:

  • 每页都存在相同的背景图片
  • 作为背景覆盖了页面大部分区域

基于上面的特征,写代码将背景移除

  • 代码:
python 复制代码
import fitz

def scan_background_images(pdf_path):
    doc = fitz.open(pdf_path)
    num_pages = len(doc)
    image_usage = {}  # 字典来记录每个图片的使用情况和页面面积覆盖

    # 遍历文档中的每一页
    for page in doc:
        page_area = abs(page.rect)  # 计算页面面积
        images = page.get_images(full=True)

        for img in images:
            xref = img[0]
            img_rect = page.get_image_rects(xref)
            img_area = sum([abs(rect) for rect in img_rect])  # 计算该图片在当前页面的总覆盖面积

            if img_area / page_area >= 0.5:  # 判断是否覆盖了超过50%的页面面积
                if xref in image_usage:
                    image_usage[xref]['count'] += 1
                    image_usage[xref]['pages'].add(page.number)
                else:
                    image_usage[xref] = {'count': 1, 'pages': set([page.number])}

    # 确定在至少80%的页面上重复出现的图片
    background_images = []
    threshold = 0.8 * num_pages  # 计算至少需要出现在多少页面上

    for xref, data in image_usage.items():
        if data['count'] >= threshold:
            background_images.append(xref)

    # 移除背景图片
    for page in doc:
        for xref in background_images:
            page.clean_contents()  # 清理页面内容,准备删除操作
            page.delete_image(xref)

    # 保存修改后的PDF
    new_pdf_path = pdf_path.replace('.pdf', '_no_bg.pdf')
    doc.save(new_pdf_path)
    doc.close()

    return new_pdf_path

# 使用函数
pdf_path = "example.pdf"
new_pdf_path = scan_background_images(pdf_path)
print("Modified PDF saved to:", new_pdf_path)
  • 依赖
bash 复制代码
pip install PyMuPDF

效果

  • 去背景前
  • 去背景后
相关推荐
随手工具-Excel, pdf, SQL2 天前
PDF拆分怎么操作?免费在线拆分PDF文件,无需安装任何软件
pdf
正在走向自律2 天前
实战心得:利用PaddleOCR彻底解决大模型无法解析图片型PDF的问题
开发语言·pdf·视觉检测·paddleocr·视觉模型·离线ocr识别
AI原来如此2 天前
零基础教程:50页PDF一键浓缩成1页摘要
人工智能·ai·pdf·大模型
186******205312 天前
PDF 转 Word 高效办公实战指南
pdf·word
随手工具-Excel, pdf, SQL2 天前
PDF删除页面怎么操作?免费在线删除PDF指定页面,无需安装软件
pdf
SunnyDays10112 天前
Java 实现 PDF 页面删除、排序、旋转和裁剪
java·pdf
zyplayer-doc3 天前
个人 AI 知识库怎么搭建:用 zyplayer-doc 把笔记、PDF 和图片资料变成可问答的第二大脑
大数据·开发语言·人工智能·笔记·pdf·ocr
日日行不惧千万里3 天前
Java AI 完整学习笔记
pdf
听风吹等浪起3 天前
002:多图合并导出PDF【网页版】
计算机视觉·pdf
꯭爿꯭巎꯭4 天前
新概念英语第二册(PDF + MP3音频)免费下载
pdf·音视频·语音识别