demo.py

import cv2
from detection.mtcnn import MTCNN # 检测图片中的人脸
def test_image(imgpath):
mtcnn = MTCNN('./mtcnn.pb')
img = cv2.imread(imgpath) bbox, landmarks, scores = mtcnn.detect_faces(img) print('total box:', len(bbox))
for box, pts in zip(bbox, landmarks):
box = box.astype('int32')
img = cv2.rectangle(img, (box[1], box[0]), (box[3], box[2]), (255, 0, 0), 3) pts = pts.astype('int32')
for i in range(5):
img = cv2.circle(img, (pts[i + 5], pts[i]), 1, (0, 255, 0), 2)
cv2.imshow('image', img)
cv2.waitKey() # 检测视频中的人脸
def test_camera():
mtcnn = MTCNN('./mtcnn.pb')
cap = cv2.VideoCapture('rtsp://admin:hik12345@192.168.3.160/Streaming/Channels/1')
while True:
ret, img = cap.read()
if not ret:
break
bbox, landmarks, scores = mtcnn.detect_faces(img)
print('total box:', len(bbox), scores)
for box, pts in zip(bbox, landmarks):
box = box.astype('int32')
img = cv2.rectangle(img, (box[1], box[0]), (box[3], box[2]), (255, 0, 0), 3)
pts = pts.astype('int32')
for i in range(5):
img = cv2.circle(img, (pts[i], pts[i + 5]), 1, (0, 255, 0), 2)
cv2.imshow('img', img)
cv2.waitKey(1) if __name__ == '__main__':
# test_image()
test_camera()

mtcnn.py

import tensorflow as tf
from detection.align_trans import get_reference_facial_points, warp_and_crop_face
import numpy as np
import cv2
import detection.face_preprocess as face_preprocess class MTCNN: def __init__(self, model_path, min_size=40, factor=0.709, thresholds=[0.7, 0.8, 0.8]):
self.min_size = min_size
self.factor = factor
self.thresholds = thresholds graph = tf.Graph()
with graph.as_default():
with open(model_path, 'rb') as f:
graph_def = tf.GraphDef.FromString(f.read())
tf.import_graph_def(graph_def, name='')
self.graph = graph
config = tf.ConfigProto(
allow_soft_placement=True,
intra_op_parallelism_threads=4,
inter_op_parallelism_threads=4)
config.gpu_options.allow_growth = True
self.sess = tf.Session(graph=graph, config=config)
self.refrence = get_reference_facial_points(default_square=True) # 人脸检测
def detect_faces(self, img):
feeds = {
self.graph.get_operation_by_name('input').outputs[0]: img,
self.graph.get_operation_by_name('min_size').outputs[0]: self.min_size,
self.graph.get_operation_by_name('thresholds').outputs[0]: self.thresholds,
self.graph.get_operation_by_name('factor').outputs[0]: self.factor
}
fetches = [self.graph.get_operation_by_name('prob').outputs[0],
self.graph.get_operation_by_name('landmarks').outputs[0],
self.graph.get_operation_by_name('box').outputs[0]]
prob, landmarks, box = self.sess.run(fetches, feeds)
return box, landmarks, prob # 对齐获取单个人脸
def align_face(self, img):
ret = self.detect_faces(img)
if ret is None:
return None
bbox, landmarks, prob = ret
if bbox.shape[0] == 0:
return None landmarks_copy = landmarks.copy()
landmarks[:, 0:5] = landmarks_copy[:, 5:10]
landmarks[:, 5:10] = landmarks_copy[:, 0:5]
# print(landmarks[0, :]) bbox = bbox[0, 0:4]
bbox = bbox.astype(int) bbox = bbox[::-1]
bbox_copy = bbox.copy()
bbox[0:2] = bbox_copy[2:4]
bbox[2:4] = bbox_copy[0:2]
# print(bbox) points = landmarks[0, :].reshape((2, 5)).T
# print(points) '''
face_img = cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 0, 255), 6)
for i in range(5):
pts = points[i, :]
face_img = cv2.circle(face_img, (pts[0], pts[1]), 2, (0, 255, 0), 2)
cv2.imshow('img', face_img)
if cv2.waitKey(100000) & 0xFF == ord('q'):
cv2.destroyAllWindows()
''' warped_face = face_preprocess.preprocess(img, bbox, points, image_size='112,112')
'''
cv2.imshow('face', warped_face) if cv2.waitKey(100000) & 0xFF == ord('q'):
cv2.destroyAllWindows()
'''
# warped_face = cv2.cvtColor(warped_face, cv2.COLOR_BGR2RGB)
# aligned = np.transpose(warped_face, (2, 0, 1))
# return aligned
return warped_face # 对齐获取多个人脸
def align_multi_faces(self, img, limit=None):
boxes, landmarks, _ = self.detect_faces(img)
if limit:
boxes = boxes[:limit]
landmarks = landmarks[:limit] landmarks_copy = landmarks.copy()
landmarks[:, 0:5] = landmarks_copy[:, 5:10]
landmarks[:, 5:10] = landmarks_copy[:, 0:5] # print('landmarks', landmark)
faces = []
for idx in range(len(landmarks)):
'''
landmark = landmarks[idx, :]
facial5points = [[landmark[j], landmark[j + 5]] for j in range(5)]
warped_face = warp_and_crop_face(np.array(img), facial5points, self.refrence, crop_size=(112, 112))
faces.append(warped_face)
'''
bbox = boxes[idx, 0:4]
bbox = bbox.astype(int) bbox = bbox[::-1]
bbox_copy = bbox.copy()
bbox[0:2] = bbox_copy[2:4]
bbox[2:4] = bbox_copy[0:2]
# print(bbox) points = landmarks[idx, :].reshape((2, 5)).T
# print(points)
warped_face = face_preprocess.preprocess(img, bbox, points, image_size='112,112') cv2.imshow('faces', warped_face)
# warped_face = cv2.cvtColor(warped_face, cv2.COLOR_BGR2RGB)
# aligned = np.transpose(warped_face, (2, 0, 1))
faces.append(warped_face) # print('faces',faces)
# print('boxes',boxes)
return faces, boxes, landmarks

MTCNN 人脸检测的更多相关文章

  1. 项目实战 - 原理讲解<-> Keras框架搭建Mtcnn人脸检测平台

    Mtcnn它是2016年中国科学院深圳研究院提出的用于人脸检测任务的多任务神经网络模型,该模型主要采用了三个级联的网络,采用候选框加分类器的思想,进行快速高效的人脸检测.这三个级联的网络分别是快速生成 ...

  2. MTCNN人脸检测 附完整C++代码

    人脸检测 识别一直是图像算法领域一个主流话题. 前年 SeetaFace 开源了人脸识别引擎,一度成为热门话题. 虽然后来SeetaFace 又放出来 2.0版本,但是,我说但是... 没有训练代码, ...

  3. MTCNN人脸检测识别笔记

    论文:Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks 论文链接:https:// ...

  4. MTCNN算法与代码理解—人脸检测和人脸对齐联合学习

    目录 写在前面 算法Pipeline详解 如何训练 损失函数 训练数据准备 多任务学习与在线困难样本挖掘 预测过程 参考 博客:blog.shinelee.me | 博客园 | CSDN 写在前面 主 ...

  5. 第三十七节、人脸检测MTCNN和人脸识别Facenet(附源码)

    在说到人脸检测我们首先会想到利用Harr特征提取和Adaboost分类器进行人脸检测(有兴趣的可以去一看这篇博客第九节.人脸检测之Haar分类器),其检测效果也是不错的,但是目前人脸检测的应用场景逐渐 ...

  6. 人脸检测——MTCNN

    人脸检测——MTCNN .

  7. 基于MTCNN多任务级联卷积神经网络进行的人脸识别 世纪晟人脸检测

    神经网络和深度学习目前为处理图像识别的许多问题提供了最佳解决方案,而基于MTCNN(多任务级联卷积神经网络)的人脸检测算法也解决了传统算法对环境要求高.人脸要求高.检测耗时高的弊端. 基于MTCNN多 ...

  8. 使用TensorRT对人脸检测网络MTCNN进行加速

    前言 最近在做人脸比对的工作,需要用到人脸关键点检测的算法,比较成熟和通用的一种算法是 MTCNN,可以同时进行人脸框选和关键点检测,对于每张脸输出 5 个关键点,可以用来进行人脸对齐. 问题 刚开始 ...

  9. caffe_实战之两个简单的例子(物体分类和人脸检测)

    一.物体分类: 这里使用的是caffe官网中自带的例子,我这里主要是对代码的解释~ 首先导入一些必要的库: import caffe import numpy as np import matplot ...

随机推荐

  1. moment使用,把某个时间时间戳转换成日期

    1.某个时间时间戳转换成日期 moment(时间戳 ).format("YYYYMMDD")   2.获取某个日期当月的最后一天 moment(“2019-04-05”).endO ...

  2. facebook第三方登陆实践

    未完,待续... 1.注册 到Facebook官网注册开发者账号,创建应用(开发者平台 https://developers.facebook.com),如果尚未注册账号的请注册账号并进行登录) 注册 ...

  3. JDK5的新特性

    本篇博客内容 一.自动装箱和自动拆箱 二.泛型 三.增强for循环 四.静态导入 五.可变参数 六.枚举 一.自动装箱和自动拆箱  <=返回目录 java有8种基本数据类型  byte.shor ...

  4. 记一下今天上下班学的Thread

    1 Thread 默认为前台线程,即主程序退出后,线程还可以继续(曾经就掉入这个坑中,使用两线程分别进行UDP收发,结果发线程结束了退出方法,收线程还在继续) 2 Thread 没有可以暂停,可以重新 ...

  5. JavaScript toFixed()、toExponential、toPrecision方法

    JavaScript toFixed() 定义和用法 toFixed() 方法可把 Number 四舍五入为指定小数位数的数字. 语法 NumberObject.toFixed(num) 参数 描述 ...

  6. Spring Boot 异步方法的调用

    Spring Boot 异步方法的调用 参考资料: 1.Spring Boot中使用@Async实现异步调用 使用方法 两个步骤: 1.开启配置 @EnableAsync,这一步特别容易忘记,导致测试 ...

  7. [转]Vue项目全局配置微信分享思路详解

    这篇文章给大家介绍了vue项目全局配置微信分享思路讲解,使用vue作为框架,使用vux作为ui组件库,具体内容详情大家跟随脚本之家小编一起学习吧 这个项目为移动端项目,主要用于接入公众号服务.项目采用 ...

  8. UEFI手札

    基于Intel TianoCore衍生的EDK-II诞生的UEFI,用来取代Legacy BIOS. INF文件 Module Information File,模块描述文件.Module可以是可执行 ...

  9. xargs -i参数详解

    学习所需,文章转载过来! xargs与find经常结合来进行文件操作,平时删日志的时候只是习惯的去删除,比如 # find . -type f -name "*.log" | xa ...

  10. (转)用C#实现实现简单的 Ping 的功能,用于测试网络是否已经连通

    本文转载自:http://blog.csdn.net/xiamin/archive/2009/02/14/3889696.aspx 用C#实现实现简单的 Ping 的功能,用于测试网络是否已经联通 1 ...