图片拼接|横向拼接|竖向拼接|正方形拼接|其他模式拼接 python

  • 读取某文件夹下所有子文件夹的图片,进行拼接

文件夹

---文件夹1

|----图片1

|----图片2

---文件夹2

|----图片3

---文件夹3

|----图片4

|----图片5

python 复制代码
import os
import cv2
import numpy as np
import random
from math import ceil, sqrt


# 支持中文路径的图片读取函数
# def cv_imread(file_path):
#     cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
#     cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)  # 转换为 BGR 格式
#     return cv_img

def cv_imread(file_path):
    """支持中文路径的图片读取,修正反色问题"""
    cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
    return cv_img  # 不再进行颜色转换,直接返回 BGR 图像



def load_images_from_folder(folder):
    """加载指定文件夹及其子文件夹中的所有图片,支持中文路径"""
    images = []
    for root, _, files in os.walk(folder):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
                img_path = os.path.join(root, file)
                img = cv_imread(img_path)  # 使用支持中文路径的读取方法
                if img is not None:
                    images.append(img)
    return images


def vertical_stack(images):
    """竖向拼接"""
    return np.vstack(images)


def horizontal_stack(images):
    """横向拼接"""
    return np.hstack(images)


def square_stack(images):
    """拼接成接近正方形的布局"""
    n = len(images)
    cols = ceil(sqrt(n))
    rows = ceil(n / cols)
    max_height = max(img.shape[0] for img in images)
    max_width = max(img.shape[1] for img in images)

    # 创建空白画布
    canvas = np.zeros((rows * max_height, cols * max_width, 3), dtype=np.uint8)

    for idx, img in enumerate(images):
        row = idx // cols
        col = idx % cols
        y_offset = row * max_height
        x_offset = col * max_width
        canvas[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]] = img
    return canvas


def chaotic_stack(images):
    """恶搞模式:随机旋转、缩放和排列图片"""
    canvas_size = (1000, 1000, 3)
    canvas = np.zeros(canvas_size, dtype=np.uint8)
    h, w = canvas.shape[:2]

    for img in images:
        # 随机缩放
        scale = random.uniform(0.5, 1.5)
        resized_img = cv2.resize(img, (0, 0), fx=scale, fy=scale)

        # 随机旋转
        angle = random.randint(0, 360)
        center = tuple(np.array(resized_img.shape[1::-1]) // 2)
        rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated_img = cv2.warpAffine(resized_img, rot_mat, resized_img.shape[1::-1], flags=cv2.INTER_LINEAR,
                                     borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))

        # 随机放置
        x_offset = random.randint(0, w - rotated_img.shape[1])
        y_offset = random.randint(0, h - rotated_img.shape[0])

        try:
            canvas[y_offset:y_offset + rotated_img.shape[0], x_offset:x_offset + rotated_img.shape[1]] = rotated_img
        except ValueError:
            # 如果超出范围,跳过
            continue
    return canvas


def save_image(output_path, image):
    """保存图片,支持中文路径"""
    cv2.imencode('.jpg', image)[1].tofile(output_path)


def main():
    folder = input("请输入图片文件夹路径:")
    output_path = input("请输入拼接后图片保存路径(如 output.jpg):")
    print("选择拼接模式:")
    print("1: 竖向拼接")
    print("2: 横向拼接")
    print("3: 拼成接近正方形")
    print("4: 恶搞模式")
    mode = int(input("请输入模式编号(1/2/3/4):"))

    images = load_images_from_folder(folder)
    if not images:
        print("未找到图片,请检查文件夹路径!")
        return

    if mode == 1:
        result = vertical_stack(images)
    elif mode == 2:
        result = horizontal_stack(images)
    elif mode == 3:
        result = square_stack(images)
    elif mode == 4:
        result = chaotic_stack(images)
    else:
        print("无效的模式编号!")
        return

    save_image(output_path, result)
    print(f"拼接完成,图片已保存至:{output_path}")


if __name__ == "__main__":
    main()
相关推荐
曲幽9 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805114 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞17 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
CoovallyAIHub17 小时前
OpenClaw 近 2000 个 Skills,为什么没有一个好用的视觉检测工具?
深度学习·算法·计算机视觉
CoovallyAIHub17 小时前
CVPR 2026 | 用一句话告诉 AI 分割什么——MedCLIPSeg 让医学图像分割不再需要海量标注
深度学习·算法·计算机视觉
CoovallyAIHub18 小时前
Claude Code 突然变成了 66 个专家?这个 5.8k Star 的开源项目,让我重新理解了什么叫"会用 AI"
深度学习·算法·计算机视觉
dev派18 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪20 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636720 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python