Python是一種高效的編程語言,在人工智能和計算機視覺領域得到了廣泛的應用。睜眼閉眼檢測是計算機視覺領域的一項重要任務,Python可以通過OpenCV庫來實現這一功能。下面介紹Python實現睜眼閉眼檢測的方法。
import cv2 import dlib detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") def eyes_closed(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rects = detector(gray, 0) for rect in rects: shape = predictor(gray, rect) left_eye = shape.part(36).x, shape.part(37).y right_eye = shape.part(45).x, shape.part(46).y lx, ly, lw, lh = cv2.boundingRect(np.array([left_eye])) rx, ry, rw, rh = cv2.boundingRect(np.array([right_eye])) cv2.rectangle(image, (lx, ly), (lx + lw, ly + lh), (0, 255, 0), 2) cv2.rectangle(image, (rx, ry), (rx + rw, ry + rh), (0, 255, 0), 2) left_eye_roi = gray[ly: ly + lh, lx: lx + lw] right_eye_roi = gray[ry: ry + rh, rx: rx + rw] left_eye_hull = cv2.convexHull(cv2.findContours(left_eye_roi.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]) right_eye_hull = cv2.convexHull(cv2.findContours(right_eye_roi.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]) cv2.drawContours(image, [left_eye_hull + (lx, ly)], -1, (0, 255, 0), 1) cv2.drawContours(image, [right_eye_hull + (rx, ry)], -1, (0, 255, 0), 1) left_eye_ratio = eye_aspect_ratio(left_eye_hull) right_eye_ratio = eye_aspect_ratio(right_eye_hull) eye_ratio = (left_eye_ratio + right_eye_ratio) / 2.0 if eye_ratio< 0.25: return True else: return False def eye_aspect_ratio(eye): A = np.linalg.norm(eye[1] - eye[5]) B = np.linalg.norm(eye[2] - eye[4]) C = np.linalg.norm(eye[0] - eye[3]) ear = (A + B) / (2.0 * C) return ear cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if ret: if eyes_closed(frame): print("Eyes closed") else: print("Eyes open") if cv2.waitKey(1) == ord('q'): break cap.release() cv2.destroyAllWindows()
上面的代碼中,使用的是dlib庫來檢測面部區域和68個標志點的位置,并使用OpenCV來處理這些信息。使用凸包來找到眼睛區域,并計算眼睛的長寬比。如果長寬比小于0.25,則表示眼睛閉合,否則表示眼睛睜開。
通過Python實現睜眼閉眼檢測,可以應用于多個領域,如安防、護眼、游戲等。Python的開放性和易于編寫的特點,也讓眼動追蹤技術得到了更廣闊的應用前景。