Python批量裁剪图片

发布时间:2023-05-20

随着科技的快速发展,数字化时代的到来,图片已经成为人们生活中必不可少的一部分。然而,我们在处理大量图片时,裁剪图片是一项非常重要的任务。在这里,我们将介绍如何使用Python进行批量裁剪图片。

一、安装Pillow库

在Python中,使用Pillow库来处理图片是非常方便的。首先,我们需要安装Pillow库。在命令行或终端中输入以下命令即可:

pip install pillow

我们可以通过以下代码检查Pillow库是否安装成功:

import PIL
if hasattr(PIL, '__version__'):
    print("Pillow库已经安装成功!")
else:
    print("Pillow库没有安装成功!")

二、裁剪单张图片

在这一部分中,我们将展示如何使用Python裁剪单张图片:

from PIL import Image
image = Image.open('input.jpg')
# left, upper, right, lower
cropped_image = image.crop((100, 100, 400, 400))
cropped_image.save('output.jpg')
cropped_image.show()

代码解析:

  1. 首先,我们导入了 Image 模块。
  2. 然后,我们使用 Image 模块的 open() 函数打开图片文件。
  3. 接下来,我们使用 crop() 函数裁剪图片。crop() 函数需要接收一个 tuple 类型的参数,表示裁剪的范围。范围参数的顺序为 (left, upper, right, lower),分别代表裁剪框的左上、右下角坐标。
  4. 最后,我们使用 save() 函数保存裁剪后的图片,并且使用 show() 函数显示裁剪后的图片。

三、批量裁剪图片

在这一部分中,我们将展示如何使用Python批量裁剪图片。我们将图片文件放置在“input”文件夹中,裁剪后的图片将保存在“output”文件夹中:

from PIL import Image
import os
input_dir = 'input'
output_dir = 'output'
# make output dir if it does not exist
if not os.path.exists(output_dir):
    os.mkdir(output_dir)
for file_name in os.listdir(input_dir):
    try:
        file_path = os.path.join(input_dir, file_name)
        image = Image.open(file_path)
        # left, upper, right, lower
        cropped_image = image.crop((100, 100, 400, 400))
        output_path = os.path.join(output_dir, file_name)
        cropped_image.save(output_path)
    except:
        print("An error occurred while processing the file:", file_name)

代码解析:

  1. 我们导入了 Image 模块和 os 模块。
  2. 然后,我们定义了一个 input_dir 变量和一个 output_dir 变量,用来表示输入和输出文件夹的路径。
  3. 我们使用 os 模块中的函数,先检查输出文件夹是否存在,不存在则创建该文件夹。
  4. 接着,我们使用 os 模块中的 listdir() 函数来获取输入文件夹中的文件列表。然后,我们使用一个循环来遍历文件列表。
  5. 在循环中,我们使用 join() 函数来生成每个文件的完整路径,然后打开它并使用 crop() 函数裁剪它。
  6. 最后,我们使用 join() 函数来生成输出文件的完整路径,并使用 save() 函数保存裁剪后的文件。

四、调整裁剪宽高比例

在上面的例子中,我们使用了固定的裁剪框大小。但是,在一些情况下,我们可能需要调整裁剪框的大小和宽高比例。以下是一个例子,我们将裁剪框调整为输入图片的50%大小:

from PIL import Image
import os
input_dir = 'input'
output_dir = 'output'
# make output dir if it does not exist
if not os.path.exists(output_dir):
    os.mkdir(output_dir)
for file_name in os.listdir(input_dir):
    try:
        file_path = os.path.join(input_dir, file_name)
        image = Image.open(file_path)
        width, height = image.size
        # adjust cropping box size and aspect ratio
        left = width / 4
        upper = height / 4
        right = (3 * width) / 4
        lower = (3 * height) / 4
        cropped_image = image.crop((left, upper, right, lower))
        output_path = os.path.join(output_dir, file_name)
        cropped_image.save(output_path)
    except:
        print("An error occurred while processing the file:", file_name)

代码解析:

  1. 该代码与前面的代码类似,但是这里使用了输入图片的大小来计算裁剪框的大小。
  2. 首先,我们获取了输入图片的宽和高。
  3. 然后,我们根据比例计算裁剪框的大小。在这个例子中,我们将裁剪框大小设置为输入图片宽和高的1/4至3/4之间。
  4. 最后,我们使用相同的方法来打开、裁剪和保存图片。

五、结论

在本文中,我们介绍了如何使用Python裁剪图片。通过使用Pillow库,我们能够快速、简便地批量裁剪图片。我们还展示了如何调整裁剪框的大小和宽高比例。