Python-dlib实现人脸提取和分割

效果

参考资料和资源

GitHub - Onwaier/SegfaceAndAlignByDlib: 用dlib实现脸部分割和人脸对齐

shape_predictor_68_face_landmarks.dat 下载地址_shape_predictor_68_face_landmarks.dat下载-CSDN博客

未运行的参考资料 dlib实现脸部分割与人脸对齐 - 知乎

单图片读取并另存人脸图

"""
代码功能:
1. 用dlib人脸检测器检测出人脸,返回的人脸矩形框
2. 对检测出的人脸进行关键点检测并切割出人脸
"""
import cv2
import dlib
import numpy as np
import matplotlib.pyplot as plt

# In[]
imgname='1'
in_path = imgname+".jpg"
outpts = 100
out_path = imgname+'-face.jpg'
colorRGB=cv2.COLOR_BGR2RGB

# In[]
# cv2读取图像
img = cv2.imread(in_path)#,cv2.IMREAD_COLOR)BGR阵列是蓝脸,需要转换成正常色
img = cv2.cvtColor(img, colorRGB)
plt.imshow(img);

# In[]
predictor_model = 'shape_predictor_68_face_landmarks.dat'
detector = dlib.get_frontal_face_detector()# dlib人脸检测器
predictor = dlib.shape_predictor(predictor_model)
# In[]
# 人脸数rects
rects = detector(img, 0)
# faces存储full_object_detection对象
faces = dlib.full_object_detections()

for i in range(len(rects)):
    faces.append(predictor(img,rects[i]))

face_images = dlib.get_face_chips(img, faces, size=outpts)
for image in face_images:
    cv_bgr_img = cv2.cvtColor(image, colorRGB)
    cv2.imwrite(out_path, cv_bgr_img)

多个子文件夹另存人脸图:len(faces)

import os
import shutil
import warnings
import cv2
import io
import matplotlib.pyplot as plt
import dlib

from PIL import Image
warnings.filterwarnings("error", category=UserWarning)
PATH1 = "data300"
outpts = 120

sum = 0
colorRGB=cv2.COLOR_BGR2RGB

def is_read_successfully(file):
    try:
        imgFile = Image.open(file)
        return True
    except Exception:
        return False

def clipface(parent,file):
    in_path=os.path.join(parent, file)
    img = cv2.imread(in_path)#cv2.IMREAD_COLOR)BGR阵列是蓝脸,需要转换成正常色
    img = cv2.cvtColor(img, colorRGB)
    # plt.imshow(img);
    detector = dlib.get_frontal_face_detector()# dlib人脸检测器
    predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
    # 人脸数rects
    rects = detector(img, 0)
    # faces存储full_object_detection对象
    faces = dlib.full_object_detections()
    for i in range(len(rects)):
        faces.append(predictor(img,rects[i]))

    if len(faces)>0:
        # http://dlib.net/python/index.html#dlib_pybind11.get_face_chips
        face_images = dlib.get_face_chips(img, faces, size = outpts)
        for image in face_images:
            cv_bgr_img = cv2.cvtColor(image, colorRGB)
            if not os.path.exists('face'):
                os.makedirs('face')
            out_dir=os.path.join('face', parent)
            out_file=os.path.join('face', parent, file)
            if not os.path.exists(out_dir):
                os.makedirs(out_dir)
                print('newfolder '+ out_dir)
            cv2.imwrite(out_file, cv_bgr_img)
            print('doneclip '+ out_file)

if __name__=="__main__":
    #子文件夹
    for childlist in os.listdir(PATH1):
        #子文件夹路径
        childPATH = PATH1 + '/'+ str(childlist)
        for cpath, dirs, files in os.walk(childPATH):
            # print(cpath)
            if childlist=='0':
                print (childlist)
                for file in files:
                    in_file=os.path.join(cpath, file)
                    if not is_read_successfully(in_file):
                        print('cant open '+ in_file)
                    else:
                        sum+=1
                        print(str(sum)+ 'read ' +  in_file)
                        clipface(cpath,file)

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值