python人脸切割

输入图像

 

 

 

输出:

 

# created at 2018-01-22
# updated at 2018-09-29
# Author:   coneypo
# Blog:     http://www.cnblogs.com/AdaminXie
# GitHub:   https://github.com/coneypo/Dlib_face_cut
import dlib         # 人脸识别的库dlib
import numpy as np  # 数据处理的库numpy
import cv2          # 图像处理的库OpenCv
import os
# 读取图像的路径
path_read = "./data/images/faces_for_test/1/0/"
# 用来存储生成的单张人脸的路径
path_save = "./data/images/img_small/"
# Delete old images
def clear_images():
    imgs = os.listdir(path_save)
    for img in imgs:
        os.remove(path_save + img)
    print("clean finish", '\n')
clear_images()
# Dlib 预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('data/dlib/shape_predictor_68_face_landmarks.dat')
# Dlib 检测

jj=1
for i in os.listdir(path_read):
    path_1read=path_read+i
    print(path_1read)
    img = cv2.imread(path_1read)
    a=img.shape
    jj=jj+1
    faces = detector(img, 1)
    print("人脸数:", len(faces), '\n')
    for k, d in enumerate(faces):
    # 计算矩形大小
    # (x,y), (宽度width, 高度height)
       pos_start = tuple([d.left(), d.top()])
       
    # 计算矩形框大小
       height = d.bottom()-d.top()
       if a[1]>=d.right():
          pos_end = tuple([d.right(), d.bottom()])
          width = d.right()-d.left()
       else:
          pos_end = tuple([a[1], d.bottom()])
          width =a[1]-d.left()
    # 根据人脸大小生成空的图像
       try:
          img_blank = np.zeros((height, width, 3), np.uint8)
          for i in range(height):
             for j in range(width):
                img_blank[i][j] = img[d.top()+i][d.left()+j]
    # cv2.imshow("face_"+str(k+1), img_blank)
    # 存在本地
          print("Save to:", path_save+"img_face_"+str(k+1)+".jpg")
          cv2.imwrite(path_save+"img_face3_"+str(k+1)+"_"+str(jj)+".jpg", img_blank)      
       except:
            print("发生异常")
       else:
            print("没有异常")
          
          

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值