人脸的图像的切割以检测为前提,以下是切割过程总结
1、python实现:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#!/usr/bin/python
import dlib # 人脸识别库
import numpy as np #数据处理库
import cv2 # 图像处理库
detector = dlib.get_frontal_face_detector()#与人脸检测相同,使用dlib自带的frontal_face_detector作为人脸检测器
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')#使用官方提供的模型构建特征提取器
#读取图像
path = "/home/sunwen/image/"
img = cv2.imread(path+"friend0.jpg")
#print("img/shape:", img.shape)
dets = detector(img)
print("人脸数", len(dets))
height_max = 0
width_sum = 0
# 计算要生成的图像img_blank大小
for k, d in enumerate(dets):
# 计算矩形大小
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("img_blank的大小:")
print("高度", height_max, "宽度", width_sum)
img_blank = np.zeros((height_max, width_sum, 3), np.uint8)
blank_start = 0
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", 2)
cv2.imshow("img_faces", img_blank)
#cv2.imwrite("img_new.jpg", img_blank)
cv2.waitKey(0)
结果
剪切的人脸保存如下:
2、Matlab实现:
clc;
clear;
faceDetector = vision.CascadeObjectDetector();
file_path='E:/database/Normal/';
path_list=dir(strcat(file_path,'*.tif'));
img_num=length(path_list);
if img_num>0
for j=1:img_num
image_name=path_list(j).name;
I=imread(strcat(file_path,image_name));
bbox=step(faceDetector,I);
faceOut = insertObjectAnnotation(I,'rectangle',bbox,'face');
faceout1=imcrop(I,bbox);
faceout2=imresize(faceout1,[80,80]);
imwrite(faceout2,strcat(num2str(j+1004),'.tif'));
end
end
运行结果: