将图片按照指定大小批量进行裁剪(可设置步长_python)
import os
from PIL import Image
Image.MAX_IMAGE_PIXELS = None def crop_image(image_path, block_size=(640, 640), step_size=(340, 340)):img = Image.open(image_path)img_width, img_height = img.sizeblock_width, block_height = block_sizecropped_images = []for top in range(0, img_height, step_size[1]): for left in range(0, img_width, step_size[0]): right = min(left + block_width, img_width)bottom = min(top + block_height, img_height)cropped_image = img.crop((left, top, right, bottom))cropped_images.append(cropped_image)return cropped_imagesdef crop_images_in_folder(input_folder, output_folder, block_size=(640, 640), step_size=(340, 340)):if not os.path.exists(output_folder):os.makedirs(output_folder)for filename in os.listdir(input_folder):if filename.lower().endswith(('.png', '.jpg', '.jpeg')):image_path = os.path.join(input_folder, filename)cropped_images = crop_image(image_path, block_size, step_size)for i, cropped_img in enumerate(cropped_images):output_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}_cropped_{i}.jpg")cropped_img.save(output_path)print(f"保存裁剪图像: {output_path}")
input_folder = r"D:\BaiduNetdiskDownload\数据"
output_folder = r"D:\BaiduNetdiskDownload\图片裁剪"
block_size = (640, 640)
step_size = (340, 340)
crop_images_in_folder(input_folder, output_folder, block_size, step_size)