Python图片切割---用Python切出目标检测任务中的人脸并另存脸图

引:

    近期做CV方面算法,分享几个简单的视频、图片处理脚本

    脚本中均有print调试代码,,方便更改

 

用Python切出目标检测图中的标注人脸并另存脸图, 用于训练模型

# coding: utf-8
import os
import random

from PIL import Image

# data_path = '/home/ccpd/ccpd_dataset/ccpd_weather'
save_path = 'E:\\WIDER_FACE\\save_cut_0to19'


# 获取文件夹下所有文件名
def get_filename(path: str, file_list: list):
    for file_name in os.listdir(path):
        file_path = os.path.join(path, file_name)
        if os.path.isdir(file_path):
            print("文件夹, 跳过")
            continue
        file_list.append(file_name)
    file_list.sort()


# if not os.path.exists(data_path):
#     raise Exception(f'资源文件夹:{data_path} 不存在')
#
if not os.path.exists(save_path):
    os.makedirs(save_path)
#
# files = list()
# get_filename(data_path, files)
# total = len(files)


if __name__ == '__main__':
    f = open("E:\\WIDER_FACE\\wider_face_split\\wider_face_split\\WIDER_train2.txt", "r")
    lines = f.readlines()  # 读取全部内容 ,并以列表方式返回
    for line in lines:
        try:
            new_line_list = []
            b = []
            print(f'\n\n\nline: \n {line}')
            line_list = line.split(" ")
            print(f'line_list: {line_list}')
            jpg_path = line_list[1]
            print(f'jpg_path: {jpg_path}')
            jpg_name = jpg_path.split("\\")[-1]
            print(f'jpg_name: {jpg_name}')
            for i in range(4, len(line_list)):
                new_line_list.append(line_list[i])
            print(f'new_line_list, {new_line_list}')
            b = [new_line_list[i:i + 5] for i in range(0, len(new_line_list), 5)]
            print(f'b:  {b}\n')
            index = 0
            for box in b:
                print(f"b begin: {b}")
                x1, y1, x2, y2 = box[1], box[2], box[3], box[4]
                print(f'x1, y1, x2, y2: {x1}, {y1}, {x2}, {y2}')
                img = Image.open(jpg_path)
                # cut_img = img.crop((left, up, right, down))
                cut_img = img.crop((int(x1), int(y1), int(x2), int(y2)))
                cut_img.save(os.path.join(save_path, str(index) + "__" + jpg_name))
                print(f"b sub process: {b}")
                index += 1
            print(f"b end: {b}")
        except Exception as e:
            print("ERROR, e----------------------------------------------\n:", e, "\n--------------------------------")

  

posted @ 2022-03-11 14:28  张Star  阅读(425)  评论(0编辑  收藏  举报