Python是一種非常強(qiáng)大的編程語(yǔ)言,擁有眾多應(yīng)用場(chǎng)景。其中一個(gè)方向是眼動(dòng)檢測(cè),利用Python可以實(shí)現(xiàn)非常高效的眼動(dòng)檢測(cè)程序。
import cv2 import dlib import numpy as np import math # 加載面部特征檢測(cè)模型 detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 加載視頻或者攝像頭 cap = cv2.VideoCapture(0) while True: # 讀取視頻幀 ret, frame = cap.read() if not ret: break # 根據(jù)面部特征點(diǎn)檢測(cè)眼睛位置 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray, 0) for face in faces: landmarks = predictor(gray, face) left_eye_points = [] right_eye_points = [] for n in range(36, 42): x = landmarks.part(n).x y = landmarks.part(n).y left_eye_points.append((x, y)) for n in range(42, 48): x = landmarks.part(n).x y = landmarks.part(n).y right_eye_points.append((x, y)) # 計(jì)算眼睛中心位置 left_eye_center = np.mean(left_eye_points, axis=0).astype(int) right_eye_center = np.mean(right_eye_points, axis=0).astype(int) # 計(jì)算眼睛長(zhǎng)寬和傾斜角度 left_eye_width = math.dist(left_eye_points[0], left_eye_points[3]) left_eye_height = math.dist(left_eye_points[1], left_eye_points[4]) right_eye_width = math.dist(right_eye_points[0], right_eye_points[3]) right_eye_height = math.dist(right_eye_points[1], right_eye_points[4]) left_eye_angle = math.atan((left_eye_points[1][1] - left_eye_points[4][1]) / (left_eye_points[1][0] - left_eye_points[4][0])) * 180 / math.pi right_eye_angle = math.atan((right_eye_points[1][1] - right_eye_points[4][1]) / (right_eye_points[1][0] - right_eye_points[4][0])) * 180 / math.pi # 繪制眼睛位置和形狀 cv2.circle(frame, tuple(left_eye_center), 2, (0, 255, 0), thickness=2) cv2.circle(frame, tuple(right_eye_center), 2, (0, 255, 0), thickness=2) cv2.line(frame, left_eye_points[0], left_eye_points[3], (0, 0, 255), thickness=2) cv2.line(frame, left_eye_points[1], left_eye_points[4], (0, 0, 255), thickness=2) cv2.line(frame, right_eye_points[0], right_eye_points[3], (0, 0, 255), thickness=2) cv2.line(frame, right_eye_points[1], right_eye_points[4], (0, 0, 255), thickness=2) # 顯示視頻幀 cv2.imshow("Frame", frame) # 按下q鍵退出 if cv2.waitKey(1) & 0xFF == ord("q"): break // 釋放視頻或者攝像頭 cap.release() cv2.destroyAllWindows()
上面的代碼通過(guò)調(diào)用面部特征檢測(cè)模型找到眼睛位置并計(jì)算了眼睛長(zhǎng)寬和傾斜角度,然后繪制在視頻幀上。利用這些信息,可以實(shí)現(xiàn)眼動(dòng)檢測(cè),比如眼動(dòng)追蹤等。