最近在做人脸识别,需要对人脸数据集进行处理,对一张或批量图像的人脸进行切割分离,并且另保存下来。受网上开源工具的启发,在借鉴他人的基础上进行了改进,使得更加方便实用。
以下代码是改进版,分为两部分功能:
- 一张人脸图片切割并显示,不保存
- 一张/批量人脸图像切割并保存
在这里需要申明一下,尊重原著!(转发需要标注一下原著信息)
原创版:
Author: coneypo
Blog: http://www.cnblogs.com/AdaminXie
GitHub: https://github.com/coneypo/Dlib_face_cut
改进版:
Improver: Cai_90hou
Blog: https://blog.csdn.net/qq_38677310/article/details/84702662
Github:
#crop_faces_show.py
import dlib # 人脸识别的库dlib
import numpy as np # 数据处理的库numpy
import cv2 # 图像处理的库OpenCv
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# 读取图像
path = "faces_for_test/"
img = cv2.imread(path+"test_faces_1.jpg")
# Dlib 检测
dets = detector(img, 1)
print("检测到的人脸数 / faces :", len(dets), "\n")
# 记录人脸矩阵大小
height_max = 0
width_sum = 0
# 计算要生成的图像 img_blank 大小
for k, d in enumerate(dets):
# 计算矩形大小
# (x,y), (宽度width, 高度height)
pos_start = tuple([d.left(), d.top()])
pos_end = tuple([d.right(), d.bottom()])
# 计算矩形框大小
height = d.bottom()-d.top()
width = d.right()-d.left()
# 处理宽度
width_sum += width
# 处理高度
if height > height_max:
height_max = height
else:
height_max = height_max
# 绘制用来显示人脸的图像的大小
print("窗口大小:"
, '\n', "高度 / height :", height_max
, '\n', "宽度 / width : ", width_sum)
# 生成用来显示的图像
img_blank = np.zeros((height_max, width_sum, 3), np.uint8)
# 记录每次开始写入人脸像素的宽度位置
blank_start = 0
# 将人脸填充到img_blank
for k, d in enumerate(dets):
height = d.bottom()-d.top()
width = d.right()-d.left()
# 填充
for i in range(height):
for j in range(width):
img_blank[i][blank_start+j] = img[d.top()+i][d.left()+j]
# 调整图像
blank_start += width
cv2.namedWindow("img_faces", 0)
cv2.imshow("img_faces", img_blank)
cv2.waitKey(0)
#crop_faces_save.py
import dlib # 人脸识别的库dlib
import numpy as np # 数据处理的库numpy
import cv2 # 图像处理的库OpenCv
import os
#切割后的人脸序号,为全局变量
image_num = 0
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# 读取图像的路径
path_read = "faces_for_test/"
#img = cv2.imread(path_read+"test_faces_3.jpg")
# 用来存储生成的单张人脸的路径
path_save = "faces_separated/"
#将文件夹中待处理的图片存于列表中
imgs_read = os.listdir(path_read) #源地址文件夹
imgs_write = os.listdir(path_save) #存储地址文件夹
# Delete old images
def clear_images():
for img in imgs_write:
os.remove(path_save + img)
print("clean finish", '\n')
#处理一张图片:
def cut_one_photo(img):
global image_num
# Dlib 检测
faces = detector(img, 1)
print("人脸数:", len(faces))
for k, d in enumerate(faces):
# 计算矩形大小
# (x,y), (宽度width, 高度height)
pos_start = tuple([d.left(), d.top()])
pos_end = tuple([d.right(), d.bottom()])
# 计算矩形框大小
height = d.bottom()-d.top()
width = d.right()-d.left()
# 根据人脸大小生成空的图像
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+"CWH"+str(image_num+1)+".jpg")
print("Save to:", "img_face" + str(image_num + 1) + ".jpg")
cv2.imwrite(path_save + "img_face" + str(image_num + 1) + ".jpg", img_blank)
image_num += 1
#批量处理图片
def cut_batch_photoes():
clear_images() #清除原有图片
for img in imgs_read:
try:
path = os.path.join(path_read, img)
image = cv2.imread(path)
cut_one_photo(image)
print('\n')
except:
continue
print('Successful operation!\n')
print('total number of faces: ', image_num)
def main():
# 批量处理图片并保存
cut_batch_photoes()
if __name__ == '__main__':
main()