opencv实现人脸检测
一、摄像头人脸检测
python
import cv2
# 加载预训练的人脸检测模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# 打开默认摄像头(通常是 0)
cap = cv2.VideoCapture(0)
# 检查摄像头是否成功打开
if not cap.isOpened():
print("无法打开摄像头")
exit()
while True:
# 逐帧读取摄像头视频
ret, frame = cap.read()
# 检查是否成功读取帧
if not ret:
print("无法读取帧")
break
# 将图像转换为灰度
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 使用人脸检测器检测人脸
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 在原始图像上绘制人脸方框
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 在窗口中显示视频帧
cv2.imshow("Face real-time detection", frame)
# 按下 "q" 键退出循环
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
二、捕获屏幕人脸检测
python
import cv2
import numpy as np
import pyautogui
# 创建窗体
cv2.namedWindow('Face Detection', cv2.WINDOW_NORMAL)
# 加载人脸检测器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
while True:
# 截取屏幕图像
screenshot = pyautogui.screenshot()
frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
# 在图像中检测人脸
faces = face_cascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5, minSize=(20, 20))
# 绘制方框
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'键退出循环
key = cv2.waitKey(1)
if key == ord('q') or key == 27: # 'q'键或ESC键
break
# 关闭窗口
cv2.destroyAllWindows()