Python 30 天 – 第 21 天 – 脚本基础知识(python图像处理,python PDF水印)

作者 : 慕源网 本文共5094个字,预计阅读时间需要13分钟 发布时间: 2021-10-14 共503人阅读

本文是 30 天 Python 挑战系列的一部分。您可以在此处找到本系列之前所有帖子的链接

今天我探索了 Python 脚本的基础知识。脚本编写基本上意味着编写具有一系列命令的程序,这些命令从命令行或交互式 shell 执行,以执行有用的任务并自动化它们。有很多事情可以使用 Python 脚本自动化,例如处理各种类型的文件,如 PDF、图像、excel、CSV 等,发送电子邮件,创建 twitter bot 等机器人以及许多其他事情。作为这个挑战的一部分,我决定学习脚本的基础知识,以便我理解这些概念,然后可以在未来进行更深入的探索。我今天的重点是找出使用 Python 脚本处理图像和 PDF 文件的基本技术。

图像处理

简单来说,图像处理是使用程序对图像执行某些操作以增强图像或从中提取信息的方法或技术。有很多流行的库可以在 Python 中执行图像处理,例如

  • Pillow
  • OpenCV
  • Python Imaging Library (Deprecated)
  • scikit-image

我尝试了 Pillow,它是 Python Imaging Library (PIL) 的一个分支版本,PIL不再维护,并且不支持 Python 最新的版本。因此,建议 Pillow 使用而不是 PIL。

安装和基本用法可以在Pillow 文档中找到

Pillow 可以使用命令行安装,使用命令 pip install Pillow(查看特定操作系统命令的文档)。

是时候创建一些图像处理脚本了。我创建的第一个是一个基本的图像转换器,它将一个文件夹中的所有 JPEG 格式图像转换为 PNG 格式图像并将它们存储在另一个文件夹中。我从 https://unsplash.com 下载了一些 JPEG 图像并将它们存储在一个文件夹图像中。该脚本需要读取所有 JPEG 图像,将它们转换为 PNG,然后将它们放在生成的新文件夹中。

这是我命名为 image_convertor.py 的脚本文件的代码 这是该项目的GitHub 存储库链接。

由于原始图像尺寸非常大,我首先将它们调整为较小的尺寸,然后将它们转换以提高脚本的性能。

image_converter.py

import os    
from PIL import Image    
    
# fetch all the files from the source folder    
dirname = 'images'    
output_dirname = 'generated'    
images_list = os.listdir(dirname)    
    
# check if output folder exits otherwise create it    
if not os.path.exists(output_dirname):    
    os.makedirs(output_dirname)    
    
for image in images_list:    
    # split the filename to separate the format and name    
    name, format = os.path.splitext(image)    
    
    original = Image.open(f'{dirname}\{image}')    
    
    # resize image to a standard size and to reduce file size    
    size = 1000,1000    
    # thumbnail maintains aspect ratio    
    original.thumbnail(size)     
        
    
    # save image as png format    
    original.save(f'{output_dirname}\{name}.png')  

该脚本可以作为 python image_converter.py 从终端运行。它应该自动转换生成文件夹中的图像。

我创建的第二个脚本是一个灰度图片转换器,它将所有图像转换为黑白图像。使用 Pillow 可以在图像上应用许多过滤器,grayscale就是其中之一。

grayscale_converter.py

import os    
from PIL import Image, ImageFilter    
    
# fetch all the files from the source folder    
dirname = 'images'    
output_dirname = 'greyscale'    
images_list = os.listdir(dirname)    
    
# check if output folder exits otherwise create it    
if not os.path.exists(output_dirname):    
    os.makedirs(output_dirname)    
    
for image in images_list:    
    # split the filename to separate the format and name    
    name, format = os.path.splitext(image)    
    
    original = Image.open(f'{dirname}\{image}')    
    
    # resize image to a standard size and to reduce file size    
    size = 1000, 1000    
    # thumbnail maintains aspect ratio    
    original.thumbnail(size)    
    
    # convert the image to greyscale    
    grayscale_image = original.convert('L')  # L mode means greyscale    
    grayscale_image.save(f'{output_dirname}\{image}')   

最后,我创建了另一个图像处理脚本来在所有图像上应用徽标。这使用了合并图像的技术。如果我们必须将品牌应用于图像,这可能非常有用。我在根目录中添加了一个 logo.png 图像文件。

brand_stamp.py

import os    
from PIL import Image, ImageFilter    
    
# fetch all the files from the source folder    
dirname = 'images'    
output_dirname = 'branded'    
images_list = os.listdir(dirname)    
logo = Image.open('logo.png')    
    
# check if output folder exits otherwise create it    
if not os.path.exists(output_dirname):    
    os.makedirs(output_dirname)    
    
for image in images_list:    
    # split the filename to separate the format and name    
    name, format = os.path.splitext(image)    
    
    original = Image.open(f'{dirname}\{image}')    
    
    # resize image to a standard size and to reduce file size    
    size = 1000, 1000    
    # thumbnail maintains aspect ratio    
    original.thumbnail(size)    
    
    # create a copy of the image    
    image_copy = original.copy()    
    # obtain the position to place the logo    
    
    position = ((image_copy.width - logo.width),    
                (image_copy.height - logo.height))    
    # The third parameter makes it transparent    
    image_copy.paste(logo, position, logo)    
    image_copy.save(f'{output_dirname}\{name}.png')   

这只是触及处理图像的表面。我认为这是一个很好的起点,可以在未来创建项目时进一步探索。

处理 PDF

除了处理图像之外,我还基于一些实际用例探索了处理 PDF 文件和处理 PDF 文件的基础知识。PDF 是使用最广泛的文件格式之一,可以存储各种数据。

我使用的库是 PyPDF2 https://pypi.org/project/PyPDF2/,这是我在 PyPI 上发现的一个非常受欢迎的库。可以使用 pip 命令 pip install PyPDF2 下载该库

我在 pdfs 目录中添加了一个示例 PDF 文件

我创建的第一个脚本主要是从 PDF 文件中提取信息,例如作者、页数、主题、标题等。

info_extractor.py
from PyPDF2 import PdfFileReader    
    
def extract_information(pdf_path):    
    with open(pdf_path, 'rb') as f:    
        pdf = PdfFileReader(f)    
        information = pdf.getDocumentInfo()    
        number_of_pages = pdf.getNumPages()    
    
    txt = f"""  
    Information about {pdf_path}:   
  
    Author: {information.author}  
    Creator: {information.creator}  
    Producer: {information.producer}  
    Subject: {information.subject}  
    Title: {information.title}  
    Number of pages: {number_of_pages}  
    """    
    
    print(txt)    
    return information    
    
if __name__ == '__main__':    
    path = 'pdfs/sample1.pdf'    
    extract_information(path)  

该脚本可以使用 python info_extractor.py 运行。它应该成功打印出有关 PDF 文件的所有必要信息。

最后,我编写了另一个脚本,将品牌徽标作为水印添加到所有 pdf 中。为此,我创建了另一个空白 PDF,其中只有带有水印的徽标。现在可以将其与 PDF 文件合并以进行处理。创建带水印的 PDF 是一项非常普遍的要求,自动化此任务可能非常有用。

pdf_watermarker.py

from PyPDF2 import PdfFileWriter, PdfFileReader    
    
def create_watermark(input_pdf, output, watermark):    
    watermark_obj = PdfFileReader(watermark)    
    watermark_page = watermark_obj.getPage(0)    
    
    pdf_reader = PdfFileReader(input_pdf)    
    pdf_writer = PdfFileWriter()    
   
    # Watermark all the pages    
    for page in range(pdf_reader.getNumPages()):    
        page = pdf_reader.getPage(page)    
        page.mergePage(watermark_page)    
        pdf_writer.addPage(page)    
    
    with open(output, 'wb') as out:    
        pdf_writer.write(out)    
    
if __name__ == '__main__':    
    create_watermark(    
        input_pdf='pdfs/sample1.pdf',     
        output='pdfs/watermarked_sample.pdf',    
        watermark='pdfs/watermark.pdf')   

在运行 python pdf_watermarker.py 时,它应该生成带水印的 PDF 文件。

PDF可以做很多事情。然而,我只是决定通过基础知识来熟悉这个过程。我正在链接一些很棒的资源以深入研究 PDF 处理。

这里有一些在 Python 中处理 PDF 的参考资料

  • https://realpython.com/pdf-python/
  • https://towardsdatascience.com/pdf-preprocessing-with-python-19829752af9f
  • https://www.geeksforgeeks.org/working-with-pdf-files-in-python/
  • https://automatetheboringstuff.com/chapter13/
  • https://medium.com/@umerfarooq_26378/python-for-pdf-ef0fac2808b0

这就是今天的全部内容。明天将探索更多关于脚本的内容,例如为 Twitter 构建自动化机器人、发送电子邮件和其他很酷的东西。


慕源网 » Python 30 天 – 第 21 天 – 脚本基础知识(python图像处理,python PDF水印)

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录