Tensorflow + OpenCV实现简单的人脸识别

本文介绍了一种使用Tensorflow和OpenCV进行人脸识别的方法。首先在Windows环境下,利用Python、Tensorflow、OpenCV等库获取和处理人脸图像,包括用dlib进行人脸检测并裁剪为64x64尺寸。接着,将图像转化为适合训练的数据类型,最后通过卷积神经网络进行训练,以实现人脸识别。
摘要由CSDN通过智能技术生成

这段时间在学习卷积神经网络,为了对CNN有更深的了解和认识,便搞了一个简单的人脸识别作为练习。

运行环境

  • Windows
  • Python 3.x (tensorflow, opencv, numpy, sklearn, dlib)

获取人脸

第一步就是要获取用于训练的人脸图像,其中自己的人脸,我们使用程序来拍照,数量需求比较大,我用了12000张自己的人脸图像。
其他人人的人脸在网上找到,这里有一个人脸数据集:http://vis-www.cs.umass.edu/lfw/lfw.tgz

要获取人脸,首先要能检测出人脸来,OpenCV与dlib都能实现,OpenCV的检测速度更快,但是精度却不如dlib,这里我们采用dlib进行检测。这里我们将所有图片裁剪成64x64。

import cv2
import dlib
import os
import random

output_dir = './my_faces'
size = 64

if not os.path.exists(output_dir):
    os.makedirs(output_dir)


# 改变图片的亮度与对比度
def relight(image, light=1, bias=0):
    width = image.shape[1]
    height = image.shape[0]
    for w in range(0, width):
        for h in range(0, height):
            for c in range(3):
                tmp = int(image[h, w, c]*light + bias)
                if tmp > 255:
                    tmp = 255
                elif tmp < 0:
                    tmp = 0
                image[h, w, c] = tmp
    return img


# 使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0)
index = 1
while True:
    if index <= 10000:
        print('Being processed picture %s' % index)
        # 从摄像头读取照片
        success, img = camera.read()
        # 转为灰度图片
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 使用detector进行人脸检测
        dets = detector(gray_img, 1)
        for i, d in enumerate(dets):
            x1 = d.top() if d.top() > 0 else 0
            y1 = d.bottom() if d.bottom() > 0 else 0
            x2 = d.left() if d.left() > 0 else 0
            y2 = d.right() if d.right() > 0 else 0

            face = img[x1:y1, x2:y2]
            # 调整图片的对比度与亮度, 对比度与亮度值都取随机数,这样能增加样本的多样性
            face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))

            face = cv2.res
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值