首先打开数据集,将人脸检测出来并对图片进行裁剪
import dlib # 人脸识别的库dlib
import numpy as np # 数据处理的库numpy
import cv2 # 图像处理的库OpenCv
import os
# dlib预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 读取图像的路径
path_read = "D:\\Firefox_download\\genki4k\\files"
num = 0
for file_name in os.listdir(path_read):
# aa是图片的全路径
aa = (path_read + "/" + file_name)
# 读入的图片的路径中含非英文
img = cv2.imdecode(np.fromfile(aa, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
# 获取图片的宽高
img_shape = img.shape
img_height = img_shape[0]
img_width = img_shape[1]
# 用来存储生成的单张人脸的路径
path_save = "D:\\Firefox_download\\genki4k\\files1"
# dlib检测
dets = detector(img, 1)
print("人脸数:", len(dets))
for k, d in enumerate(dets):
if len(dets) > 1:
continue
num = num + 1
# 计算矩形大小
# (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):
if d.top() + i >= img_height: # 防止越界
continue
for j in range(width):
if d.left() + j >= img_width: # 防止越界
continue
img_blank[i][j] = img[d.top() + i][d.left() + j]
img_blank = cv2.resize(img_blank, (200, 200), interpolation=cv2.INTER_CUBIC)
cv2.imencode('.jpg', img_blank)[1].tofile(path_save + "\\" + "file" + str(num) + ".jpg") # 正确方法
代码:
import os, shutil
# 原始数据集路径
original_dataset_dir = 'D:\\Firefox_download\\genki4k\\files1'
# 新的数据集
base_dir = 'D:\\Firefox_download\\genki4k\\files2'
os.mkdir(base_dir)
# 训练图像、验证图像、测试图像的目录
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)
validation_dir = os.path.join(base_dir, 'validation')
os.mkdir(validation_dir)
test_dir = os.path.join(base_dir, 'test')
os.mkdir(test_dir)
train_cats_dir = os.path.join(train_dir, 'smile')
os.mkdir(train_cats_dir)
train_dogs_dir = os.path.join(train_dir, 'unsmile')
os.mkdir(train_dogs_dir)
validation_cats_dir = os.path.join(validation_dir, 'smile')
os.mkdir(validation_cats_dir)
validation_dogs_dir = os.path.join(validation_dir, 'unsmile')
os.mkdir(validation_dogs_dir)
test_cats_dir = os.path.join(test_dir, 'smile')
os.mkdir(test_cats_dir)
test_dogs_dir = os.path.join(test_dir, 'unsmile')
os.mkdir(test_dogs_dir)
# 复制1000张笑脸图片到train_c_dir
fnames = ['file{}.jpg'.format(i) for i in range(1, 900)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(train_cats_dir, fname)
shutil.copyfile(src, dst)
fnames = ['file{}.jpg'.format(i) for i in range(900, 1350)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(validation_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 cat images to test_cats_dir
fnames = ['file{}.jpg'.format(i) for i in range(1350, 1800)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(test_cats_dir, fname)
shutil.copyfile(src, dst)
fnames = ['file{}.jpg'.format(i) for i in range(2127, 3000)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(train_dogs_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 dog images to validation_dogs_dir
fnames = ['file{}.jpg'.format(i) for i in range(3000, 3878)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(validation_dogs_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 dog images to test_dogs_dir
fnames = ['file{}.jpg'.format(i) for i in range(3000, 3878)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(test_dogs_dir, fname)
shutil.copyfile(src, dst)
这里是创建一个新文件夹,如果已有同名的,程序运行会报错
base_dir = 'D:\\Firefox_download\\genki4k\\files2'
os.mkdir(base_dir)
代码:
import cv2 # 图像处理的库 OpenCv
import dlib # 人脸识别的库 dlib
import numpy as np # 数据处理的库 numpy
class face_emotion():
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
self.cap = cv2.VideoCapture(0)
self.cap.set(3, 480)
self.cnt = 0
def learning_face(self):
line_brow_x = []
line_brow_y = []
while(self.cap.isOpened()):
flag, im_rd = self.cap.read()
k = cv2.waitKey(1)
# 取灰度
img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
faces = self.detector(img_gray, 0)
font = cv2.FONT_HERSHEY_SIMPLEX
# 如果检测到人脸
if(len(faces) != 0):
# 对每个人脸都标出68个特征点
for i in range(len(faces)):
for k, d in enumerate(faces):
cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0,0,255))
self.face_width = d.right() - d.left()
shape = self.predictor(im_rd, d)
mouth_width = (shape.part(54).x - shape.part(48).x) / self.face_width
mouth_height = (shape.part(66).y - shape.part(62).y) / self.face_width
brow_sum = 0
frown_sum = 0
for j in range(17, 21):
brow_sum += (shape.part(j).y - d.top()) + (shape.part(j + 5).y - d.top())
frown_sum += shape.part(j + 5).x - shape.part(j).x
line_brow_x.append(shape.part(j).x)
line_brow_y.append(shape.part(j).y)
tempx = np.array(line_brow_x)
tempy = np.array(line_brow_y)
z1 = np.polyfit(tempx, tempy, 1)
self.brow_k = -round(z1[0], 3)
brow_height = (brow_sum / 10) / self.face_width # 眉毛高度占比
brow_width = (frown_sum / 5) / self.face_width # 眉毛距离占比
eye_sum = (shape.part(41).y - shape.part(37).y + shape.part(40).y - shape.part(38).y +
shape.part(47).y - shape.part(43).y + shape.part(46).y - shape.part(44).y)
eye_hight = (eye_sum / 4) / self.face_width
if round(mouth_height >= 0.03) and eye_hight<0.56:
cv2.putText(im_rd, "smile", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 2,
(0,255,0), 2, 4)
if round(mouth_height<0.03) and self.brow_k>-0.3:
cv2.putText(im_rd, "unsmile", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 2,
(0,255,0), 2, 4)
cv2.putText(im_rd, "Face-" + str(len(faces)), (20,50), font, 0.6, (0,0,255), 1, cv2.LINE_AA)
else:
cv2.putText(im_rd, "No Face", (20,50), font, 0.6, (0,0,255), 1, cv2.LINE_AA)
im_rd = cv2.putText(im_rd, "S: screenshot", (20,450), font, 0.6, (255,0,255), 1, cv2.LINE_AA)
im_rd = cv2.putText(im_rd, "Q: quit", (20,470), font, 0.6, (255,0,255), 1, cv2.LINE_AA)
if (cv2.waitKey(1) & 0xFF) == ord('s'):
self.cnt += 1
cv2.imwrite("screenshoot" + str(self.cnt) + ".jpg", im_rd)
# 按下 q 键退出
if (cv2.waitKey(1)) == ord('q'):
break
# 窗口显示
cv2.imshow("Face Recognition", im_rd)
self.cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
my_face = face_emotion()
my_face.learning_face()
Python人脸识别微笑检测