欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)為PDF大文件批量去除水印

 更新時(shí)間:2023年05月23日 09:04:41   作者:力語  
在閱讀過程中如果遇到一些帶有水印的資料是比較煩心的,而市面上去水印的功能有多要收費(fèi)且很不方便,那么,如何通過Python來對(duì)這類圖片水印進(jìn)行去除呢,本文就來和大家分享一下實(shí)現(xiàn)方法吧

導(dǎo)入

在閱讀過程中如果遇到一些帶有水印的資料是比較煩心的,如下圖所示,水印以及類似的內(nèi)容會(huì)影響我們的閱讀體驗(yàn),而市面上去水印的功能有多要收費(fèi)且很不方便,那么,如何通過Python來對(duì)這類圖片水印進(jìn)行去除呢?

適用場(chǎng)景:本教程適合批量去除文件量較大的PDF文檔內(nèi)的圖片水印。

使用軟件:Python;

需安裝第三方庫:PIL,fitzpymupdf

pip install PIL
pip install fitz
pip install pymupdf

不說廢話,先把代碼貼在前面。

from PIL import Image
import fitz
import os
def replace_color(img_path):
    new_color = (255, 255, 255, 255)
    for filename in os.listdir(img_path):
        image = Image.open(os.path.join(img_path, filename))
        new_pixels = [new_color if pixel == (220,220,220) else pixel for pixel in image.getdata()]
        new_image = Image.new(image.mode, image.size)
        new_image.putdata(new_pixels)
        new_image.save(os.path.join(img_path, filename))
def convert_pdf_to_images(img_path,doc):
    for i, page in enumerate(doc):
        pix = page.getPixmap(matrix=fitz.Matrix(2, 2))
        img_output_path = os.path.join(img_path, f"{i+1:04d}.jpg")
        pix.writePNG(img_output_path)
def creat_file(img_path):
    if not os.path.exists(img_path):
        os.makedirs(img_path)
    else:
        for root, dirs, files in os.walk(img_path, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
def convert_images_to_pdf(img_path, output_path):
    image_list = []
    for filename in os.listdir(img_path):
        image_list.append(Image.open(os.path.join(img_path, filename)))
    image_list[0].save(output_path, save_all=True, append_images=image_list[1:])
def delete_watermark(file_path):
    folder_path = os.path.dirname(file_path)
    file_name = os.path.basename(file_path)
    output_path = os.path.join(folder_path, 'new_'+file_name)
    img_path = os.path.join(folder_path, f"img_{os.path.splitext(file_name)[0]}")
    creat_file(img_path)
    convert_pdf_to_images(img_path, doc=fitz.open(file_path))
    replace_color(img_path)
    convert_images_to_pdf(img_path, output_path)
if __name__ == "__main__":
    delete_watermark('E:\...\example.pdf')

正文

為了不影響閱讀體驗(yàn),一般水印都是由灰色或紅色等與正文內(nèi)容明顯不同的顏色構(gòu)成的。因此,要去除此類水印只需要判斷出它是哪種顏色,然后將此顏色替換為背景色即可。

以上面圖片中的水印為例,我們通過對(duì)水印部分進(jìn)行取色可以看到,水印的 RGB 值為 (128, 130, 133),背景色為白色( RGB為 (255, 255, 255) ),那么我們只需要將 RGB 值為 (128, 130, 133) 的像素值替換為 (255, 255, 255) 即可實(shí)現(xiàn)圖像水印的去除。

博主使用的取色工具為 Snipaste,也可以用 PS 等其它工具對(duì)水印取色。

首先需要將 PDF 中的一頁信息提取出來,我們使用的是 fitz 庫。

# 將 PDF 文件分解為圖片
def convert_pdf_to_images(img_path,doc)
    for i, page in enumerate(doc):
        pix = page.getPixmap(matrix=fitz.Matrix(2, 2))
        img_output_path = os.path.join(img_path, f"{i+1}.jpg")
        pix.writePNG(img_output_path)

然后再對(duì)圖片中的特定顏色進(jìn)行替換

def replace_color(pixel, old_color, new_color):
    if pixel in old_color:
        return new_color
    else:
        return pixel
old_color = (128, 130, 133)
new_color = (255, 255, 255) 
# 遍歷輸入文件夾中的所有.jpg文件并進(jìn)行顏色替換
for filename in os.listdir(input_folder):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        # 打開圖片并獲取像素?cái)?shù)據(jù)
        image = Image.open(os.path.join(input_folder, filename))
        pixels = list(image.getdata())
        # 遍歷像素?cái)?shù)據(jù)并進(jìn)行顏色替換
        new_pixels = [replace_color(pixel, old_color, new_color) for pixel in pixels]
        # 將修改后的像素?cái)?shù)據(jù)保存到新文件夾中
        new_image = Image.new(image.mode, image.size)
        new_image.putdata(new_pixels)
        new_image.save(os.path.join(output_folder, filename))

最后再將圖片拼接起來則得到去水印后的 PDF

def convert_images_to_pdf(img_path, output_path):
    image_list = []
    for filename in sorted(os.listdir(img_path), key=lambda x: int(x.split('.')[0])):
        image_list.append(Image.open(os.path.join(img_path, filename)))
    image_list[0].save(output_path, save_all=True, append_images=image_list[1:])

將以上三個(gè)步驟合并,即可得到我們的最終代碼

from PIL import Image
import fitz
import os
def replace_color(img_path):
    new_color = (255, 255, 255, 255)
    for filename in os.listdir(img_path):
        image = Image.open(os.path.join(img_path, filename))
        new_pixels = [new_color if pixel == (220,220,220) else pixel for pixel in image.getdata()]
        new_image = Image.new(image.mode, image.size)
        new_image.putdata(new_pixels)
        new_image.save(os.path.join(img_path, filename))
def convert_pdf_to_images(img_path,doc):
    for i, page in enumerate(doc):
        pix = page.getPixmap(matrix=fitz.Matrix(2, 2))
        img_output_path = os.path.join(img_path, f"{i+1:04d}.jpg")
        pix.writePNG(img_output_path)
def creat_file(img_path):
    if not os.path.exists(img_path):
        os.makedirs(img_path)
    else:
        for root, dirs, files in os.walk(img_path, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
def convert_images_to_pdf(img_path, output_path):
    image_list = []
    for filename in os.listdir(img_path):
        image_list.append(Image.open(os.path.join(img_path, filename)))
    image_list[0].save(output_path, save_all=True, append_images=image_list[1:])
def delete_watermark(file_path):
    folder_path = os.path.dirname(file_path)
    file_name = os.path.basename(file_path)
    output_path = os.path.join(folder_path, 'new_'+file_name)
    img_path = os.path.join(folder_path, f"img_{os.path.splitext(file_name)[0]}")
    creat_file(img_path)
    convert_pdf_to_images(img_path, doc=fitz.open(file_path))
    replace_color(img_path)
    convert_images_to_pdf(img_path, output_path)
if __name__ == "__main__":
    delete_watermark('E:\...\example.pdf')

只需要對(duì)水印和背景進(jìn)行取色,然后更改相應(yīng)代碼即可實(shí)現(xiàn)全自動(dòng) Python 去水印功能。

由于水印顏色并不總是某一個(gè)RGB值,而是一個(gè)范圍,所以也可以使用 218<pixel[0]<244 and 218<pixel[1]<244 and 218<pixel[2]<244: 替換 pixel == (220,220,220)

上述程序在運(yùn)行過程中會(huì)根據(jù)文件名,產(chǎn)生一個(gè)"img_[文件名]"文件夾用于存放圖片,以及產(chǎn)生一個(gè)去除水印后的"new_[文件名].pdf"文件。

若不需要查看單張圖片的效果,也可以直接運(yùn)行如下代碼,在等待一段時(shí)間后會(huì)直接生成去除水印后的 PDF。

import fitz
with fitz.open('example.pdf') as doc:
    for page in doc:
        pix = page.getPixmap(matrix=fitz.Matrix(2, 2))
        pix = pix.applyFunction(lambda r,g,b: (255, 255, 255) if (r,g,b) == (220, 220, 220) else (r,g,b))
        new_page = fitz.new_page(width=pix.width, height=pix.height)
        new_page.insert_image(fitz.Rect(0, 0, pix.width, pix.height), pixmap=pix)
new_doc.save("new_example.pdf")

不過該方法生成的 PDF 文件會(huì)遠(yuǎn)大于原始文件,若是介意這點(diǎn)可繼續(xù)用前一種方法。關(guān)于為什么該方法生成的文件變大這點(diǎn),筆者目前也不清楚,如果有知道原因的朋友可以留下評(píng)論。

對(duì)于特別大的文件,可能導(dǎo)致 MemoryError,這時(shí)可以嘗試先將圖片分組,每組圖片生成 pdf 文件后,再將多個(gè) pdf 文件合并。

from PyPDF2 import PdfFileMerger
def convert_images_to_pdf2(img_path, pdf_path, output_path, num_group=10):
    image_list = []
    creat_file(pdf_path)
    pdf_file = []
    for i, filename in enumerate(os.listdir(img_path)):
        img = Image.open(os.path.join(img_path, filename))
        image_list.append(img)
        if (i + 1) % num_group == 0:
            split_pdf_path = os.path.join(pdf_path, f"{len(pdf_file)+1:04d}.pdf")
            image_list[0].save(split_pdf_path, save_all=True, append_images=image_list[1:])
            pdf_file.append(split_pdf_path)
            image_list = []
    pdfs = [os.path.join(pdf_path, f) for f in os.listdir(pdf_path)]
    merger = PdfFileMerger()
    for pdf in pdfs:
        merger.append(pdf)
    merger.write(os.path.join(pdf_path, output_path))
    merger.close()

以上就是Python實(shí)現(xiàn)為PDF大文件批量去除水印的詳細(xì)內(nèi)容,更多關(guān)于Python PDF去水印的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論