1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import mediapipe as mp import numpy as np
def get_face(image,mode=1): mp_drawing = mp.solutions.drawing_utils mp_face_mesh = mp.solutions.face_mesh drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1, color=(0, 255, 0)) with mp_face_mesh.FaceMesh( max_num_faces=2, min_detection_confidence=0.5, min_tracking_confidence=0.5) as face_mesh: image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB) image.flags.writeable = False results = face_mesh.process(image) image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) if mode==1: mask=image elif mode==2: mask=np.zeros(image.shape,dtype=np.uint8) if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: mp_drawing.draw_landmarks( image=mask, landmark_list=face_landmarks, connections=mp_face_mesh.FACEMESH_CONTOURS, landmark_drawing_spec=drawing_spec, connection_drawing_spec=drawing_spec) if mode==2: xs=[] ys=[] zs=[] for id,lm in enumerate(face_landmarks.landmark): ih, iw, ic = image.shape x,y = int(lm.x*iw), int(lm.y*ih) xs.append(x) ys.append(y) zs.append(lm.z) box=cv2.boundingRect(np.array([xs,ys]).T) face=mask[box[1]:box[1]+box[3],box[0]:box[0]+box[2]] return face elif mode==1: return mask if mode==1: return image elif mode==2: return np.zeros(image.shape,dtype=np.uint8)
|