人脸识别:
实现代码
import sys
import cv2
import face_recognition
# 读取图像
face_img = face_recognition.load_image_file('img.jpg')
# 返回图像每个面的128维的人脸编码
face_encodings = face_recognition.face_encodings(face_img)
# 每个人脸的面部特征位置
face_locations = face_recognition.face_locations(face_img)
# 判断图像中的人数
n = len(face_encodings)
if n > 2:
sys.exit()
try:
face1 = face_encodings[0]
face2 = face_encodings[1]
except:
sys.exit()
# 比较脸部的编码是否匹配
result = face_recognition.compare_faces([face1], face2, tolerance=0.5)
if result == [True]:
name = "YES"
else:
name = "NO"
# 绘图
for i in range(len(face_encodings)):
face_encoding = face_encodings[i-1]
face_location = face_locations[i-1]
print(face_location)
top, right, bottom, left = face_location # 坐标
# 画框 图像 坐标 颜色 粗细
cv2.rectangle(face_img, (left, top), (right, bottom), (0, 255, 0), 2)
# 放上字体 图像 坐标 字体 大小 颜色 粗细
cv2.putText(face_img, name, (left-20, top-20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
# 颜色
face_img_rgb = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)
# 展示图像
cv2.imshow("Output", face_img_rgb)
# 保存图像
cv2.imwrite('result.jpg', face_img_rgb, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
# 关闭
cv2.waitKey(0)
人脸检测:
实现代码
功能:保存:s 退出:q
import os
import cv2
import face_recognition
# 定义摄像头
cap = cv2.VideoCapture(0)
width = 640 # 定义摄像头获取图像宽度
height = 480 # 定义摄像头获取图像长度
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) # 设置宽度
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) # 设置长度
num = 0
while True:
ret, frame = cap.read() # 读取每一帧
# 返回图像每个面的128维的人脸编码
face_encodings = face_recognition.face_encodings(frame)
# 每个人脸的面部特征位置
face_locations = face_recognition.face_locations(frame)
# 图像中的人数
n = len(face_encodings)
print("检测到%s人" % n)
# 绘图
for i in range(len(face_encodings)):
face_encoding = face_encodings[i - 1]
face_location = face_locations[i - 1]
top, right, bottom, left = face_location # 坐标
# 画框 图像 坐标 颜色 粗细
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
# 放上字体 图像 坐标 字体 大小 颜色 粗细
cv2.putText(frame, str(n), (left - 20, top - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
# 展示图像
cv2.imshow('Output', frame) # 显示每一帧
# 获取系统管理员用户名
admin = os.environ.get("USERNAME")
# 当检测到"s"时保存图片;检测到 'q' 时,退出,释放摄像头,并销毁所有窗口
if cv2.waitKey(1) & 0xFF == ord("s"):
num += 1
cv2.imwrite('C:\\Users\\' + admin + r'\Desktop\frame{}.jpg'.format(num), frame, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
elif cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()