OpenCV学习——图像脸部识别_笨小古的博客-CSDN博客
OpenCV学习——摄像头人脸识别_笨小古的博客-CSDN博客
填写个人数据,拍照建立个人脸形,使用身份证号当作个人的脸形文件。之后输入身份证号调出个人的图片文件当作比对依据,运行程序摄像头读取人脸信息,进行身份核验。
histogram()方法是取出2个脸形的颜色分布的直方图,对2个颜色做RMS(root-mean-square),
如果2个图一样则所得的RMS为0,RMS结果值越大代表图差异越大,一般若是所得的结果是在100左右算是临界值。
import cv2
from PIL import Image
from functools import reduce
import math, operator
ID = input("请输入身份证号:")
face = ID + ".jpg"
pictPath = r'data\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(pictPath) # 建立识别文件对象
cv2.namedWindow("Photo")
cap = cv2.VideoCapture(0) # 开启摄像头
while (cap.isOpened()): # 摄像头开启后执行
ret, img = cap.read() # 读取图像;ret是布尔值,摄像头拍摄成功便返回True,img是摄像头所拍的图像对象
cv2.imshow("Photo", img) # 显示图像在OpenCV窗口
if ret == True: # 如果图像读取成功
key = cv2.waitKey(200) # 每0.2秒检查一次
if key == ord("a") or key == ord("A"):
cv2.imwrite("photo.jpg", img) # 将图像写入photo.jpg
break
cap.release() # 关闭摄像头
faces = face_cascade.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=3, minSize=(20, 20))
# 标注右下角底色是黄色
cv2.rectangle(img, (img.shape[1] - 140, img.shape[0] - 20), (img.shape[1], img.shape[0]), (0, 255, 255), -1)
# 标注找到多少人脸
cv2.putText(img, "Finding " + str(len(faces)) + " face", (img.shape[1] - 135, img.shape[0] - 5),
cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 1)
# 将人脸框起来,由于有可能找到好几张脸所以用循环绘制出来
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # 蓝色框住人脸
image = Image.open("photo.jpg") # PIL模块开启
imageCrop = image.crop((x, y, x + w, y + h)) # 裁切
imageResize = imageCrop.resize((150, 150), Image.ANTIALIAS) # 高质量重制大小
imageResize.save("newface.jpg") # 存储文件
cv2.namedWindow("FaceRecognition", cv2.WINDOW_NORMAL) # 建立图像对象
cv2.imshow("FaceRecognition", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
h1 = Image.open(face).histogram()
h2 = Image.open("newface.jpg").histogram()
# histogram()方法是取出2个脸形的颜色分布的直方图,对2个颜色做RMS(root-mean-square),
# 如果2个图一样则所得的RMS为0,RMS结果值越大代表图差异越大,一般若是所得的结果是在100左右算是临界值。
RMS = math.sqrt(reduce(operator.add, list(map(lambda a, b:
(a - b) ** 2, h1, h2))) / len(h1))
if RMS <= 100:
print("身份核验成功")
else:
print("人脸比对失败")