In this project, we develop a face recognize platform based on MTCNN object-detection netcwork and FaceNet self-supervised network.

Overview

模式识别大作业——人脸检测与识别平台

本项目是一个简易的人脸检测识别平台,提供了人脸信息录入人脸识别的功能。前端采用 html+css+js,后端采用 pytorch,前后端交互采用 flask。

0 环境依赖

flask==2.0.1
werkzeug==2.0.1
torch==1.10.1
torchvision==0.11.1
pillow==8.2.0

1 文件结构

image-20211121230548707

MTCNN_FaceNet:人脸检测算法接口

simplified:人脸识别算法接口

static:静态资源文件夹(包含数据库)

templates:前端Html框架

app.py:前后端交互flask框架

2 人脸识别算法——facenet

  • 一次性导入数据库:使用 face_in.py,请将数据库中每个人组织成单个文件夹的形式,如图

    image-20211121230548707

    • 格式为 python face_in.py -i -d
    • 样例输入:python face_in.py -i In_data -d dataset.json
    • 样例输出:在当前工作目录下生成(default)名为"dataset.json"的文件,即为数据库
    • 若为直接调用函数的话,传入包含上面两种信息的字典即可,输出不变
      • 即类似 {'image_path':<>, 'dataset_path':<>} 的参数
  • 添加单个人像:使用 face_append.py,格式为 python face_append.py -i -n -d

    • 样例输入:python face_append.py -i In_data/acatsa/acatsa.1.jpg -n acatsa -d dataset.json
    • 样例输出:修改指定的 dataset.json,向其中添加新的人脸数据
    • 若为直接调用函数的话,传入包含上面三种信息的字典即可,输出不变
      • 即类似 {'image_path':<>, 'dataset_path':<>, 'name':<>} 的参数
  • 从数据库中判别人脸:使用 classify_func.py,格式为 python classify_func.py -i -d

    • 样例输入: python classify_func.py -i In_data/acatsa/acatsa.1.jpg -d dataset.json
    • 样例输出:'acatsa'
    • 若为直接调用函数的话,传入包含上面三种信息的字典即可,输出不变
      • 即类似 {'image_path':<>, 'dataset_path':<>} 的参数
  • 剪切人脸 和 输出特征向量的 接口,见 interface.py 中的 mtcnn_single() 和 embedding_single() 函数

    • mtcnn_single()
      • 输入:字典,{'image_path':<>, 'save_path':< default:None >}
      • 输出:返回剪切后的图片,同时在 save_path 保存剪切后的图片
    • embedding_single()
      • 输入:字典, {'image_path':<>}
      • 输出:返回编码向量
  • 一键将图片库中人脸进行 mtcnn 剪裁,见 mtcnn_trans() 函数

    • 输入:字典,{'image_path':<>}

    • 输出:无返回值,剪裁后替换原有图片位置

    • 注意:需要图片库的组织形式如本文开头 face_in.py 的要求那样见 mtcnn_trans() 函数

  • classify_test() 函数

    • 输入:字典,{'img_path':<>, 'dataset_path':<>, 'origin_data':<>}
      • img_path,输入图片的路径位置
      • dataset_path,之前保存的数据 json
      • origin_data,图片的保存位置,即各个人脸的总保存位置
      • image-20211225172640828
      • 就像上面这样的话,origin_data = 'In_data'
    • 输出:
      • 若找到匹配的人脸。返回路径,示例:'In_data/acatsa/acatsa_1.jpg'
      • 若未找到,返回字符串 'no matched people'

3 人脸检测算法——mtcnn

4 平台使用

本平台采用flask框架搭建,运行时,在flask_FC文件夹下打开终端,运行如下指令:

python -m flask run

在浏览器中输入网址 http://127.0.0.1:5000/

前端设置了两个接口,分别进行信息录入人脸截图识别。将新录入的人脸图片传入后端,可利用mtcnn算法进行人脸检测,在数据库中加入该用户的人脸信息;将视频流截图后的图片传入后端,可利用facenet算法进行人脸识别,在后台数据库中信息匹配,返回识别成功或错误信息。

image-20211225172640828

4.1 人脸信息录入

form表单将文件流传入后端 —— mtcnn接口检测人脸 —— DataBase中更新图片信息 —— dataset.json中更新编码信息 —— 检测人脸图片返回前端

aaa.html

">
<form action="/" id="uploadForm" method="post" enctype="multipart/form-data" >
	<button class="btn btn-danger" type="submit" >
      <h3>Enter Photo to experienceh3> 
    button>
	<input type="file" name="photo">
form>

app.py

@app.route('/', methods=['GET', 'POST'])
def upinfo():
    if request.method == 'POST':
        if request.files.get('photo'):
            # 创建文件夹,保存录入图片
            photo = request.files.get('photo')
            basepath = os.path.dirname(__file__)
            filename = secure_filename(photo.filename)
            uploadpath = os.path.join(basepath, 'static/DataBase', filename[:-4], filename)
            path = os.path.join(basepath, 'static/DataBase', filename[:-4])
            if not path:
                os.makedirs(path)

            Reshape = transforms.Resize((160, 160))
            trans = transforms.Compose([Reshape])
            img = trans(tojpg(Image.open(photo)))
            save_path = uploadpath
            newphoto = mtcnn_single(img, save_path=save_path)

            # 更新dataset.json
            args = {'image_path': uploadpath, "dataset_path": 'static/face_dataset.json', 'name': filename[:-4]}
            face_append(args)
            return render_template('aaa.html', output='DataBase/' + filename[:-4] + '/' + filename)

    return render_template('aaa.html')

4.2 视频流截图检测

前端视频流截图传入后端 —— facenet接口识别人脸 —— 后端数据库匹配 —— 返回数据库已录入图片(匹配成功)/返回失败信息

aaa.html

">
<video id="myVideo" autoplay>video>
			<script>

				let v = document.getElementById("myVideo");

				//create a canvas to grab an image for upload
				let imageCanvas = document.createElement('canvas');
				let imageCtx = imageCanvas.getContext("2d");

				//Add file blob to a form and post
				function postFile(file) {
					let formdata = new FormData();
					formdata.append("image", file);
					let xhr = new XMLHttpRequest();
					xhr.open('POST', 'http://localhost:5000/', true);
					xhr.onload = function () {
						if (this.status === 200){
							var path = JSON.parse(this.response)['path']
							console.log(this.response['path']);
							$('#img').attr('src',path);
						}
						else
							console.error(xhr);
					};
					xhr.send(formdata);
				}

				//Get the image from the canvas
				function sendImagefromCanvas() {

					//Make sure the canvas is set to the current video size
					imageCanvas.width = v.videoWidth;
					imageCanvas.height = v.videoHeight;

					imageCtx.drawImage(v, 0, 0, v.videoWidth, v.videoHeight);

					//Convert the canvas to blob and post the file
					imageCanvas.toBlob(postFile, 'image/jpeg');
				}

				//Take a picture on click
				v.onclick = function() {
					console.log('click');
					sendImagefromCanvas();
				};

				window.onload = function () {

					//Get camera video
					navigator.mediaDevices.getUserMedia({video: {width: 640, height: 360}, audio: false})
						.then(stream => {
							v.srcObject = stream;
						})
						.catch(err => {
							console.log('navigator.getUserMedia error: ', err)
						});

				};

			script>

app.py

@app.route('/', methods=['GET', 'POST'])
def upinfo():
    if request.method == 'POST':
        if request.files['image']:
            photo = request.files['image']
            basepath = os.path.dirname(__file__)
            filename = secure_filename(photo.filename)
            uploadpath = os.path.join(basepath, 'static/screenshot', filename)
            photo.save(uploadpath + '.jpg')

            Reshape = transforms.Resize((160, 160))
            trans = transforms.Compose([Reshape])
            img = trans(tojpg(Image.open(photo)))
            save_path = 'static/recognized_screenshot/' + "recognized_" + filename + '.jpg'
            newphoto = mtcnn_single(img, save_path=save_path)

            uploadpath = os.path.join(basepath, 'static/recognized_screenshot', 'recognized_'+filename)
            args = {'img_path': uploadpath + '.jpg', 'dataset_path': 'static/face_dataset.json',
                    'origin_data': 'static/DataBase'}
            out = classify_test(args)
            if out != "no matched people":
                print("数据库存储路径:" + out)
                print("识别成功!")
            else:
                print(out)
                print("数据库中不存在该人脸信息!")

            return {'path': out}

    return render_template('aaa.html')
Owner
Xuhua Huang
Xuhua Huang
HeartRate detector with ArduinoandPython - Use Arduino and Python create a heartrate detector.

Syllabus of Contents Syllabus of Contents Introduction Of Project Features Develop With Python code introduction Installation License Developer Contac

1 Jan 05, 2022
Contrastive Learning of Structured World Models

Contrastive Learning of Structured World Models This repository contains the official PyTorch implementation of: Contrastive Learning of Structured Wo

Thomas Kipf 371 Jan 06, 2023
Paddle implementation for "Highly Efficient Knowledge Graph Embedding Learning with Closed-Form Orthogonal Procrustes Analysis" (NAACL 2021)

ProcrustEs-KGE Paddle implementation for Highly Efficient Knowledge Graph Embedding Learning with Orthogonal Procrustes Analysis 🙈 A more detailed re

Lincedo Lab 4 Jun 09, 2021
Tool cek opsi checkpoint facebook!

tool apa ini? cek_opsi_facebook adalah sebuah tool yang mengecek opsi checkpoint akun facebook yang terkena checkpoint! tujuan dibuatnya tool ini? too

Muhammad Latif Harkat 2 Jul 17, 2022
[CIKM 2021] Enhancing Aspect-Based Sentiment Analysis with Supervised Contrastive Learning

Enhancing Aspect-Based Sentiment Analysis with Supervised Contrastive Learning. This repo contains the PyTorch code and implementation for the paper E

Akuchi 18 Dec 22, 2022
Official implementation of the Neurips 2021 paper Searching Parameterized AP Loss for Object Detection.

Parameterized AP Loss By Chenxin Tao, Zizhang Li, Xizhou Zhu, Gao Huang, Yong Liu, Jifeng Dai This is the official implementation of the Neurips 2021

46 Jul 06, 2022
My coursework for Machine Learning (2021 Spring) at National Taiwan University (NTU)

Machine Learning 2021 Machine Learning (NTU EE 5184, Spring 2021) Instructor: Hung-yi Lee Course Website : (https://speech.ee.ntu.edu.tw/~hylee/ml/202

100 Dec 26, 2022
Deep Learning for Human Part Discovery in Images - Chainer implementation

Deep Learning for Human Part Discovery in Images - Chainer implementation NOTE: This is not official implementation. Original paper is Deep Learning f

Shintaro Shiba 63 Sep 25, 2022
Social Distancing Detector

Computer vision has opened up a lot of opportunities to explore into AI domain that were earlier highly limited. Here is an application of haarcascade classifier and OpenCV to develop a social distan

Ashish Pandey 2 Jul 18, 2022
Keyhole Imaging: Non-Line-of-Sight Imaging and Tracking of Moving Objects Along a Single Optical Path

Keyhole Imaging Code & Dataset Code associated with the paper "Keyhole Imaging: Non-Line-of-Sight Imaging and Tracking of Moving Objects Along a Singl

Stanford Computational Imaging Lab 20 Feb 03, 2022
A Demo server serving Bert through ONNX with GPU written in Rust with <3

Demo BERT ONNX server written in rust This demo showcase the use of onnxruntime-rs on BERT with a GPU on CUDA 11 served by actix-web and tokenized wit

Xavier Tao 28 Jan 01, 2023
Genetic feature selection module for scikit-learn

sklearn-genetic Genetic feature selection module for scikit-learn Genetic algorithms mimic the process of natural selection to search for optimal valu

Manuel Calzolari 260 Dec 14, 2022
Code for CMaskTrack R-CNN (proposed in Occluded Video Instance Segmentation)

CMaskTrack R-CNN for OVIS This repo serves as the official code release of the CMaskTrack R-CNN model on the Occluded Video Instance Segmentation data

Q . J . Y 61 Nov 25, 2022
realsense d400 -> jpg + csv

Realsense-capture realsense d400 - jpg + csv Requirements RealSense sdk : Installation Python3 pyrealsense2 (RealSense SDK) Numpy OpenCV Tkinter Run

Ar-Ray 2 Mar 22, 2022
This reposityory contains the PyTorch implementation of our paper "Generative Dynamic Patch Attack".

Generative Dynamic Patch Attack This reposityory contains the PyTorch implementation of our paper "Generative Dynamic Patch Attack". Requirements PyTo

Xiang Li 8 Nov 17, 2022
A Jupyter notebook to play with NVIDIA's StyleGAN3 and OpenAI's CLIP for a text-based guided image generation.

A Jupyter notebook to play with NVIDIA's StyleGAN3 and OpenAI's CLIP for a text-based guided image generation.

Eugenio Herrera 175 Dec 29, 2022
Quantile Regression DQN a Minimal Working Example, Distributional Reinforcement Learning with Quantile Regression

Quantile Regression DQN Quantile Regression DQN a Minimal Working Example, Distributional Reinforcement Learning with Quantile Regression (https://arx

Arsenii Senya Ashukha 80 Sep 17, 2022
Implementation for paper MLP-Mixer: An all-MLP Architecture for Vision

MLP Mixer Implementation for paper MLP-Mixer: An all-MLP Architecture for Vision. Give us a star if you like this repo. Author: Github: bangoc123 Emai

Ngoc Nguyen Ba 86 Dec 10, 2022
Tutorials, assignments, and competitions for MIT Deep Learning related courses.

MIT Deep Learning This repository is a collection of tutorials for MIT Deep Learning courses. More added as courses progress. Tutorial: Deep Learning

Lex Fridman 9.5k Jan 07, 2023
This repository contains the code for the CVPR 2020 paper "Differentiable Volumetric Rendering: Learning Implicit 3D Representations without 3D Supervision"

Differentiable Volumetric Rendering Paper | Supplementary | Spotlight Video | Blog Entry | Presentation | Interactive Slides | Project Page This repos

697 Jan 06, 2023