给我一份基于opencv的人脸识别代码
时间: 2023-12-06 19:04:00 浏览: 72
好的,以下是一个基于OpenCV的人脸识别代码示例:
```
import cv2
# 加载训练好的模型
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取视频帧
ret, frame = cap.read()
# 将帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 绘制检测到的人脸矩形框
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
# 显示视频帧
cv2.imshow('Face Detection', frame)
# 按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
```
在代码中,我们首先加载了一个预训练的人脸检测模型 `haarcascade_frontalface_default.xml`,并打开了摄像头,然后不断读取视频帧,将其转换为灰度图像,再用人脸检测模型检测人脸,并在检测到的人脸周围绘制矩形框,最后显示视频帧。按下q键即可退出程序。
阅读全文
相关推荐















