• opencv人脸数据收集


    项目中收到7000多张图片需要找到图片中最大的人脸并且裁剪出来,保存到指定的目录下,用python+opencv写的脚本代码如下:

    import cv2
    import os

    class FaceCrop:
    #初始化函数
    def __init__(self):
    self.number = 0
    self.face_image_dir = "F:/temp/origin"
    self.face_image_path = "F:/temp/result1"
    self.face_detector=cv2.CascadeClassifier(
    'haarcascade_frontalface_default.xml'
    )
    list = os.listdir(self.face_image_dir)
    for i in range(0, len(list)):
    print(list[i])
    path = os.path.join(self.face_image_dir, list[i])
    img = cv2.imread(path)
    myImg, max_face = self.face_collect(img)
    if (max_face[0] < 0) or (max_face[1] < 0):
    continue
    # if max_face == [-80, -80, 160, 300]:
    # continue
    print(max_face)
    self.face_save(myImg, max_face)

    #找出面积最大的矩形
    def max_matrix(self, matrixs):
    max_matrix=[0,0,0,0]
    for [x,y,w,h] in matrixs:
    if w*h >= max_matrix[2]*max_matrix[3]:
    max_matrix=[x,y,w,h]
    max_matrix[0] = max_matrix[0] - 80
    max_matrix[1] = max_matrix[1] - 80
    max_matrix[2] = max_matrix[2] + 160
    max_matrix[3] = max_matrix[3] + 300
    return max_matrix

    # 给图片绘制矩形
    # def plot_rectangle(self, img, matrix):
    # cv2.rectangle(img, (matrix[0], matrix[1]), (matrix[0] + matrix[2], matrix[1] + matrix[3]),
    # (255, 0, 0), 2)

    # 人脸检测,标记并返回检测到的最大的人脸,用于人脸识别
    def face_collect(self, img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = self.face_detector.detectMultiScale(gray, 1.2, 8)
    max_face = self.max_matrix(faces)
    # self.plot_rectangle(img, max_face)
    return img, max_face

    # 保存人脸照片
    def face_save(self, img, max_face):
    # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    if max_face[2] > 30:
    self.number = self.number + 1
    print(self.number)
    print(
    self.face_image_path + "/" + str(self.number) + ".jpg"
    )
    cv2.imwrite(
    self.face_image_path + '/' + str(self.number) + '.jpg',
    img[max_face[1]:max_face[1] + max_face[3], max_face[0]:max_face[0] + max_face[2]]
    )
    return

    if __name__=="__main__":
    f=FaceCrop()
  • 相关阅读:
    谷歌BERT预训练源码解析(二):模型构建
    python 直接if判断和is not None的区别
    pytorch nn.Embedding
    独家 | TensorFlow 2.0将把Eager Execution变为默认执行模式,你该转向动态计算图了
    Facebook 发布深度学习工具包 PyTorch Hub,让论文复现变得更容易
    Hive与数据库的异同
    Linux自动删除n天前备份
    Haproxy安装与配置
    Nagios监控磁盘
    Nagios监控Oralce
  • 原文地址:https://www.cnblogs.com/hua-sheng/p/15245864.html
Copyright © 2020-2023  润新知