Bootstrap

python 实现根据bbox对人脸进行裁剪

任务要求描述:根据CelebA的人脸bbox标签,对其进行裁剪,并保存至目标文件夹

代码:

import os
from PIL import Image
import matplotlib.pyplot as plt

label_position_path = r"H:\CelebA\Save\img_celeba\Anno\train_list_bbox_celeba.txt"
handel_path = r"H:\CelebA\Save\crop_train_img_celeba"  # 处理完样本保存路径
image_path = r"H:\CelebA\Save\img_celeba\Train"   # 图片路径
if not os.path.exists(handel_path):
    os.mkdir(handel_path)
img_list = []
f_position = open(label_position_path).readlines()  # 读入人脸位置标签
for index in range(len(f_position)):
    if index < 2:
        continue
    strs_postion = f_position[index].strip().split(" ")
    strs_postion = list(filter(bool, strs_postion))
    filename = strs_postion[0]
    print(filename)
    x1 = float(strs_postion[1])
    y1 = float(strs_postion[2])
    w = float(strs_postion[3])
    h = float(strs_postion[4])
    x2 = x1 + w
    y2 = y1 + h
    image = Image.open(os.path.join(image_path, filename))  # open只能打开一个具体的文件,而不能打开一个文件夹,否则会报denied error
    img = image.crop((x1, y1, x2, y2))  # crop只能接受一个值,必须将四个值用括号括起来
    img_list.append(img)
    for temp in img_list:
        temp.save(os.path.join(handel_path,os.path.basename(filename)))
;