
import mediapipe as mp import cv2 import numpy as np import time
def findDis(pts1,pts2): return ((pts2[0]-pts1[0])**2 + (pts2[1]-pts1[1])**2)**0.5
cap = cv2.VideoCapture(0) pTime = 0
id_list = [23, 159, 130, 243, 62, 292, 12, 15]
mpDraw = mp.solutions.drawing_utils mpFaceMesh = mp.solutions.face_mesh faceMesh = mpFaceMesh.FaceMesh(max_num_faces=2) drawSpec = mpDraw.DrawingSpec(thickness=1, circle_radius=2)
while True: success, img = cap.read() imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = faceMesh.process(imgRGB) if results.multi_face_landmarks: for faceLms in results.multi_face_landmarks: mpDraw.draw_landmarks(img, faceLms, mpFaceMesh.FACEMESH_CONTOURS, drawSpec,drawSpec) mp_data = [] for id,lm in enumerate(faceLms.landmark): ih, iw, ic = img.shape x,y = int(lm.x*iw), int(lm.y*ih) if id in id_list: #左眼[22, 23, 24, 26, 110, 157, 158, 159, 160, 161, 130, 243]: mp_data.append([x,y]) cv2.circle(img,(x,y),2,(255,0,0),-1) eye_length_1 = findDis(mp_data[0],mp_data[1]) eye_length_2 = findDis(mp_data[2],mp_data[3]) mouth_length_2 = findDis(mp_data[4],mp_data[5]) mouth_length_1 = findDis(mp_data[6],mp_data[7]) # print(eye_length_1,eye_length_2) if ((mouth_length_1/mouth_length_2)<(98/18)): cv2.putText(img,"mouth close",(400,50),cv2.FONT_HERSHEY_PLAIN, 2,(0,0,255),3) else: cv2.putText(img,"mouth open",(400,50),cv2.FONT_HERSHEY_PLAIN, 2,(0,0,255),3) if (eye_length_2/eye_length_1)>18: cv2.putText(img,"eye open",(400,100),cv2.FONT_HERSHEY_PLAIN, 2,(0,0,255),3) else: cv2.putText(img,"eye close",(400,100),cv2.FONT_HERSHEY_PLAIN, 2,(0,0,255),3)
cTime = time.time() fps = 1 / (cTime - pTime) pTime = cTime cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3) cv2.imshow("Image", img) if cv2.waitKey(1)&0xFF == ord("q"): cv2.imwrite("6.jpg",img) break cap.release() cv2.destroyAllWindows() 结果
