当涉及到深度学习数据集的下采样时,裁剪图片的代码是至关重要的。通过裁剪图片,我们可以有效地减少数据集的大小,从而降低训练模型的计算成本和内存消耗。同时裁减图片也比直接letterbox图像更加精细,有利于模型最终的效果提升。
import os
from PIL import Image
def split_image_folder(folder_path, x_parts, y_parts):
parts = []
sum=0
for filename in os.listdir(folder_path):
if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".webp"):
image_path = os.path.join(folder_path, filename)
image = Image.open(image_path)
width, height = image.size
part_width = width // x_parts
part_height = height // y_parts
for y in range(y_parts):
for x in range(x_parts):
sum += 1
left = x * part_width
upper = y * part_height
right = (x + 1) * part_width
lower = (y + 1) * part_height
part = image.crop((left, upper, right, lower))
parts.append(part)
part.save(rf"F:\shixi\seglabels/GGB_{sum}.png")
print(sum)
# 调用函数并传入文件夹路径、拆分份数x_parts和y_parts
split_image_folder(r"your_img_path", x_parts=2, y_parts=2)
这段代码输入你的图片文件夹,然后可以选择x轴切几刀,y轴切几刀,保存路径在函数中自行设置。