文件结构
4张图片实现拼接
按照文件命名确定拼接位置,(0,0)(0,1) (1,0) (1,1),第一排两张,第二排两张,自定义重叠区域
代码:
from PIL import Image
# 定义图片文件夹路径
folder_path = "images/"
# 定义图片文件名列表
image_files = [
"QKD#258#0#0.png",
"QKD#258#0#1.png",
"QKD#258#1#0.png",
"QKD#258#1#1.png"
]
# 存储图片对象的列表
images = []
# 读取图片并添加到列表中
for filename in image_files:
image = Image.open(folder_path + filename)
images.append(image)
# 获取第一张图片的大小
width, height = images[0].size
# 自定义重叠部分的大小(单位:像素)
overlap_size = 100 # 可以根据需要修改
# 创建一个新的大图,用于拼接图片
result_width = 2 * width - overlap_size
result_height = 2 * height - overlap_size
result_image = Image.new("RGB", (result_width, result_height))
# 拼接图片
for i in range(2):
for j in range(2):
index = i * 2 + j
x_offset = j * (width - overlap_size)
y_offset = i * (height - overlap_size)
result_image.paste(images[index], (x_offset, y_offset))
# 保存拼接后的图片
result_image.save("result_image.png")
# 显示拼接后的图片
result_image.show()
2*3拼接:
from PIL import Image
# 定义图片文件夹路径
folder_path = "images/"
# 定义图片文件名列表
image_files = [
"QKD#258#0#0.png",
"QKD#258#0#1.png",
"QKD#258#0#2.png",
"QKD#258#1#0.png",
"QKD#258#1#1.png",
"QKD#258#1#2.png"
]
# 存储图片对象的列表
images = []
# 读取图片并添加到列表中
for filename in image_files:
image = Image.open(folder_path + filename)
images.append(image)
# 获取第一张图片的大小
width, height = images[0].size
# 自定义重叠部分的大小(单位:像素)
overlap_size = 50 # 可以根据需要修改
# 计算拼接后的图片尺寸
result_width = 3 * width - 2 * overlap_size
result_height = 2 * height - overlap_size
result_image = Image.new("RGB", (result_width, result_height))
# 拼接图片
for i in range(2):
for j in range(3):
index = i * 3 + j
x_offset = j * (width - overlap_size)
y_offset = i * (height - overlap_size)
result_image.paste(images[index], (x_offset, y_offset))
# 保存拼接后的图片
result_image.save("result_image.png")
# 显示拼接后的图片
result_image.show()
3*3 拼接:
from PIL import Image
# 定义图片文件夹路径
folder_path = "images/"
# 定义图片文件名列表
image_files = [
"QKD#258#0#0.png",
"QKD#258#0#1.png",
"QKD#258#0#2.png",
"QKD#258#1#0.png",
"QKD#258#1#1.png",
"QKD#258#1#2.png",
"QKD#258#2#0.png",
"QKD#258#2#1.png",
"QKD#258#2#2.png"
]
# 存储图片对象的列表
images = []
# 读取图片并添加到列表中
for filename in image_files:
image = Image.open(folder_path + filename)
images.append(image)
# 获取第一张图片的大小
width, height = images[0].size
# 自定义重叠部分的大小(单位:像素)
overlap_size = 50 # 可以根据需要修改
# 计算拼接后的图片尺寸
result_width = 3 * width - 2 * overlap_size
result_height = 3 * height - 2 * overlap_size
result_image = Image.new("RGB", (result_width, result_height))
# 拼接图片
for i in range(3):
for j in range(3):
index = i * 3 + j
x_offset = j * (width - overlap_size)
y_offset = i * (height - overlap_size)
result_image.paste(images[index], (x_offset, y_offset))
# 保存拼接后的图片
result_image.save("result_image.png")
# 显示拼接后的图片
result_image.show()