使用Pillow库实现的任意大小图像的裁剪,如果没有安装pillow库需要pip install pillow来进行pillow库的安装。代码对于输入图像的格式有要求只能是jpg或者png格式图像。tqdm是显示进度条的库,不需要的话可以直接删除,也可以使用pip install tqdm安装所需要的库。
import os
from PIL import Image
from tqdm import tqdm
folder_path = r''
#crop_size,裁剪后图像的大小
crop_size = 256
save_path = r''
if not os.path.exists(save_path):
os.makedirs(save_path)
temp = 1
for i,filename in enumerate(tqdm(os.listdir(folder_path))):
if filename.endswith('.jpg') or filename.endswith('.png'):
image = Image.open(os.path.join(folder_path, filename))
width, height = image.size
for top in range(0, height, crop_size):
for left in range(0, width, crop_size):
bottom = min(top + crop_size, height)
right = min(left + crop_size, width)
if bottom - top < crop_size:
top = bottom - crop_size
if right - left < crop_size:
left = right - crop_size
#这里是跳过裁剪后写出有问题的图像,继续执行下一步
try:
cropped_image = image.crop((left, top, right, bottom))
cropped_image.save(os.path.join(save_path,str(temp)+".jpg"))
temp += 1
except Exception as e:
print(filename)
pass