📜  如何在Python使用 Pillow 连接图像?

📅  最后修改于: 2022-05-13 01:54:30.906000             🧑  作者: Mango

如何在Python使用 Pillow 连接图像?

先决条件: Python枕头

连接图像意味着连接两个图像。我们可以合并任何图像,无论它是否具有不同的像素,不同的图像格式,即 'jpeg'、'png'、'gif'、'tiff' 等。在Python,我们可以使用Python图像库(也称为枕头图书馆。在本文中,我们将看到图像的连接是如何完成的。

图像的连接可以通过两种方式完成:

  • 水平的
  • 垂直的

水平连接图像

方法:

  • 导入模块
  • 打开图片
  • 使用 Resize()函数调整图像大小。两个调整大小的图像应该具有相同的宽度和高度,以便它们的纵横比完好无损,并且可以粘贴到新的背景图像中。
  • 要创建一个新图像,它有一个 new()函数,它有 3 个参数(“模式”、(大小)、颜色)
  • 使用 paste() 将图像粘贴到新图像

程序:



Python3
# library
from PIL import Image
import matplotlib.pyplot as plt
  
# opening up of images
img = Image.open("logo.png")
img1 = Image.open("logo2.png")
img.size
img1.size
img_size = img.resize((250, 90))
img1_size = img1.resize((250, 90))
  
# creating a new image and pasting 
# the images
img2 = Image.new("RGB", (500, 90), "white")
  
# pasting the first image (image_name,
# (position))
img2.paste(img_size, (0, 0))
  
# pasting the second image (image_name,
# (position))
img2.paste(img1_size, (250, 0))
  
plt.imshow(img2)


Python3
# library
from PIL import Image
import matplotlib.pyplot as plt
  
  
# opening up of images
img = Image.open("logo.png")
img1 = Image.open("logo2.png")
img.size
img1.size
img_size = img.resize((250, 90))
img1_size = img1.resize((250, 90))
  
# creating a new image and pasting the 
# images
img2 = Image.new("RGB", (250, 180), "white")
  
# pasting the first image (image_name,
# (position))
img2.paste(img_size, (0, 0))
  
# pasting the second image (image_name,
# (position))
img2.paste(img1_size, (0, 90)
  
plt.imshow(img2)


输出 :

垂直连接图像

整个代码与水平相同,但唯一的变化是在水平中我们将宽度加倍,高度相同,但在垂直中,我们使宽度的大小相同,但我们将高度加倍。

方法:

  • 导入用于图像处理的库。
  • 使用 Image.open() 打开库。
  • 使用 img.size 知道图像的大小。
  • 使用 img.resize((width,height)) 调整图像大小。
  • 两个图像的大小应该相同。
  • 使用 new() 创建一个新图像并传递 3 个参数“mode”、size、“color”)。
  • 新图像的大小应该是(宽,2*高)。
  • 创建新图像后,使用 paste() 粘贴第一张图像并传递参数(img_resize,(position)) #position(0,0)
  • 粘贴第一张图片后,使用paste粘贴第二张图片并传递参数(img1_reszie, (position))。在位置上,宽度将相同,但高度将是第一张图像高度的最后一个位置。 . #position=(0,180)
  • 使用 plt.imshow(img2) 显示图像的连接。

程序:

蟒蛇3

# library
from PIL import Image
import matplotlib.pyplot as plt
  
  
# opening up of images
img = Image.open("logo.png")
img1 = Image.open("logo2.png")
img.size
img1.size
img_size = img.resize((250, 90))
img1_size = img1.resize((250, 90))
  
# creating a new image and pasting the 
# images
img2 = Image.new("RGB", (250, 180), "white")
  
# pasting the first image (image_name,
# (position))
img2.paste(img_size, (0, 0))
  
# pasting the second image (image_name,
# (position))
img2.paste(img1_size, (0, 90)
  
plt.imshow(img2)

输出: