import os
from PIL import Image
def mirror_images_in_subfolders(parent_directory, x_threshold):
"""
遍历指定目录,找到包含图片数量少于指定阈值的子文件夹,并镜像这些图片,
同时保存新名称以避免重复。保留原始图片,并为镜像图片添加(1)后缀。
:param parent_directory: 要搜索的根目录。
:param x_threshold: 文件夹被考虑进行镜像的最大图片数量。
:return: None
"""
# 在父目录中遍历所有目录和文件
for subdir, dirs, files in os.walk(parent_directory):
image_files = [file for file in files if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
image_count = len(image_files)
# 检查图片数量是否少于阈值且大于0
if 0 < image_count < x_threshold:
print(f"正在镜像以下文件夹中的图片: {subdir} - 图片总数: {image_count}")
# 处理每个图片文件
for image_file in image_files:
try:
# 构建完整的文件路径
file_path = os.path.join(subdir, image_file)
# 打开并镜像图片
with Image.open(file_path) as img:
mirrored_img = img.transpose(Image.FLIP_LEFT_RIGHT)
# 分离文件名和扩展名
name, extension = os.path.splitext(image_file)
# 创建带有额外(1)后缀的新名称
new_name = f"{name}(1){extension}"
new_path = os.path.join(subdir, new_name)
# 检查新文件名是否存在,避免覆盖
counter = 1
while os.path.exists(new_path):
new_name = f"{name}(1)({counter}){extension}"
new_path = os.path.join(subdir, new_name)
counter += 1
# 将镜像后的图片保存回同一目录并使用新名称
mirrored_img.save(new_path)
except Exception as e:
print(f"处理图片 {image_file} 时发生错误: {e}")
print(f"完成镜像以下文件夹中的图片: {subdir}")
if __name__ == "__main__":
# 提示用户输入父目录和X阈值
parent_dir = input("请输入父目录的地址: ")
x_value = int(input("请输入X值(图片数量阈值): "))
# 执行镜像过程
mirror_images_in_subfolders(parent_dir, x_value)