Python Pillow 简明教程
Python Pillow - Concatenating two Images
使用 Pillow 合并两张图像通常是指将两张独立的图像水平或垂直合并或连接起来以创建一张图像。此过程允许我们将两张图像的内容合并到一张更大的图像中。
Concatenating two images with Pillow typically refers to combining or joining two separate images to create a single image either horizontally or vertically. This process allows us to merge the content of the two images into a larger image.
Pillow 是一个 Python 图像库 (PIL),它提供了多种方法和函数执行图像操作,包括图像拼接。在拼接图像时,我们可以选择将它们垂直拼接堆叠到彼此上方,或水平拼接将它们并排放置。
Pillow is a Python Imaging Library (PIL) which provides various methods and functions to perform image manipulation including image concatenation. When concatenating images we can choose to stack them on top of each other vertical concatenation or place them side by side horizontal concatenation.
在 Pillow 中没有直接的方法来拼接图像,但我们可以使用 python 中的 paste() 方法来执行此操作。
There are no direct methods in pillow to concatenate the images but we can perform that by using the paste() method in python.
以下是如何执行两张图像拼接的分步指南。
Here is a step-by-step guide on how to perform concatenation of two Images.
-
Import the necessary modules.
-
Load the two images that we want to concatenate.
-
Decide whether we want to concatenate the images horizontally or vertically.
-
Save the concatenated image to a file.
-
Optionally we can display the concatenated image. This step is useful for visualizing the result but it’s not required.
以下是本章所有示例中使用的输入图像。
Following is the input images used in all the examples of this chapter.


Example
在此示例中,我们将水平拼接两张输入图像。
In this example we are concatenating two input images horizontally.
from PIL import Image
image1 = Image.open("Images/butterfly.jpg")
image2 = Image.open("Images/flowers.jpg")
result = Image.new("RGB", (image1.width + image2.width, image1.height))
result.paste(image1, (0, 0))
result.paste(image2, (image1.width, 0))
result.save("output Image/horizontal_concatenated_image.png")
result.show()
Example
在此示例中,我们将垂直拼接给定的两张输入图像。
Here in this example we are concatenating the given two input images vertically.
from PIL import Image
image1 = Image.open("Images/butterfly.jpg")
image2 = Image.open("Images/flowers.jpg")
result = Image.new("RGB", (image1.width, image1.height + image2.height))
result.paste(image1, (0, 0))
result.paste(image2, (0, image1.height))
result.save("output Image/vertical_concatenated_image.png")
result.show()