Python3 人脸识别

face_recognition 源码

人脸图片进行训练,识别摄像头人脸

  • 代码和人脸库在同一级

  • 训练库中以人名命名文件夹

  • 每个人可以多张图片,这里的名字无所谓

1. Ubuntu 20 安装人脸识别库

# 先:
sudo su rootapt-get install -y gitapt-get install -y cmake apt-get install -y python3-pip apt-get install libboost-all-devgit clone https://github.com/davisking/dlib.git
cd dlib
mkdir build
cd build
cmake .. -DDLIB_USE_CUDA=0 -DUSE_AVX_INSTRUCTIONS=1
cmake --build .
cd .. # 可能会报错
# 第一种:
python3 setup.py install --yes USE_AVX_INSTRUCTIONS --no DLIB_USE_CUDA
# 第二种
python3 setup.py install --set USE_AVX_INSTRUCTIONS=1 --set DLIB_USE_CUDA=1# 修改 ~/.pip/pip.conf (没有就创建一个)
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simplepip3 install face_recognitionpip install scikit-buildsudo apt-get install build-essential
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev# 上面有报错的执行
sudo add-apt-repository "deb http://security.ubuntu.com/ubuntu xenial-security main"
sudo apt update
sudo apt install libjasper1 libjasper-devpython3 -m pip install --upgrade pippip3 install opencv-pythonpip3 install scikit-learn# npm
sudo apt-get install npm
npm config set registry https://registry.npm.taobao.org

2. Windwos 安装face_recognition

参考文章:

  1. https://blog.csdn.net/weixin_41194171/article/details/108513392
  2. https://pypi.org/simple/dlib/
  3. https://www.icode9.com/content-1-1197216.html

人脸识别源码:


import cv2
import math
from sklearn import neighbors
import os
import os.path
import pickle
from numba import cuda
from PIL import Image, ImageDraw
import face_recognition
from face_recognition.face_recognition_cli import image_files_in_folder
import numpy as npALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'JPG'}# cuda.select_device(1)
# @cuda.jit
# def gpu():
#     pass# 训练(训练的目录, 训练库保存的位置, )
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):X = []y = []for class_dir in os.listdir(train_dir):if not os.path.isdir(os.path.join(train_dir, class_dir)):continueprint("开始训练用户:", class_dir, "...", end="")images = []for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):image = face_recognition.load_image_file(img_path)images.append(image)S = face_recognition.batch_face_locations(images, number_of_times_to_upsample=1, batch_size=len(images))for face_bounding_boxes in S:if len(face_bounding_boxes) != 1:if verbose:print("图片中人脸太多或者不存在人脸,不适合进行训练")else:X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])y.append(class_dir)print("训练结束")if n_neighbors is None:n_neighbors = int(round(math.sqrt(len(X))))if verbose:print("Chose n_neighbors automatically:", n_neighbors)knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')knn_clf.fit(X, y)if model_save_path is not None:with open(model_save_path, 'wb') as f:pickle.dump(knn_clf, f)return knn_clfdef predict(X_frame, knn_clf=None, model_path=None, distance_threshold=0.5):if knn_clf is None and model_path is None:raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")if knn_clf is None:with open(model_path, 'rb') as f:knn_clf = pickle.load(f)X_face_locations = face_recognition.face_locations(X_frame)if len(X_face_locations) != 1:return []faces_encodings = face_recognition.face_encodings(X_frame, known_face_locations=X_face_locations)closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]return [(pred, loc) if rec else ("", loc) for pred, loc, rec inzip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]"""X_face_locations = face_recognition.face_locations(X_frame)S = face_recognition.batch_face_locations([X_frame], number_of_times_to_upsample=1, batch_size=128)for face_bounding_boxes in S:print(face_bounding_boxes)if len(face_bounding_boxes) != 1:return []faces_encodings = face_recognition.face_encodings(X_frame, known_face_locations=face_bounding_boxes)# 匹配人脸closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]return [(pred, loc) if rec else ("", loc) for pred, loc, rec inzip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]return []"""def show_prediction_labels_on_image(frame, predictions):pil_image = Image.fromarray(frame)draw = ImageDraw.Draw(pil_image)for name, (top, right, bottom, left) in predictions:# enlarge the predictions for the full sized image.top *= 2right *= 2bottom *= 2left *= 2# Draw a box around the face using the Pillow moduleif name == "":rgbFace = (0, 0, 255)else:rgbFace = (118, 238, 0)draw.rectangle(((left, top), (right, bottom)), outline=rgbFace)name = name.encode("UTF-8")text_width, text_height = draw.textsize(name)draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=rgbFace, outline=rgbFace)draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))del drawopencvimage = np.array(pil_image)return opencvimagedef set_gpus(gpu_index):if type(gpu_index) == list:gpu_index = ','.join(str(_) for _ in gpu_index)if type(gpu_index) == int:gpu_index = str(gpu_index)os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"os.environ["CUDA_VISIBLE_DEVICES"] = gpu_indexif __name__ == "__main__":set_gpus(0)train_flag = 1 # 1表示训练、0表示不训练【训练一次之后建议改为0,提高效率,更图片或者添加人脸后需要重新训练】if train_flag:print("Training KNN classifier...")classifier = train("./train", model_save_path="trained_knn_model.clf", n_neighbors=2)print("Training complete!")print('Setting cameras up...')# 摄像头读取:https://blog.csdn.net/qq_44009311/article/details/121799698cap = cv2.VideoCapture(0)while 1 > 0:ret, frame = cap.read()if ret:img = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)predictions = predict(img, model_path="trained_knn_model.clf")frame = show_prediction_labels_on_image(frame, predictions)cv2.imshow('camera', frame)if ord('q') == cv2.waitKey(10):cap.release()cv2.destroyAllWindows()exit(0)

Python3 人脸识别 源码相关推荐

  1. Android园区部队人脸识别源码门禁项目讲解

    Android园区部队人脸识别源码门禁项目讲解 这边搞人脸识别相关项目有一段时间,今天抽时间讲述一个经典的人脸识别项目:部队人脸识别门禁系统. 大家都知道部队对人员管理安全要求是相当高的,很多保密的技 ...

  2. 人脸检测颜值软件_AI人脸颜值测颜版下载-百度ai测试颜值人脸识别源码下载v1.0 免费版-西西软件下载...

    百度ai测试颜值人脸识别源码这是由官方百度AI精心打造出来的,这款软件将人脸识别氛围V2和V3两个接口,而且用户使用可以参考相应的文档权限来选择接口类型,让广大用户学习到百度AI人脸识别测颜值相关知识 ...

  3. python 人脸识别源码

    Python是一种流行的编程语言,可以用于许多任务,包括人脸识别.以下是使用Python进行人脸识别的基本步骤: 安装必要的库:为了进行人脸识别,您需要安装OpenCV(用于图像处理),dlib(用于 ...

  4. python人脸识别源码_Python 抖音机器人,让你找到漂亮小姐姐

    本项目作者沉迷于抖音无法自拔,常常花好几个小时在抖音漂亮小姐姐身上. 本着高效.直接地找到漂亮小姐姐的核心思想,我用 Python + ADB 做了一个 Python 抖音机器人 Douyin-Bot ...

  5. facenet 人脸识别源码的使用方法(一)

    1. 开发环境 OS:        ubuntu16.04 tensorflow版本:1.12.0 python版本:    3.6.7 2. 下载源码到本地 facenet官方github: ht ...

  6. android 虹软 例子,虹软离线人脸识别源码Android版本

    [实例简介] 虹软离线识别Android 源码,下载即可运行,包含aar包,不需要越墙下载,可运行 [实例截图] [核心代码] ArcFaceDemo ├── ArcFaceDemo-master │ ...

  7. java实现人脸识别源码【含测试效果图】——ServiceImpl层(UserServiceImpl)

    /** * @Title: BaseServiceImpl.java * @Package org.service.impl * @Description: TODO该方法的主要作用: * @auth ...

  8. java实现人脸识别源码【含测试效果图】——Service层(IUserService)

    /** * @Title: BaseService.java * @Package org.service * @Description: TODO该方法的主要作用: * @author A18ccm ...

  9. java实现人脸识别源码【含测试效果图】——DaoImpl层(UserDaoImpl)

    /** * @Title: UserDaoImpl.java * @Package org.dao.impl * @Description: TODO该方法的主要作用: * @author A18cc ...

  10. java实现人脸识别源码【含测试效果图】——DaoImpl层(BaseDaoUtilImpl)

    /*** */ package org.dao.impl;import java.sql.ResultSet; import java.sql.SQLException; import java.ut ...

最新文章

  1. 解决pip安装时,下载速度慢的问题
  2. ASP.NET多线程的使用
  3. cocos2d-x游戏实例(23)-简易动作游戏(1)
  4. ps4修改服务器地区,ps4怎么修改服务器地址
  5. 构建iOS风格移动Web应用程序的8款开发框架
  6. 初学编程,你必须要打牢的几根“支柱”,地基越稳,成就越高!
  7. nginx在windows无法停止所有服务_这5项windows服务项目很常见,关于它们的设置建议请仔细参考...
  8. matlab 线性规划_从零开始的matlab学习笔记——(37)线性规划——后传
  9. 1038 一元三次方程求解
  10. java类转换异常,java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
  11. 力扣——查找常用字符
  12. 趋势科技防毒墙—控管中心
  13. 九宫格数独模型设计(随机生成题目)
  14. 泰迪杯数据挖掘挑战赛—机器学习(三)
  15. vue常用的事件修饰符
  16. 34. 进程管理之优先级,nice,renice,Priority
  17. 21 个人所得税计算
  18. Excel中如何显示复杂公式中局部的计算结果,例如嵌套函数,使用多个函数
  19. 2018年考研真题计算机专业,2018年计算机考研真题及参考答案.pdf
  20. 力扣(226.112)补9.8

热门文章

  1. 花了三个月终于把所有的 Python 库全部整理了!可以说很全面了
  2. Ubuntu安装gcc失败的那些事儿
  3. Echarts 下载使用教程
  4. 情人节程序员用HTML网页表白【制作浪漫气球520告白相册】 HTML5七夕情人节表白网页源码 HTML+CSS+JavaScript
  5. 【物联网毕设基础】实时时钟芯片 DS1302 介绍
  6. html5 video标签嵌入视频
  7. python爬取斗鱼礼物数据_Python---20行代码爬取斗鱼平台房间数据(上)
  8. mysql五日均线代码_通达信均线源码,5日通达信均线公式源码
  9. wav音频文件的提取和分析(matlab)
  10. 【数据技术】利用Python获取高德地图POI数据——以上海瑞幸门店为例