将大图像裁剪成512512的小图,如果边缘不够的话就直接舍弃
需要配置输入文件夹和输出文件夹路径
from PIL import Image
import os
'''
将大图像裁剪成512512的小图,如果边缘不够的话就直接舍弃
'''
def crop_images_to_512(folder_path, output_folder):
# 创建输出文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
# 检查文件是否为图片
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
# 打开图像文件
image_path = os.path.join(folder_path, filename)
image = Image.open(image_path)
# 获取图像的宽度和高度
width, height = image.size
# 计算可以裁剪出多少个512x512的小图
cols = width // 512
rows = height // 512
# 裁剪图像并保存小图
for row in range(rows):
for col in range(cols):
# 计算裁剪区域的位置
left = col * 512
upper = row * 512
right = left + 512
lower = upper + 512
# 裁剪图像
cropped_image = image.crop((left, upper, right, lower))
# 构建输出文件路径
output_filename = f"{filename.split('.')[0]}_{row}_{col}.png"
output_path = os.path.join(output_folder, output_filename)
# 保存裁剪后的小图
cropped_image.save(output_path)
print(f"已裁剪并保存: {output_path}")
# 调用函数进行裁剪
folder_path = 'D:\\Desktop\\CycleGAN_init_images_100pics'
output_folder = 'D:\\Desktop\\CycleGAN\\pytorch-CycleGAN-and-pix2pix-master\\datasets\\gas_images_512'
crop_images_to_512(folder_path, output_folder)