请用python编写人脸识别程序
由于人脸识别程序需要使用一些第三方库和一些特殊硬件设备(如摄像头),所以无法在此提供完整的代码。但是,以下是一个简单的人脸识别程序的框架,供您参考:
- 导入必要的库和模块:
import cv2
import face_recognition
- 加载已知的人脸图像并进行编码:
known_image = face_recognition.load_image_file("known_face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
- 利用OpenCV打开摄像头:
video_capture = cv2.VideoCapture(0)
- 开始循环读取摄像头的帧:
while True:
_, frame = video_capture.read()
rgb_frame = frame[:, :, ::-1]
- 在帧中查找人脸:
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
- 遍历人脸,计算与已知人脸的距离:
for face_encoding in face_encodings:
distance = face_recognition.face_distance([known_encoding], face_encoding)
- 如果距离小于某个阈值,则认为是已知人脸:
if distance < 0.6:
# 在人脸周围画一个矩形框
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
# 在矩形框上方显示人名
cv2.putText(frame, "Known face", (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
- 显示帧:
cv2.imshow('Video', frame)
- 按下“q”键退出程序:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
- 释放摄像头并关闭窗口:
video_capture.release()
cv2.destroyAllWindows()
``
原文地址: https://www.cveoy.top/t/topic/harp 著作权归作者所有。请勿转载和采集!