本站消息

站长简介/公众号


站长简介:高级软件工程师,曾在阿里云,每日优鲜从事全栈开发工作,利用周末时间开发出本站,欢迎关注我的微信公众号:程序员总部,程序员的家,探索程序员的人生之路!分享IT最新技术,关注行业最新动向,让你永不落伍。了解同行们的工资,生活工作中的酸甜苦辣,谋求程序员的最终出路!

  价值13000svip视频教程,python大神匠心打造,零基础python开发工程师视频教程全套,基础+进阶+项目实战,包含课件和源码

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2020-12(13)

2021-01(34)

Untitled5

发布于2021-11-21 18:20     阅读(517)     评论(0)     点赞(16)     收藏(5)



1.人脸信息处理

从文件夹中读取人脸,并将特征值提取出并保存到文件。

import cv2
import os
import dlib
from skimage import io
import csv
import numpy as np

# 要读取人脸图像文件的路径
path_images_from_camera = "D:/myworks/persons"

# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()

# Dlib 人脸预测器
predictor = dlib.shape_predictor("D:/myworks/shape_predictor_68_face_landmarks.dat")

# Dlib 人脸识别模型
face_rec = dlib.face_recognition_model_v1("D:/myworks/dlib_face_recognition_resnet_model_v1.dat")


# 返回单张图像的 128D 特征
def return_128d_features(path_img):
    img_rd = io.imread(path_img)
    img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)
    faces = detector(img_gray, 1)


    # 因为有可能截下来的人脸再去检测,检测不出来人脸了
    # 所以要确保是 检测到人脸的人脸图像 拿去算特征
    if len(faces) != 0:
        shape = predictor(img_gray, faces[0])
        face_descriptor = face_rec.compute_face_descriptor(img_gray, shape)
    else:
        face_descriptor = 0
        print("no face")

    return face_descriptor


# 将文件夹中照片特征提取出来, 写入 CSV
def return_features_mean_personX(path_faces_personX):
    features_list_personX = []
    photos_list = os.listdir(path_faces_personX)
    if photos_list:
        for i in range(len(photos_list)):
            # 调用return_128d_features()得到128d特征
            features_128d = return_128d_features(path_faces_personX + "/" + photos_list[i])
            #  print(features_128d)
            # 遇到没有检测出人脸的图片跳过
            if features_128d == 0:
                i += 1
            else:
                features_list_personX.append(features_128d)
    else:
        print("文件夹内图像文件为空 / Warning: No images in " + path_faces_personX + '/', '\n')

    # 计算 128D 特征的均值
    # N x 128D -> 1 x 128D
    if features_list_personX:
        features_mean_personX = np.array(features_list_personX).mean(axis=0)
    else:
        features_mean_personX = '0'

    return features_mean_personX


# 读取某人所有的人脸图像的数据
people = os.listdir(path_images_from_camera)
people.sort()

with open("D:myworks/features2_all.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    for person in people:
        print("##### " + person + " #####")
        # Get the mean/average features of face/personX, it will be a list with a length of 128D
        features_mean_personX = return_features_mean_personX(path_images_from_camera)
        writer.writerow(features_mean_personX)
    print("所有录入人脸数据存入 / Save all the features of faces registered into: features_all2.csv")

##### person0.jpg #####
##### person1.jpg #####
##### person10.jpg #####
##### person11.jpg #####
##### person12.jpg #####
##### person13.jpg #####
##### person14.jpg #####
##### person15.jpg #####
##### person16.jpg #####
##### person17.jpg #####
##### person18.jpg #####
##### person19.jpg #####
##### person2.jpg #####
##### person3.jpg #####
##### person4.jpg #####
##### person5.jpg #####
##### person6.jpg #####
##### person7.jpg #####
##### person8.jpg #####
##### person9.jpg #####
所有录入人脸数据存入 / Save all the features of faces registered into: features_all2.csv

人脸识别

欧氏距离计算

计算两张人脸图片间的欧氏距离

def return_euclidean_distance(feature_1, feature_2):
    feature_1 = np.array(feature_1)
    feature_2 = np.array(feature_2)
    dist = np.sqrt(np.sum(np.square(feature_1 - feature_2)))
    return dist

人脸识别实现

# 摄像头实时人脸识别
import dlib
import time
import numpy as np   # 数据处理的库 numpy
import pandas as pd  # 数据处理的库 Pandas
import cv2
import os
from skimage import io
import csv

# 要读取人脸图像文件的路径
path_images_from_camera = "D:/myworks/persons"

# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()

# Dlib 人脸预测器
predictor = dlib.shape_predictor("D:/myworks/shape_predictor_68_face_landmarks.dat")

# Dlib 人脸识别模型
face_rec = dlib.face_recognition_model_v1("D:/myworks/dlib_face_recognition_resnet_model_v1.dat")

# 计算两个128D向量间的欧式距离
def return_euclidean_distance(feature_1, feature_2):
    feature_1 = np.array(feature_1)
    feature_2 = np.array(feature_2)
    dist = np.sqrt(np.sum(np.square(feature_1 - feature_2)))
    return dist


# 处理存放所有人脸特征的 csv
path_features_known_csv = "D:myworks/features2_all.csv"
csv_rd = pd.read_csv(path_features_known_csv, header=None)


# 用来存放所有录入人脸特征的数组
features_known_arr = []

# 读取已知人脸数据
for i in range(csv_rd.shape[0]):
    features_someone_arr = []
    for j in range(0, len(csv_rd.iloc[i, :])):
        features_someone_arr.append(csv_rd.iloc[i, :][j])
    features_known_arr.append(features_someone_arr)
print("Faces in Database:", len(features_known_arr))



# 创建 cv2 摄像头对象
cap = cv2.VideoCapture(0)

# cap.set(propId, value)
# 设置视频参数,propId 设置的视频参数,value 设置的参数值
cap.set(3, 480)

# cap.isOpened() 返回 true/false 检查初始化是否成功
# when the camera is open
while cap.isOpened():

    flag, img_rd = cap.read()
    kk = cv2.waitKey(1)

    # 取灰度
    img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)

    # 人脸数 faces
    faces = detector(img_gray, 0)

    # 待会要写的字体 font to write later
    font = cv2.FONT_HERSHEY_COMPLEX

    # 存储当前摄像头中捕获到的所有人脸的坐标/名字
    # the list to save the positions and names of current faces captured
    pos_namelist = []
    name_namelist = []

    # 按下 q 键退出
    # press 'q' to exit
    if kk == ord('q'):
        break
    else:
        # 检测到人脸 when face detected
        if len(faces) != 0:  
            # 获取当前捕获到的图像的所有人脸的特征,存储到 features_cap_arr
            # get the features captured and save into features_cap_arr
            features_cap_arr = []
            for i in range(len(faces)):
                shape = predictor(img_rd, faces[i])
                features_cap_arr.append(face_rec.compute_face_descriptor(img_rd, shape))

            # 遍历捕获到的图像中所有的人脸
            # traversal all the faces in the database
            for k in range(len(faces)):
                print("##### camera person", k+1, "#####")
                # 让人名跟随在矩形框的下方
                # 确定人名的位置坐标
                # 先默认所有人不认识,是 unknown
                name_namelist.append("unknown")

                # 每个捕获人脸的名字坐标 the positions of faces captured
                pos_namelist.append(tuple([faces[k].left(), int(faces[k].bottom() + (faces[k].bottom() - faces[k].top())/4)]))

                # 对于某张人脸,遍历所有存储的人脸特征
                e_distance_list = []
                for i in range(len(features_known_arr)):
                    # 如果 person_X 数据不为空
                    if str(features_known_arr[i][0]) != '0.0':
                        e_distance_tmp = return_euclidean_distance(features_cap_arr[k], features_known_arr[i])
                        e_distance_list.append(e_distance_tmp)
                    else:
                        e_distance_list.append(999999999)
                # 找出最接近的一个人脸数据是第几个
                similar_person_num = e_distance_list.index(min(e_distance_list))
                print("Minimum e distance with person", int(similar_person_num)+1)
                
                # 计算人脸识别特征与数据集特征的欧氏距离
                # 距离小于0.4则标出为可识别人物
                if min(e_distance_list) < 0.4:
                    # 这里可以修改摄像头中标出的人名
                    # 1、遍历文件夹目录
                    folder_name = 'D:/myworks/persons'
                    # 最接近的人脸
                    sum=similar_person_num+1
                    key_id=1 # 从第一个人脸数据文件夹进行对比
                    # 获取文件夹中的文件名
                    file_names = os.listdir(folder_name)
                    for name in file_names:
                        if sum ==key_id:
                            name_namelist[k] = name[0:]
                        key_id += 1
                    # -----------筛选出人脸并保存到visitor文件夹------------
                    for i, d in enumerate(faces):
                        x1 = d.top() if d.top() > 0 else 0
                        y1 = d.bottom() if d.bottom() > 0 else 0
                        x2 = d.left() if d.left() > 0 else 0
                        y2 = d.right() if d.right() > 0 else 0
                        face = img_rd[x1:y1,x2:y2]
                        size = 64
                        face = cv2.resize(face, (size,size))
                        # 要存储visitor人脸图像文件的路径
                        path_visitors_save_dir = "D:/myworks/visitor/known"
                        # 存储格式:YYYY-MM-DD-HH-MM-SSxx.jpg
                        now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
                        save_name = str(now_time)+str(name_namelist[k])+'.jpg'
                        # print(save_name)
                        # 本次图片保存的完整url
                        save_path = path_visitors_save_dir+'/'+ save_name    
                        # 遍历visitor文件夹所有文件名
                        visitor_names = os.listdir(path_visitors_save_dir)
                        visitor_name=''
                        for name in visitor_names:
                            # 名字切片到分钟数:2019-06-26-11-33-00LQH.jpg
                            visitor_name=(name[0:16]+'-00'+name[19:])
                        visitor_save=(save_name[0:16]+'-00'+save_name[19:])
                        # 一分钟之内重复的人名不保存
                        if visitor_save!=visitor_name:
                            cv2.imwrite(save_path, face)
                            print('新存储:'+path_visitors_save_dir+'/'+str(now_time)+str(name_namelist[k])+'.jpg')
                        else:
                            print('重复,未保存!')
                            
                else:
                    print("Unknown person")
                    # -----保存图片-------
                    # -----------筛选出人脸并保存到visitor文件夹------------
                    for i, d in enumerate(faces):
                        x1 = d.top() if d.top() > 0 else 0
                        y1 = d.bottom() if d.bottom() > 0 else 0
                        x2 = d.left() if d.left() > 0 else 0
                        y2 = d.right() if d.right() > 0 else 0
                        face = img_rd[x1:y1,x2:y2]
                        size = 64
                        face = cv2.resize(face, (size,size))
                        # 要存储visitor-》unknown人脸图像文件的路径
                        path_visitors_save_dir = "D:/myworks/visitor/unknown"
                        # 存储格式:2019-06-24-14-33-40unknown.jpg
                        now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
                        # print(save_name)
                        # 本次图片保存的完整url
                        save_path = path_visitors_save_dir+'/'+ str(now_time)+'unknown.jpg'
                        cv2.imwrite(save_path, face)
                        print('新存储:'+path_visitors_save_dir+'/'+str(now_time)+'unknown.jpg')
                
                # 矩形框
                # draw rectangle
                for kk, d in enumerate(faces):
                    # 绘制矩形框
                    cv2.rectangle(img_rd, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
                print('\n')

            # 在人脸框下面写人脸名字
            # write names under rectangle
            for i in range(len(faces)):
                cv2.putText(img_rd, name_namelist[i], pos_namelist[i], font, 0.8, (0, 255, 255), 1, cv2.LINE_AA)

    print("Faces in camera now:", name_namelist, "\n")

    #cv2.putText(img_rd, "Press 'q': Quit", (20, 450), font, 0.8, (84, 255, 159), 1, cv2.LINE_AA)
    cv2.putText(img_rd, "Face Recognition", (20, 40), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
    cv2.putText(img_rd, "Visitors: " + str(len(faces)), (20, 100), font, 1, (0, 0, 255), 1, cv2.LINE_AA)

    # 窗口显示 show with opencv
    cv2.imshow("camera", img_rd)

# 释放摄像头 release camera
cap.release()

# 删除建立的窗口 delete all the windows
cv2.destroyAllWindows()

Faces in Database: 20
##### camera person 1 #####
Minimum e distance with person 1
新存储:D:/myworks/visitor/known/2021-11-19-20-53-20person0.jpg.jpg


Faces in camera now: ['person0.jpg'] 

##### camera person 1 #####
Minimum e distance with person 1
重复,未保存!


Faces in camera now: ['person0.jpg'] 

##### camera person 1 #####
Minimum e distance with person 1
重复,未保存!


Faces in camera now: ['person0.jpg'] 

##### camera person 1 #####
Minimum e distance with person 1
重复,未保存!


Faces in camera now: ['person0.jpg'] 

##### camera person 1 #####
Minimum e distance with person 1
重复,未保存!


Faces in camera now: ['person0.jpg'] 

##### camera person 1 #####
Minimum e distance with person 1
重复,未保存!


Faces in camera now: ['person0.jpg'] 

##### camera person 1 #####
Minimum e distance with person 1
重复,未保存!


Faces in camera now: ['person0.jpg'] 

请添加图片描述

可以识别并检测到人脸

参考资料

https://blog.csdn.net/qq_43279579/article/details/117637044







所属网站分类: 技术文章 > 博客

作者:我想吃火锅

链接:https://www.pythonheidong.com/blog/article/1082717/b9ed8a1bcb83e3540e69/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)