python如何把两张图片拼成一张
以下是使用Python的Pillow库(PIL)将两张高度相同的图片水平拼接的详细步骤:
from PIL import Imagedef concat_images_horizontally(img1_path, img2_path, output_path):# 打开两张图片img1 = Image.open(img1_path)img2 = Image.open(img2_path)# 验证图片高度是否相同if img1.height != img2.height:raise ValueError("图片高度不一致,无法拼接")# 创建新画布(宽度相加,高度不变)new_width = img1.width + img2.widthnew_height = img1.heightnew_img = Image.new('RGB', (new_width, new_height))# 拼接图片new_img.paste(img1, (0, 0)) # 左半部分new_img.paste(img2, (img1.width, 0)) # 右半部分# 保存结果new_img.save(output_path)print(f"拼接完成,结果已保存至 {output_path}")# 使用示例
concat_images_horizontally(img1_path = "left_image.jpg",img2_path = "right_image.jpg",output_path = "combined_image.jpg"
)
关键点说明:
- 高度验证:自动检查两张图片高度是否一致
- 模式处理:自动将图片转换为RGB模式(支持处理PNG透明背景)
- 坐标计算:第二张图片的粘贴位置为第一张图片的宽度
- 异常处理:当高度不一致时会抛出明确错误
运行前准备:
pip install Pillow
扩展建议:
- 如需垂直拼接,可修改为:
new_height = img1.height + img2.height new_img.paste(img1, (0, 0)) new_img.paste(img2, (0, img1.height))
- 如需处理大量图片,建议使用
os.path
模块批量读取文件 - 如需添加间距,可在粘贴时调整坐标值
注意事项:
- 确保输入图片路径正确
- 输出格式由文件后缀自动判断(支持jpg/png等常见格式)
- 大尺寸图片拼接时注意内存消耗
- 如需保留透明度,可将模式改为’RGBA’