Optimize the following code：import cv2
import mediapipe as mp
import numpy as np

mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5)
cap = cv2.VideoCapture(0)
prev_avg_x, prev_avg_y = 0, 0

while cap.isOpened():
    success, image = cap.read()

    # 水平翻转图像同时将颜色空间从 BGR 转换为 RGB
    image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)

    # 将image的writeable属性设置为False来提高性能
    image.flags.writeable = False
    
    # 使用face_mesh对象的process方法获取结果
    results = face_mesh.process(image)
    
    # 将image的writeable属性设置为True
    image.flags.writeable = True
    
    # 再次将颜色空间从RGB转换为BGR
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    # 获取image的宽度、高度和通道数
    img_h, img_w, img_c = image.shape
    face_3d = []
    face_2d = []
    
    # 姿态估计判定
    if results.multi_face_landmarks:
        for face_landmarks in results.multi_face_landmarks:
            for idx, lm in enumerate(face_landmarks.landmark):
                if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199:
                    if idx == 1:
                        nose_2d = (lm.x * img_w, lm.y * img_h)
                        nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 8000)

                    x, y = int(lm.x * img_w), int(lm.y * img_h)

                    # 获取 2D 坐标
                    face_2d.append([x, y])

                    # 获取 3D 坐标
                    face_3d.append([x, y, lm.z])       
            
            # 转为二维 NumPy 数组
            face_2d = np.array(face_2d, dtype=np.float64)
            # 转为三维 NumPy 数组
            face_3d = np.array(face_3d, dtype=np.float64)

            # The camera matrix
            focal_length = 1 * img_w

            cam_matrix = np.array([ [focal_length, 0, img_h / 2],
                                    [0, focal_length, img_w / 2],
                                    [0, 0, 1]])

            # 距离矩阵
            dist_matrix = np.zeros((4, 1), dtype=np.float64)

            # 处理 PnP
            success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix)

            # 矩阵旋转
            rmat, jac = cv2.Rodrigues(rot_vec)

            # 获取角度
            angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat)

            # 获取y轴旋转度数
            x = angles[0] * 360
            y = angles[1] * 360
            # print(y)

            # 头部倾斜位置判断
            if y < -10:
                text = "head Left"
            elif y > 10:
                text = "head Right"
            elif x < -5:
                text = "head Down"
            elif x > 10:
                text = "head Up"
            else:
                text = "Forward"

            # 头部姿态估计结果显示
            cv2.putText(image, "head pose estimation: {}".format(text), (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            
    else:
        cv2.putText(image, "leave", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        
    # 运动轨迹判定
    if results.multi_face_landmarks:
        for face_landmarks in results.multi_face_landmarks:
            # 计算人中、下巴、左眼、右眼四个点的加权平均坐标
            points = [33, 263, 1, 291]
            avg_x = 0
            avg_y = 0
            for point in points:
                landmark = face_landmarks.landmark[point]
                h, w, c = image.shape
                cx, cy = int(landmark.x * w), int(landmark.y * h)
                avg_x += cx
                avg_y += cy
            avg_x = int(avg_x / len(points))
            avg_y = int(avg_y / len(points))
            
            # 判断头部的左右和上下移动
            if abs(avg_x - prev_avg_x) >= 100 or abs(avg_y - prev_avg_y) >= 50:
                no_movement_count = 0
                if abs(avg_x - prev_avg_x) >= 100:
                    if avg_x - prev_avg_x < 50:
                        direction_x = "left"
                    else:
                        direction_x = "right"
                    prev_avg_x = avg_x
                    trace = direction_x

                if abs(avg_y - prev_avg_y) >= 50:
                    if avg_y - prev_avg_y > 0:
                        direction_y = "down"
                    else:
                        direction_y = "top"
                    prev_avg_y = avg_y
                    trace = direction_y

                # 头部运动结果显示
                print(trace)
                cv2.putText(image, "head move trace: {}".format(trace), (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            else:
                no_movement_count += 1
                if no_movement_count >= 10:
                    trace="static"
                    cv2.putText(image, "head move trace: {}".format(trace), (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            

    cv2.imshow('Head Information', image)

    if cv2.waitKey(5) & 0xFF == 27:
        break

cap.release()