import cv2
# 加载人脸识别器的模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# 打开摄像头
cap = cv2.VideoCapture(0)
# 初始化人脸框位置
prev_faces = []
# 定义绘制带圆角矩形边框的函数
def draw_rounded_rectangle(img, x, y, w, h, radius, color, thickness):
# 画上面的边框
cv2.line(img, (x + radius, y), (x + w - radius, y), color, thickness)
# 画下面的边框
cv2.line(img, (x + radius, y + h), (x + w - radius, y + h), color, thickness)
# 画左边的边框
cv2.line(img, (x, y + radius), (x, y + h - radius), color, thickness)
# 画右边的边框
cv2.line(img, (x + w, y + radius), (x + w, y + h - radius), color, thickness)
# 画左上角的圆弧
cv2.ellipse(img, (x + radius, y + radius), (radius, radius), 180, 0, 90, color, thickness)
# 画右上角的圆弧
cv2.ellipse(img, (x + w - radius, y + radius), (radius, radius), 270, 0, 90, color, thickness)
# 画右下角的圆弧
cv2.ellipse(img, (x + w - radius, y + h - radius), (radius, radius), 0, 0, 90, color, thickness)
# 画左下角的圆弧
cv2.ellipse(img, (x + radius, y + h - radius), (radius, radius), 90, 0, 90, color, thickness)
# 定义平滑处理人脸位置的函数
def smooth_faces(faces, prev_faces=None, alpha=0):
if prev_faces is None or len(prev_faces) == 0:
return faces
smoothed_faces = []
for (x, y, w, h) in faces:
found = False
for (prev_x, prev_y, prev_w, prev_h) in prev_faces:
if x - 30 <= prev_x <= x + 30 and y - 30 <= prev_y <= y + 30:
smoothed_x = int(alpha * x + (1 - alpha) * prev_x)
smoothed_y = int(alpha * y + (1 - alpha) * prev_y)
smoothed_w = int(alpha * w + (1 - alpha) * prev_w)
smoothed_h = int(alpha * h + (1 - alpha) * prev_h)
smoothed_faces.append((smoothed_x, smoothed_y, smoothed_w, smoothed_h))
found = True
break
if not found:
smoothed_faces.append((x, y, w, h))
return smoothed_faces
# 连续未检测到人脸的帧计数器
no_face_count = 0
max_no_face_count = 100 # 连续未检测到人脸的最大帧数
while True:
# 读取摄像头图像
ret, frame = cap.read()
if not ret:
# 如果无法读取摄像头图像,则退出循环
break
# 将图像转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 平滑处理人脸位置
faces = list(faces)
faces = smooth_faces(faces, prev_faces, alpha=0.3)
prev_faces = faces.copy()
# 在图像上绘制带圆角矩形边框
if len(faces) > 0:
for (x, y, w, h) in faces:
# 绘制带圆角矩形边框
radius = int(min(w, h) / 10)
draw_rounded_rectangle(frame, x, y, w, h, radius, (18, 153, 255), 2)
# 在人脸框上方显示文本信息
text = "Face"
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.8
thickness = 2
text_size, _ = cv2.getTextSize(text, font, font_scale, thickness)
text_x = x + int((w - text_size[0]) / 2)
text_y = y - 10
cv2.putText(frame, text, (text_x, text_y), font, font_scale, (18, 153, 255), thickness, cv2.LINE_AA)
# 显示图像
cv2.imshow('Face Detection', frame)
# 按下ESC键退出循环
if cv2.waitKey(1) == 27:
break
# 释放摄像头和关闭窗口
cap.release()
cv2.destroyAllWindows()
cv2人脸追踪
最新推荐文章于 2024-09-05 11:10:46 发布