python如何拼接图片
根据错误提示,文件路径设置不正确导致无法找到图片。请按以下步骤操作:
- 上传图片:点击对话框下方📎图标上传需要拼接的图片(支持JPG/PNG格式)
- 设置正确路径:将代码中的
image_dir
替换为实际路径,例如:- Windows系统:
image_dir = 'D:\\images\\'
- macOS/Linux系统:
image_dir = '/Users/name/images/'
- Windows系统:
- 选择拼接方式:
方案一:水平拼接(Pillow库)
from PIL import Image
import osdef horizontal_concat(image_paths, output_path):images = [Image.open(f) for f in image_paths]total_width = sum(img.size[0] for img in images)max_height = max(img.size[1] for img in images)result = Image.new('RGB', (total_width, max_height))x_offset = 0for img in images:result.paste(img, (x_offset, 0))x_offset += img.size[0]result.save(output_path)# 替换为实际文件路径
image_dir = '您的图片目录'
image_files = [os.path.join(image_dir, f) for f in os.listdir(image_dir) if f.endswith('.jpg')]
horizontal_concat(image_files, 'horizontal_result.jpg')
方案二:垂直拼接(OpenCV库)
import cv2
import numpy as np
import osdef vertical_concat(image_paths, output_path):images = [cv2.imread(f) for f in image_paths]# 统一宽度min_width = min(img.shape[1] for img in images)resized_images = [cv2.resize(img, (min_width, int(img.shape[0] * min_width / img.shape[1]))) for img in images]result = cv2.vconcat(resized_images)cv2.imwrite(output_path, result)# 替换为实际文件路径
image_dir = '您的图片目录'
image_files = [os.path.join(image_dir, f) for f in os.listdir(image_dir) if f.endswith('.png')]
vertical_concat(image_files, 'vertical_result.png')
注意事项:
- 确保所有图片在同一目录
- 图片格式需统一(建议全部为JPG或PNG)
- 路径中避免中文字符和特殊符号
- 安装必要库:
pip install pillow opencv-python
请上传图片后,我会立即执行修正后的代码并返回拼接结果。