Face Recognition 人脸识别

face_recognition库的使用 ​ face_recognition库基于dlib的使用,包含dlib的安装,及face_recognition库各个方法的使用 阅读详情

Face Recognition 人脸识别

python,face_recognition



简介

face_recognition项目是世界上最简洁的人脸识别库,可以使用Python和命令行工具提取、识别、操作人脸。
本项目的人脸识别是基于业内领先的C++开源库 dlib中的深度学习模型,用Labeled Faces in the Wild人脸数据集进行测试,有高达99.38%的准确率。但对小孩和亚洲人脸的识别准确率尚待提升。
Labeled Faces in the Wild是美国麻省大学安姆斯特分校(University of Massachusetts Amherst)制作的人脸数据集,该数据集包含了从网络收集的13,000多张面部图像。
本项目提供了简易的face_recognition命令行工具,你可以用它处理整个文件夹里的图片。

人脸识别实际上是对人脸进行编码后再去计算两两人脸的相似度,known_image是已知人脸库的图像,unknown_image是待检测的图像,分别利用face_encodings函数来映射成一个向量,再利用两个向量的内积来衡量相似度,compare_faces函数就是根据阈值确认是否是同一人脸。上述函数都是支持多个人脸计算的。另外compare_faces有个tolerance参数是控制阈值的,tolerance值越低越严格,默认为0.6。


搭建环境

系统MacOS10.13.6; python3.6; IDE:pycharm.

通过python的face_recognition模块实现人脸检测功能,首先需要安装好face_recognition包:
可通过pycharm直接安装,也可以用pip安装,还可以通过anaconda安装。不知道是我家网不好还是怎么的,用pycharm没查找到face_recognition的包,所以是用后两种方法安装上的。

  • 用pip直接安装face_recognition发现它依赖于dlib,而dlib依赖Boost和cmake,所以先装这两个再装dlib最后才装得上face_recognition:
$ pip3 install CMake
$ pip3 install opencv-python
$ pip3 install dlib
$ pip3 install face_recognition
#最终出现以下打印表示安装成功
#Successfully installed Click-7.0 face-recognition-1.2.3 face-recognition-models-0.3.0
  • 用anaconda安装更简单,找到要安装的环境,直接Search Packages,注意类别要选成Not installed或者all,否则默认是在安装过的包里查找的。

以上两种安装方法安装完后,在pycharm中相应的interpreter下就能看到已经装上的包。


主要方法介绍

以下方法都是face_recognition模块中常用的函数和方法:

1. load_image_file 加载图像

import face_recognition之后直接调用face_recognition.load_image_file()读入图像,参数给文件名字符串,注意:jpg文件要和程序放在同一个文件夹下。输出图像是rgb格式(opencv中是bgr格式)。

import face_recognition
#加载图像文件
image = face_recognition.load_image_file("your_file.jpg")

2. face_locations 定位图中所有人脸

加载图像文件后直接调用face_recognition.face_locations(image),能定位所有图像中识别出的人脸位置信息,返回值是列表形式,列表中每一行是一张人脸的位置信息,包括[top, right, bottom, left],也可理解为每个人脸是一个tuple存储,分别代表框住人脸的矩形中左上角和右下角的坐标(x1,y1,x2,y2)。可遍历列表打印出每张脸的位置信息,也可以通过位置信息截出识别出的人脸的图像显示出来,代码如下:

#定位所有找到的脸的位置
face_locations = face_recognition.face_locations(image)
# 循环找到的所有人脸
for face_location in face_locations:
        # 打印每张脸的位置信息
        top, right, bottom, left = face_location
        print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
        # 指定人脸的位置信息,然后显示人脸图片
        face_image = image[top:bottom, left:right]
        pil_image = Image.fromarray(face_image)
        pil_image.show()

3. face_landmarks 识别人脸关键点

加载图像后,调用face_recognition.face_landmarks(image)可识别出人脸关键点信息,包括眼睛、鼻子、嘴巴和下巴等,参数仍是加载的图像image,返回值是包含面部特征字典的列表,列表中每一项对应一张人脸,包括nose_bridge、right_eyebrow、right_eye、chine、left_eyebrow、bottom_lip、nose_tip、top_lip、left_eye几个部分,每个部分包含若干个特征点(x,y),总共有68个特征点。列表长度就是图中识别出的人脸数,可遍历此列表和字典的键值对,打印出所有面部特征点,也可在图像上画出来,代码如下:

from PIL import Image, ImageDraw
face_landmarks_list = face_recognition.face_landmarks(image)
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)
for face_landmarks in face_landmarks_list:
    #face_landmarks_list中每个元素都包含以下key的字典
    #打印此图像中每个面部特征的位置
    facial_features = [
        'chin',
        'left_eyebrow',
        'right_eyebrow',
        'nose_bridge',
        'nose_tip',
        'left_eye',
        'right_eye',
        'top_lip',
        'bottom_lip'
    ]
    for facial_feature in facial_features:
        print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))
    #在图像中画出每个人脸特征!
    for facial_feature in facial_features:
        d.line(face_landmarks[facial_feature], width=5)
pil_image.show()

4. face_encodings 获取图像文件中所有面部编码

face_recognition.face_encodings(image)方法可获取每个图像文件中每个面部的面部编码,参数仍是加载的图像image,由于每个图像中可能有多个脸,所以返回的是一个编码列表,后续访问时注意加上索引号或者依次遍历。
由打印可看出每张人脸是一个128维的向量。

face_encodings = face_recognition.face_encodings(image)
for face_encoding in face_encodings:
    print("face_encoding len = {} \nencoding:{}\n\n".format(len(face_encoding),face_encoding))

5. compare_faces 由面部编码匹配脸

用face_recognition.compare_faces()方法可匹配两个面部特征编码,利用两个向量的内积来衡量相似度,根据阈值确认是否是同一人脸。
位置参数:第一个参数给出一个面部编码列表(很多张脸),第二个参数给出单个面部编码(一张脸),compare_faces方法会将第二个参数的编码与第一个参数中的编码依次匹配,返回值是一个布尔值列表,匹配成功的脸返回True,匹配失败的返回False,顺序与第一个参数中脸的顺序一致。
默认参数:tolerance=0.6,可根据自己需求更改,tolerance越小匹配越严格,例如
matches = face_recognition.compare_faces(known_face_encodings, face_encoding,tolerance=0.39),将阈值改为了0.39,阈值太低容易造成无法成功识别人脸,太高容易造成人脸识别混淆,这个是根据我自己测试后慢慢试出来的一个值。

matche_result = face_recognition.compare_faces(known_faces, face_encoding[0],tolerance=0.39)[0]

实践

demo1:识别人脸特征并打印出来

# -*- coding: utf-8 -*-
# 自动识别人脸特征
# filename : find_facial_features_in_picture.py

from PIL import Image, ImageDraw
import face_recognition

# 将jpg文件加载到numpy 数组中
image = face_recognition.load_image_file("view_Mr_G.jpg")

#查找图像中所有面部的所有面部特征
face_landmarks_list = face_recognition.face_landmarks(image)

print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)
for face_landmarks in face_landmarks_list:
    #打印此图像中每个面部特征的位置
    facial_features =
face_recognition(人脸识别) 是一个非常流行的 Python 库,专门用于人脸识别任务。它基于 dlib 库和 HOG(Histogram of Oriented Gradients)特征以及深度学习模型,提供了简单易用的接口来进行人脸检测、面部特征点定位和人脸识别。库由 Adam Geitgey 开发,旨在简化人脸识别任务,使其更加容易上手。 阅读详情

相关推荐

【人脸识别】Face Recognition 入门

找论文搭配 Sci-Hub 食用更佳 💪 Sci-Hub 实时更新 : https://tool.yovisun.com/scihub/ 公益科研通文献求助:https://www.ablesci.com/人脸识别流程:检测、对齐、(活体)、预处理、提取特征(表示)、人脸识别(验证) 传统方法试图通过一两层表示来识别人脸,例如过滤响应、特征直方图分布。学术圈进行了深入的研究,分别改进了预处理、局部描述符和特征转换,但这些方法在提高FR准确性方面进展缓慢。更糟糕的是,大多数方法只针对不受约束的面部变化的一

ydd的博客,记录生活 2932

基于face_recognition的人脸识别

随着人工智能技术的飞速发展,人脸识别技术已成为计算机视觉领域的一个重要分支。本文提出了一个基于Python 'face_recognition'库的视频人脸识别系统,该系统能够实时检测视频中的人脸,并识别出已知个体。'face_recognition'库以其易用性和准确性而闻名,它基于dlib的深度学习模型,能够快速准确地识别和比较面部特征。

weixin_63091390的博客 2621

face_recognition人脸识别

face_recognition人脸识别 face_recognition简介 这是世界上最简单的人脸识别库了。你可以通过Python引用或者命令行的形式使用它,来管理和识别人脸。 该软件包使用dlib中最先进的人脸识别深度学习算法,使得识别准确率在《Labled Faces in the world》测试基准下达到了99.38%。它同时提供了一个叫face_recognition的命令行工具,以...

matafeiyanll的博客 6505

Github开源人脸识别项目face_recognition

face_recognition模块安装 # 安装 face_recognition(pip3命令下载的是python3对应的版本,pip命令下载的是python2对应的版本) $ pip3 install face_recognition # 安装face_recognition过程中会自动安装 numpy、scipy 等 使用方法 命令行界面 当你安装好了本项目,你可以使用两种命...

一行一生 4821

人脸识别 face_recognition

Github开源人脸识别项目face_recognition,face_recognition是一个强大、简单、易上手的人脸识别开源项目 安装 pip install face_recognition 导入face_recognition模块 import face_recognition load_image_file 加载图像 调用face_recognition.load_image_file()读入图像。输出图像是rgb格式(opencv中是bgr格式) import face_recog

我不是码农的博客~~~ 1275

智能车实战——极速越野组GPS与惯导融合定位导航全解析

本文深入解析了智能车极速越野组中GPS与惯导模块的融合定位导航技术。通过对比GPS的全局定位与惯导的高频姿态感知,详细阐述了如何利用MM32SPN27主控,将两者数据融合以实现精准、实时的车辆控制。内容涵盖硬件选型、软件数据处理、PID控制及系统调试等实战环节,为智能车开发者提供了一套完整的解决方案。

pz8901234的博客 1221

零基础转行AI产品经理:从技术小白到实战入行的完整路径

人工智能技术正在重塑互联网产品岗位的职责边界。AI产品经理并不等同于“会用AI工具”,而是需要理解模型能力边界、掌握技术对话能力,并能将模糊需求转化为可落地的产品方案。大模型、RAG检索增强、Agent智能体等概念构成了当前AI应用的核心技术栈,理解它们的原理与适用场景,是评估需求可行性、设计容错机制的基础。从智能客服到知识库问答,这些典型应用场景背后都离不开对技术方案选型与数据质量的判断。对于非技术背景的转行者而言,真正的门槛并非算法公式,而是能否建立系统认知、动手做出Demo,并具备产品基本功。本文基于

weixin_30641597的博客 289

大红球预警版-精选+自定义板块监控

这是一款简单易用的股票大单资金监控插件,兼容通达信软件,可嵌入分时图或定制版面。它以红绿圆球直观显示主力买卖情况(红球为买,绿球为卖),支持300万以上大单语音播报。插件提供实时资金流向分析、多股同时监控、自定义预警条件等功能,无需L2账号。用户可自由切换图形/列表模式,监控特定板块,并配合幻影软件实现自动交易。虽然上涨股通常红球占优,但需结合其他指标综合判断。该插件完全免费,包含详细视频教程,适合新手使用。

guleba的博客 1815

【量化交易】迅投QMT——基础操作新建策略导入策略!

策略指标 #基础操作 #新建策略 在【我的】主页,点击新建策略按钮 点击【pyhton策略】模型 会弹出一个策略编辑器框 【新建策略文件】 编辑完点击【编译】按钮 关闭策略编辑器 导入策略 券商 QMT:1. 点击进入【模型研究】界面2. 右键 -> 选择本地. rzrk导入 投研端:1. 点击【行情】界面,选择模型2. 右键 -> 选择本地. rzrk导入 #策略在副图作为指标运行 在主图上双击策略 VBA策略可以直接输出图像

weixin_eng02048的博客 4142

全能媒体工具深度测评(下篇一):AI图文生成+全能解压+图片去文字,一键搞定素材精修

解压50多种格式,文生图,图生图

cs821984831的博客 60

(四)美赛画图篇:画图模板+画图工具

美赛画图篇:画图模板+画图工具(一)画图模板(二)画图工具 因为散点图、折线图等多与数据有关,且需相关软件生成,故此处多是通用模板。直接替换文字内容即可。 (一)画图模板 1、Visio圆圈图 适合于:指标体系(E题常用) 点击下载:1 C币 如果不想花费且时间充足,悄咪咪地说,在visio-模板搜索可以找到很多。(稍微会耗一点时间) 2、简单指标体系图PPT 适合于指标体系 点击下载:0 C币...

weixin_43689393的博客 1万+

NLP高频面试题(一)——Transformer的基本结构、作用和代码实现

本文详细介绍了Transformer模型的基本结构和PyTorch代码实现过程。首先解析了Transformer的核心组成部分,包括嵌入层、多头自注意力机制、位置编码、前馈神经网络、编码器和解码器等模块,并通过清晰的代码示例逐步展示了如何在PyTorch中构建完整的Transformer模型。文末提供了一个可运行的简单示例,帮助读者快速理解并实践Transformer的核心原理与实现方法。

WeLearnNLP 1036

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

上一篇: 【leetcode】解数独
下一篇: 【python】OpenCV
view1994
博客等级 码龄8年 21粉丝 18原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值