一、课件
二、课后习题
三、答案
import cv2
import numpy as np
import sqlite3
import os
import face_recognition
# 1、从本地目录,打开一个人脸的图片,返回图片数据
def load_face_image_data(path):
image_data = cv2.imread(path)
return image_data
# 2、对人脸图片进行平移操作(向右移25像素,向上移15像素),返回新图片的数据
def move_face_image(image):
img = cv2.imread(image)
rows, cols = img.shape[:2]
M = np.float32([[1, 0, 25], [0, 1, -15]])
image_new_data = cv2.warpAffine(img, M, (cols, rows))
return image_new_data
# 3、创建一个face.db数据库(SQLite3),新建face表
# 包含id,name,image_path三个字段
def sqlite_exec_sql(conn, sql):
c = conn.cursor()
c.execute(sql)
conn.commit()
print("Total number of rows changes :", conn.total_changes)
def sqlite_query(conn, sql):
c = conn.cursor()
cursor = c.execute(sql)
return cursor
def creat_table():
conn = sqlite3.connect('face.db')
SQL_CREATE_TABLE = \
'''
CREATE TABLE FACE(
ID INTEGER PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
IMAGE_PATH CHAR(255) NOT NULL
);'''
# 新建表
sqlite_exec_sql(conn, SQL_CREATE_TABLE)
print("Table created successfully")
conn.close()
# 4、实现人脸记录的插入、删除、查询功能(三个函数)
def insert_face_data(name, img_path):
conn = sqlite3.connect('face.db')
SQL_INSET_DATA = \
"INSERT INTO FACE (NAME,IMAGE_PATH) VALUES ('" + name +"','"+ img_path + "')"
# 插入数据
print(SQL_INSET_DATA)
sqlite_exec_sql(conn, SQL_INSET_DATA)
conn.close()
def delete_face_data(id):
conn = sqlite3.connect('face.db')
SQL_DELETE_DATA = "DELETE from FACE where ID='"+str(id)+"';"
# 插入数据
sqlite_exec_sql(conn, SQL_DELETE_DATA)
conn.close()
def query_face_data_all():
conn = sqlite3.connect('face.db')
SQL_QUERY_DATA_ALL = "SELECT * from FACE;"
res = sqlite_query(conn, SQL_QUERY_DATA_ALL)
temp = []
for item in res:
temp.append({'id':item[0] ,"data":{"name":item[1],'img_path':item[2]}})
conn.close()
return temp
def query_face_data_by_name(name):
conn = sqlite3.connect('face.db')
SQL_QUERY_DATA_ALL = "SELECT * from FACE where name = '"+ name +"';"
res = sqlite_query(conn, SQL_QUERY_DATA_ALL)
temp = []
for item in res:
temp.append({'id': item[0], "data": {"name": item[1], 'img_path': item[2]}})
conn.close()
return temp
# 5、扫描LFW数据集,把前面100个人脸的名字和图片(后缀为0001)的信息插入face表的功能
def insert_face_lfw(path):
def traverse(path, pathsDic):
tempFilePath = ''
tempFileName = ''
tempPerName = ''
filePath = [os.path.join(path, f) for f in os.listdir(path)]
for itemPath in filePath:
if os.path.isdir(itemPath):
traverse(itemPath, pathsDic)
elif os.path.isfile(itemPath):
if itemPath.split("\\")[-1].split(".")[0][-4:] == '0001':
tempFileName = itemPath.split("\\")[-1]
tempFilePath = itemPath.split("\\")[0] + "/" +itemPath.split("\\")[1]+"/" +itemPath.split("\\")[2]
tempPerName = itemPath.split("\\")[1]
else:
print("未知,出现错误")
pathsDic.append({"path":tempFilePath, "imgName":tempFileName,"name":tempPerName})
return tempFilePath, tempFileName, tempPerName
result = []
traverse(path, result)
del result[-1]
return result
# 6、实现人脸识别算法(打桩,返回值:人名,为指定值)
def face_test(paths, unknown):
known_faces = []
for item in paths:
known_face = face_recognition.load_image_file(item['path'])
known_face_encoding = face_recognition.face_encodings(known_face)[0]
known_faces.append(known_face_encoding)
unknown_image = face_recognition.load_image_file(unknown)
try:
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
except IndexError:
print("I wasn't able to locate any faces in at least one of the images. Check the image files. Aborting...")
quit()
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)
index = results.index(True)
return paths[index]["name"]
# 7、实现人脸身份验证的功能,输入为人脸图片,调用人脸识别算法,从在根据人名从数据库中查询,看是否为合法用户
def face_database(name):
res = query_face_data_by_name(name)
# print(res)
if res != []:
print("合法用户")
else:
print("不合法用户")
if __name__ == "__main__":
# 需要识别的人脸信息
unknown = "faceimg/face.jpg" #Aaron_Eckhart_0001
# 加载图片
# res = load_face_image_data(unknown)
# print(res)
# 平移图片
# res = move_face_image(unknown)
# cv2.imshow("move",res)
# cv2.waitKey(0)
# 新建数据库
# creat_table()
# 删除数据通过id
# delete_face_data(1)
# 查询表中所有数据
# data = query_face_data_all()
# print(data)
# 所有照片所在文件夹
path = "faceimg/lfw"
# 遍历照片插入数据库
result = insert_face_lfw(path)
# for item in result:
# insert_face_data(item["name"],item["path"])
# 人脸识别,返回识别到的人名,
print("识别中……")
res = face_test(result, unknown)
print(res, "名字")
Comments | NOTHING