python将两个文件夹下图片名字相同的图片拼接
时间: 2024-10-15 20:18:22 浏览: 30
python实现两张图片拼接为一张图片并保存
在Python中,你可以使用PIL (Pillow) 库来进行图像处理,特别是合并相似名称的图片。这里是一个简单的示例,假设你有两个文件夹 (`folder1` 和 `folder2`),它们都包含名为 "same_image_name.jpg" 的图片:
```python
from PIL import Image
# 定义文件夹路径
folder1_path = 'path_to_folder1'
folder2_path = 'path_to_folder2'
# 获取每个文件夹下的所有图片名
images_in_folder1 = [img for img in os.listdir(folder1_path) if img.endswith('.jpg')]
images_in_folder2 = [img for img in os.listdir(folder2_path) if img.endswith('.jpg')]
# 检查是否有同名图片
same_image_names = set(images_in_folder1) & set(images_in_folder2)
for name in same_image_names:
# 找到每个文件夹下对应的照片路径
image1_path = os.path.join(folder1_path, name)
image2_path = os.path.join(folder2_path, name)
# 打开并合并图片
with Image.open(image1_path) as im1, Image.open(image2_path) as im2:
combined_image = Image.alpha_composite(im1, im2) # 如果图片有透明度,使用 alpha_composite 否则 use Image.merge()
combined_image.save('merged_' + name) # 保存结果
阅读全文