卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章1829本站已运行4109

python 批量组合图片

这个程序基于pyton的cv2库制作,先检测当前机器是否有安装了所需的库,然后通过修改background.png图片来实现与任意图片组合。使用方法很简单,首先新建一个文件夹,文件路径不要包含中文字符,将要合成的图片和底层图片放进去
自己复制代码或者双击我写好的合成图片.py
import os
import cv2
import importlib
import sys
 
initial_working_directory = os.getcwd()  # 保存初始工作目录
 
# 定义要使用的库
required_libraries = ['opencv-python', 'numpy']
 
# 检查并安装缺失的库
for library in required_libraries:
    try:
        importlib.import_module(library)
    except ImportError:
        print(f"缺少库 {library},正在安装...")
        os.system(f'pip install {library}')
 
# 获取用户输入来定义常量的值
ALPHA_WEIGHT = float(input("请输入 底层图片的权重 值(默认为 0.3): ") or 0.3)
BETA_WEIGHT = float(input("请输入 顶层图片的权重(默认为 0.7): ") or 0.7)
GAMMA_WEIGHT = float(input("请输入 亮度(设置后,每个图片像素的值将与该值相加) 的值(默认为 0): ") or 0)
 
# 获取可执行文件所在的临时目录
#BASE_DIR = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
 
# 加载底层图片
bottom_image_path = os.path.abspath(os.path.join(initial_working_directory, 'background.png'))
 
#bottom_image_path = os.path.abspath(os.path.join(BASE_DIR, 'background.png'))
bottom_image = cv2.imread(bottom_image_path)
 
 
# 构建底层图片路径
# bottom_image_path = os.path.join(BASE_DIR, 'background.png')
# bottom_image = cv2.imread(bottom_image_path)
 
# 获取底层图片的尺寸
height, width, _ = bottom_image.shape
 
# 指定顶层图片文件夹和输出文件夹
top_images_folder = './'
output_folder = './output'
 
# 添加其他支持的格式如 '.jpeg', '.bmp' 等
supported_formats = ['.png', '.jpg', '.jpeg', '.bmp']
 
# 生成输出文件夹路径
output_folder_base = os.path.join(initial_working_directory, 'output')
output_folder = output_folder_base
folder_number = 1
while os.path.exists(output_folder):
    folder_number += 1
    output_folder = f'{output_folder_base}_{folder_number}'
 
# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)
 
# 循环处理每个顶层图片
for filename in os.listdir(top_images_folder):
    if any(filename.lower().endswith(ext) for ext in supported_formats):
        # 构建顶层图片的完整路径
        top_image_path = os.path.abspath(os.path.join(top_images_folder, filename))
 
        # 加载顶层图片
        top_image = cv2.imread(top_image_path)
 
        # 调整顶层图片的大小以匹配底层图片的尺寸
        top_image_resized = cv2.resize(top_image, (width, height))
 
        # 使用用户输入的权重值叠加顶层图片到底层图片上
        combined_image = cv2.addWeighted(bottom_image, ALPHA_WEIGHT, top_image_resized, BETA_WEIGHT, GAMMA_WEIGHT)
 
        # 构建输出文件路径
        output_path = os.path.join(output_folder, filename)
 
        # 保存合成后的图像
        cv2.imwrite(output_path, combined_image)
 
print("处理完成!")
input("Press Enter to exit...")
exe版本链接:https://wwow.lanzouq.com/inKIO1juua8j
密码:4sum
卓越飞翔博客
上一篇: 用python制作扫雷
下一篇: Python 换起拍照并上传至Google云端硬盘
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏