跟着我们一起学 Python 30天课程-第21天-脚本编写基础
今天,我探讨了Python脚本编写的基础知识。脚本编写基本上意味着编写具有命令集合的程序,并从命令行或交互式外壳执行该程序以执行有用的任务并使它们自动化。使用Python脚本可以完成很多事情,例如处理各种类型的文件(如PDF,图像,excel,CSV等),发送电子邮件,创建类似twitter bot的bot以及许多其他事情。作为这一挑战的一部分,我决定学习脚本编写的基础知识,以使我了解这些概念,然后在将来进行更深入的探索。我今天的重点是找出使用Python脚本处理图像和PDF文件的基本技术。
图像处理
简单来说,图像处理是使用增强图像或从图像中提取信息的程序对图像执行某些操作的方法或技术。有很多流行的库可以在Python中执行图像处理,例如
- 枕头-https: //pillow.readthedocs.io/zh/stable/index.html
- OpenCV的
- Python Imaging Library(不建议使用)
- scikit图像
我试用了Pillow,它是Python Imaging Library(PIL)的一个分支版本,不再维护且不支持Python的最新版本。因此,建议在PIL上使用枕头。
安装和基本用法可以在Pillow文档中找到。https://pillow.readthedocs.io/en/stable/index.html
可以使用以下命令在命令行中安装枕头pip install Pillow
(有关特定的OS命令,请参阅文档)
现在该创建一些图像处理脚本了。我创建的第一个是基本的图像转换器,它将一个文件夹中的所有JPEG格式的图像转换为PNG格式的图像,并将它们存储在另一个文件夹中。我从https://unsplash.com下载了一些JPEG图像,并将它们存储在一个文件夹中images
。该脚本需要读取所有JPEG图像,将其转换为PNG,然后将其放置在新文件夹中generated
。
这是我命名的脚本文件的代码,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
它应该自动转换生成的文件夹中的图像。
我创建的第二个脚本是灰度转换器,可将所有图像转换为黑白图像。使用枕头可以将许多滤镜应用于图像,灰度是其中之一。
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')
那真是太酷了!这仅仅是在处理图像的表面。我想这是一个很好的起点,可以在以后创建项目时进一步探索。
以下是一些我发现有趣的很酷的资源,这些资源与Python中的图像处理有关
- https://auth0.com/blog/image-processing-in-python-with-pillow/
- https://opensource.com/article/19/3/python-image-manipulation-tools
- https://stackabuse.com/introduction-to-image-processing-in-python-with-opencv/
- https://towardsdatascience.com/image-manipulation-tools-for-python-6eb0908ed61f
- https://github.com/shekkizh/ImageProcessingProjects
处理PDF
除了玩转图像之外,我还根据一些实际使用案例探讨了处理PDF文件和处理PDF文件的基础知识。PDF是最广泛使用的文件格式之一,可以存储各种数据。
我使用的库是PyPDF2 https://pypi.org/project/PyPDF2/,这是我在PyPI上发现的非常流行的库。可以使用以下pip
命令下载该库pip install PyPDF2
我将样本PDF文件添加到pdfs目录中
我创建的第一个脚本主要是从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
所有相关的代码都可以在这个Github仓库中找到
今天就这些。将在脚本方面进行更多探索,例如为Twitter构建自动化的bot,明天发送电子邮件和其他有趣的东西。
跟着我们一起学 Python 30天课程目录:
- 跟着我们一起学 Python 30天课程-第30天-免费Python资源
- 跟着我们一起学 Python 30天课程-第29天-自动化测试
- 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
- 跟着我们一起学 Python 30天课程-第27天-ML和数据科学I
- 跟着我们一起学 Python 30天课程-第26天-机器学习基础
- 跟着我们一起学 Python 30天课程-第25天-Web 开发进阶
- 跟着我们一起学 Python 30天课程-第24天-Web开发基础
- 跟着我们一起学 Python 30天课程-第23天-网页爬虫
- 跟着我们一起学 Python 30天课程-第22天-脚本额外功能Scripting Extras
- 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
- 跟着我们一起学 Python 30天课程-第20天-调试和测试
- 跟着我们一起学 Python 30天课程-第19天-正则表达式
- 跟着我们一起学 Python 30天课程-第18天-文件I / O
- 跟着我们一起学 Python 30天课程-第17天-外部模块External Modules
- 跟着我们一起学 Python 30天课程-第16天-模块基础Module Basics
- 跟着我们一起学 Python 30天课程-第15天-生成器Generators
- 跟着我们一起学 Python 30天课程-第14天-错误处理Error Handling
- 跟着我们一起学 Python 30天课程-第13天-Decorators
- 跟着我们一起学 Python 30天课程-第12天-Lambda Expressions & Comprehensions
- 跟着我们一起学 Python 30天课程-第11天-函数编程Functional Programming基础
- 跟着我们一起学 Python 30天课程-第10天-OOP Missing Pieces
- 跟着我们一起学 Python 30天课程-第9天-OOP Pillars
- 跟着我们一起学 Python 30天课程-第8天-OOP基础知识
- 跟着我们一起学 Python 30天课程-第7天-开发环境搭建(Developer Environment)
- 跟着我们一起学 Python 30天课程-第6天-循环II和函数(Loops II & Functions)
- 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
- 跟着我们一起学 Python 30天课程-第4天-数据类型III(Data Types III)
- 跟着我们一起学 Python 30天课程-第3天-数据类型II(Data Types II)
- 跟着我们一起学 Python 30天课程-第2天-数据类型I(Data Types I)
- 跟着我们一起学 Python 30天课程-第1天-简介
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。