热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

TensorFlow人脸识别OpenFaceFacerecognitionInsightface和FaceNet源码运行

篇首语:本文由编程笔记#小编为大家整理,主要介绍了TensorFlow人脸识别OpenFaceFace-recognitionInsightface和FaceNet源码运行相关的知识,希望对你有

篇首语:本文由编程笔记#小编为大家整理,主要介绍了TensorFlow人脸识别OpenFaceFace-recognitionInsightface和FaceNet源码运行相关的知识,希望对你有一定的参考价值。


比较人脸识别OpenFace、Face-recognition、Insightface:

FaceNet源码运行

https://github.com/davidsandberg/facenet

1、使用Anaconda安装TensorFlow;

2、更新scipy库;

3、添加os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.

4、下载模型:20180402-114759模型路径

python compare.py 20180402-114759 02.jpg 11.jpg

"""Performs face alignment and calculates L2 distance between the embeddings of images."""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from scipy import misc
import tensorflow as tf
import numpy as np
import sys
import os
import copy
import argparse
import facenet
import align.detect_face
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def main(args):
images = load_and_align_data(args.image_files, args.image_size, args.margin, args.gpu_memory_fraction)
with tf.Graph().as_default():
with tf.Session() as sess:

# Load the model
facenet.load_model(args.model)

# Get input and output tensors
images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
# Run forward pass to calculate embeddings
feed_dict = images_placeholder: images, phase_train_placeholder:False
emb = sess.run(embeddings, feed_dict=feed_dict)

nrof_images = len(args.image_files)
print('Images:')
for i in range(nrof_images):
print('%1d: %s' % (i, args.image_files[i]))
print('')

# Print distance matrix
print('Distance matrix')
print(' ', end='')
for i in range(nrof_images):
print(' %1d ' % i, end='')
print('')
for i in range(nrof_images):
print('%1d ' % i, end='')
for j in range(nrof_images):
dist = np.sqrt(np.sum(np.square(np.subtract(emb[i,:], emb[j,:]))))
print(' %1.4f ' % dist, end='')
print('')


def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):
minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
factor = 0.709 # scale factor

print('Creating networks and loading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)

tmp_image_paths=copy.copy(image_paths)
img_list = []
for image in tmp_image_paths:
img = misc.imread(os.path.expanduser(image), mode='RGB')
img_size = np.asarray(img.shape)[0:2]
bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
if len(bounding_boxes) <1:
image_paths.remove(image)
print("can&#39;t detect face, remove ", image)
continue
det &#61; np.squeeze(bounding_boxes[0,0:4])
bb &#61; np.zeros(4, dtype&#61;np.int32)
bb[0] &#61; np.maximum(det[0]-margin/2, 0)
bb[1] &#61; np.maximum(det[1]-margin/2, 0)
bb[2] &#61; np.minimum(det[2]&#43;margin/2, img_size[1])
bb[3] &#61; np.minimum(det[3]&#43;margin/2, img_size[0])
cropped &#61; img[bb[1]:bb[3],bb[0]:bb[2],:]
aligned &#61; misc.imresize(cropped, (image_size, image_size), interp&#61;&#39;bilinear&#39;)
prewhitened &#61; facenet.prewhiten(aligned)
img_list.append(prewhitened)
images &#61; np.stack(img_list)
return images
def parse_arguments(argv):
parser &#61; argparse.ArgumentParser()

parser.add_argument(&#39;model&#39;, type&#61;str,
help&#61;&#39;Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file&#39;)
parser.add_argument(&#39;image_files&#39;, type&#61;str, nargs&#61;&#39;&#43;&#39;, help&#61;&#39;Images to compare&#39;)
parser.add_argument(&#39;--image_size&#39;, type&#61;int,
help&#61;&#39;Image size (height, width) in pixels.&#39;, default&#61;160)
parser.add_argument(&#39;--margin&#39;, type&#61;int,
help&#61;&#39;Margin for the crop around the bounding box (height, width) in pixels.&#39;, default&#61;44)
parser.add_argument(&#39;--gpu_memory_fraction&#39;, type&#61;float,
help&#61;&#39;Upper bound on the amount of GPU memory that will be used by the process.&#39;, default&#61;1.0)
return parser.parse_args(argv)
if __name__ &#61;&#61; &#39;__main__&#39;:
main(parse_arguments(sys.argv[1:]))

运行结果&#xff1a; 

(py27tf) bash-3.2$ python compare.py 20180402-114759 02.jpg 11.jpg
Creating networks and loading parameters
2019-01-15 17:11:02.874055: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
2019-01-15 17:11:02.874720: I tensorflow/core/common_runtime/process_util.cc:69] Creating new thread pool with default inter op setting: 8. Tune using inter_op_parallelism_threads for best performance.
Model directory: 20180402-114759
Metagraph file: model-20180402-114759.meta
Checkpoint file: model-20180402-114759.ckpt-275
WARNING:tensorflow:From /anaconda2/envs/py27tf/lib/python2.7/site-packages/tensorflow/python/training/queue_runner_impl.py:391: __init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.
Instructions for updating:
To construct input pipelines, use the &#96;tf.data&#96; module.
Images:
0: 02.jpg
1: 11.jpg
Distance matrix
0 1
0 0.0000 0.4207
1 0.4207 0.0000

MTCNN实时检测人脸&#xff1a;

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six import string_types, iteritems
import sys
import os
import numpy as np
import tensorflow as tf
#from math import floor
import cv2
import detect_face
import random
from time import sleep
os.environ["KMP_DUPLICATE_LIB_OK"]&#61;"TRUE"
video &#61; cv2.VideoCapture(0)
print(&#39;Creating networks and loading parameters&#39;)
with tf.Graph().as_default():
gpu_options &#61; tf.GPUOptions(per_process_gpu_memory_fraction&#61;1.0)
sess &#61; tf.Session(config&#61;tf.ConfigProto(gpu_options&#61;gpu_options, log_device_placement&#61;False))
with sess.as_default():
pnet, rnet, onet &#61; detect_face.create_mtcnn(sess, None)
minsize &#61; 20
threshold &#61; [0.6, 0.7, 0.7]
factor &#61; 0.709
while True:
ret, frame &#61; video.read()
bounding_boxes, _ &#61; detect_face.detect_face(frame, minsize, pnet, rnet, onet, threshold, factor)
nrof_faces &#61; bounding_boxes.shape[0]
print(&#39;face number :&#39;.format(nrof_faces))
for face_position in bounding_boxes:
face_position &#61; face_position.astype(int)
cv2.rectangle(frame, (face_position[0], face_position[1]), (face_position[2], face_position[3]), (0, 255, 0), 2)
cv2.imshow(&#39;show&#39;, frame)
if cv2.waitKey(5) & 0xFF &#61;&#61; ord(&#39;q&#39;):
break
video.release()
cv2.destroyAllWindows()

 


推荐阅读
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 本文比较了eBPF和WebAssembly作为云原生VM的特点和应用领域。eBPF作为运行在Linux内核中的轻量级代码执行沙箱,适用于网络或安全相关的任务;而WebAssembly作为图灵完备的语言,在商业应用中具有优势。同时,介绍了WebAssembly在Linux内核中运行的尝试以及基于LLVM的云原生WebAssembly编译器WasmEdge Runtime的案例,展示了WebAssembly作为原生应用程序的潜力。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • 本文详细介绍了PHP中与URL处理相关的三个函数:http_build_query、parse_str和查询字符串的解析。通过示例和语法说明,讲解了这些函数的使用方法和作用,帮助读者更好地理解和应用。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • Java String与StringBuffer的区别及其应用场景
    本文主要介绍了Java中String和StringBuffer的区别,String是不可变的,而StringBuffer是可变的。StringBuffer在进行字符串处理时不生成新的对象,内存使用上要优于String类。因此,在需要频繁对字符串进行修改的情况下,使用StringBuffer更加适合。同时,文章还介绍了String和StringBuffer的应用场景。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 本文介绍了为什么要使用多进程处理TCP服务端,多进程的好处包括可靠性高和处理大量数据时速度快。然而,多进程不能共享进程空间,因此有一些变量不能共享。文章还提供了使用多进程实现TCP服务端的代码,并对代码进行了详细注释。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
author-avatar
哥小名叫青蛙
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有