Python3 人脸识别 源码

article/2025/7/17 7:54:35

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)

http://chatgpt.dhexx.cn/article/kL9vUEhI.shtml

相关文章

人脸识别4:Android InsightFace实现人脸识别Face Recognition(含源码)

人脸识别4&#xff1a;Android InsightFace实现人脸识别Face Recognition(含源码) 目录 人脸识别4&#xff1a;Android InsightFace实现人脸识别Face Recognition(含源码) 1. 前言 2. 项目说明 &#xff08;1&#xff09;开发版本 &#xff08;2&#xff09;依赖库说明(O…

python人脸识别系统源码

人脸检测、人脸识别、添加人脸、qt界面完整可运行源码。链接&#xff1a;https://pan.baidu.com/s/1QkzGGCqU7kUAAnInz-dgLg?pwdlaru 提取码&#xff1a;laru

Java+opencv+mysql实现人脸识别源码(人脸采集入库+人脸识别相似度)

Javaopencv实现人脸识别 写这篇博客&#xff0c;是因为以前经常使用pythonopencv实现人脸处理&#xff0c;后来发现java也可以实现&#xff0c;于是便学习了下&#xff0c;以下将代码和实现过程贴出。 目录 1、环境准备 使用到的技术&#xff1a;javaopencvmysql 我这里用的…

java人脸识别源码_用 Java 实现人脸识别功能(附源码)

整理了一些Java方面的架构、面试资料(微服务、集群、分布式、中间件等),有需要的小伙伴可以关注公众号【程序员内点事】,无套路自行领取 更多优选 引言 远程在家办公的第N天,快要闲出屁了,今天突然有个小学弟加我VX说要咨询我点技术问题(终于可以装X了)。 看了他的需求描述…

java实现人脸识别源码【含测试效果图】——前期准备工作及访问提示

注意&#xff1a; 看完之后如有不懂&#xff0c;请看&#xff1a;关于人脸和指纹识别共同交流方案&#xff0c;也可以关注微信公众号&#xff1a;雄雄的小课堂&#xff0c;回复&#xff1a;人脸识别群获取群号&#xff0c;群内有直接可以运行的源码可供下载&#xff0c;人脸识…

人脸识别2:InsightFace实现人脸识别Face Recognition(含源码下载)

人脸识别2&#xff1a;InsightFace实现人脸识别Face Recognition(含源码下载) 目录 人脸识别2&#xff1a;InsightFace实现人脸识别Face Recognition(含源码下载) 1. 前言 2. 项目安装 3. 人脸识别系统 &#xff08;1&#xff09;人脸检测和关键点检测 &#xff08;2&am…

Linux实现代码雨

黑客帝国大部分人都知道吧&#xff0c;屏幕前的绿条条看着挺炫酷的&#xff0c;平常接触Linux系统的&#xff0c;也得娱乐一下&#xff0c;看看这个效果怎么实现的吧&#xff01; 1&#xff0c;下载cmatrixcmatrix-1.2a.tar.gz 链接&#xff1a;工具包下载 提取码&#xff1a…

黑客代码雨

想必大家看电视的时候会有那种黑客使用的电脑都是一丢绿色的都是在哪一直动&#xff0c;接着黑客随便动一下就完成一个指令了&#xff0c;今天我就带大家实现这个效果。 看看效果图吧&#xff1a; 直接开始进入主题 先导入系统文件库 import pygame import random from pyga…

【黑客帝国-代码雨】超火(免费送)(17)

&#xff08;刚学的&#xff0c;还有好多地方做的不完善&#xff0c;后期继续跟进&#xff0c;直接复制代码&#xff0c;后缀名改为&#xff1a;.html &#xff0c;直接运行就可以看到效果啦&#xff01;&#xff09; 或者&#xff1a;使用HBuilder,创建HTML文件直接运行即可看…

HTML黑客帝国代码雨

1.用法 在电脑桌面新建一个文本文档&#xff0c;然后将代码复制到文本文档里&#xff0c;再将后缀改为".html"。 2.效果图 3.html代码 <!DOCTYPE html> <html> <head><title>黑客帝国代码雨</title> </head><body> <…

骇客代码雨

以下代码实现了代码雨的一些基本功能 #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <time.h>#define XMAX 150 #define YMAX 35 #define RAINLINES 50char *str "ki)udmnh*&(^%cobpwerxz$#<>?}{";st…

C++实现代码雨

各位博友们&#xff0c;大家好&#xff0c;今天给大家打一个代码雨 接下来是代码 #include <stdio.h> #include <time.h> #include <Windows.h> #include <graphics.h>#define WIDTH 960 #define HEIGHT 640 #define STR_SIZE 20 #define STR_NUM 128…

网页实现黑客帝国代码雨

网页实现黑客帝国代码雨 <!DOCTYPE html> <html> <head> <meta charset"UTF-8"/><title>黑客帝国代码雨 </title><style type"text/css"> /*basic reset*/ *{margin:0;padding:0;} body{background:black;} ca…

Python实现代码雨效果

Python实现代码雨效果 main.py代码&#xff1a; """功能&#xff1a;代码雨效果作者&#xff1a;指尖魔法师QQ&#xff1a;14555110 """ import pygame import randomdef main():# 初始化pygamepygame.init()# 默认不全屏fullscreen False# …

酷炫黑客代码雨

大家看到这要说切scratch谁不会呀&#xff01; 我要说&#xff1a;退退退&#xff01; 话不多.................好了再见 代 码 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>黑客帝国代码雨</title><st…

经典代码雨----C语言实现

代码架构&#xff1a; 1、初始化窗口&#xff08;窗口大小信息&#xff09; 2、描绘雨点信息&#xff08;颜色&#xff0c;数字&#xff09; 3、初始化雨&#xff08;雨点位置变化&#xff09; 4、下雨操作&#xff08;坐标更新&#xff09; 5、更新窗口&#xff08;场景描…

学习编程的方法及入门

&#xff08;入门&#xff09;学习编程可以通过以下步骤进行&#xff1a; 1. 确定学习目标&#xff1a;首先&#xff0c;明确你希望学习编程的具体目标和用途。这有助于你选择学习的编程语言和方向&#xff0c;例如网页开发、移动应用开发或数据分析等。 2. 选择编程语言&…

怎么学习编程?小白如何入门?

前言 编程的范围实在很大&#xff0c;学什么就是小白的首要问题。如果是学编程希望能够将重复工作自动化这类朋友&#xff0c;直接学Python即可。下文会说怎么学习&#xff0c;本文主要针对的是想要通过编程高薪转行的这类人。 一、编程方向 编程可就业的技术岗位非常多&…

易语言编程入门教程学习

易语言是一款中文开发软件&#xff0c;因为是国人开发的&#xff0c;对于国人使用也是比较友好的。其最大的特点&#xff0c;就是易&#xff0c;容易的易&#xff0c;新手入门很容易。 易语言简介 易语言是一门以中文作为程序代码编程语言。以“易”著称。创始人为吴涛。早期版…

入门编程指南:如何从零开始学习编程?

一、自学编程需要注意什么&#xff1f; 自学编程需要注意以下几点&#xff1a; 选择适合自己的编程语言&#xff0c;在学习初期建议选择易入手的编程语言。需要不断地练习&#xff0c;并建立自己的编程项目&#xff0c;以此提高编程技巧和应用能力。追求知识的全面性&#xf…