使用 OpenCV 和 dlib 库实现眼睛和嘴巴识别的 Python 代码
时间: 2024-02-16 21:04:02 浏览: 145
以下是使用OpenCV和dlib库实现眼睛和嘴巴识别的Python代码示例:
```python
import cv2
import dlib
# 加载人脸检测器和关键点检测器
face_detector = dlib.get_frontal_face_detector()
keypoint_detector = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 将图像转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_detector(gray)
# 检测人脸关键点
for face in faces:
keypoints = keypoint_detector(gray, face)
# 绘制人脸关键点
for i in range(68):
x, y = keypoints.part(i).x, keypoints.part(i).y
cv2.circle(frame, (x, y), 1, (0, 255, 0), -1)
# 根据人脸关键点定位眼睛和嘴巴
left_eye = [(keypoints.part(i).x, keypoints.part(i).y) for i in range(36, 42)]
right_eye = [(keypoints.part(i).x, keypoints.part(i).y) for i in range(42, 48)]
mouth = [(keypoints.part(i).x, keypoints.part(i).y) for i in range(48, 68)]
# 计算眼睛和嘴巴的状态
left_eye_open = is_eye_open(left_eye)
right_eye_open = is_eye_open(right_eye)
mouth_open = is_mouth_open(mouth)
# 根据状态绘制不同的框和文本
if left_eye_open and right_eye_open:
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 2)
cv2.putText(frame, "Eyes open", (face.left(), face.top() - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
else:
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0, 0, 255), 2)
cv2.putText(frame, "Eyes closed", (face.left(), face.top() - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
if mouth_open:
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 2)
cv2.putText(frame, "Mouth open", (face.left(), face.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
else:
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0, 0, 255), 2)
cv2.putText(frame, "Mouth closed", (face.left(), face.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.imshow("frame", frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
上述代码中使用了`shape_predictor_68_face_landmarks.dat`文件,用于人脸关键点检测。在绘制人脸关键点时,使用了`cv2.circle`函数绘制圆形,并根据关键点的位置和状态绘制不同的框和文本。具体的眼睛和嘴巴状态计算函数`is_eye_open`和`is_mouth_open`可以自行实现。
阅读全文