import cv2 import numpy as np import mediapipe as mp import mss import time import…
- User
import cv2 import numpy as np import mediapipe as mp import mss import time import logging import threading from dataclasses import dataclass from typing import Tuple, Any from queue import Queue
设置日志配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
初始化 MediaPipe Pose
mp_drawing = mp.solutions.drawing_utils mp_pose = mp.solutions.pose
定义颜色
class Color: WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (0, 0, 255) BLUE = (255, 0, 0)
@dataclass class MonitorConfig: """屏幕监控配置""" top: int = 0 left: int = 0 width: int = 2880 # 修改为您的屏幕宽度 height: int = 1800 # 修改为您的屏幕高度
@dataclass class PoseEstimatorConfig: """姿态估计器配置""" min_detection_confidence: float = 0.3 # 降低置信度阈值 min_tracking_confidence: float = 0.3 # 降低置信度阈值
class PoseEstimator: def init(self, config: PoseEstimatorConfig): self.pose = mp_pose.Pose( min_detection_confidence=config.min_detection_confidence, min_tracking_confidence=config.min_tracking_confidence )
def process(self, image: np.ndarray) -> Any: """处理图像并进行姿态检测。""" image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_rgb.flags.writeable = False results = self.pose.process(image_rgb) return results def draw(self, image: np.ndarray, results: Any): """在图像上绘制13个骨骼点的骨架、人物矩形框以及头部方框。""" if results.pose_landmarks: # 获取关节点坐标 landmarks = results.pose_landmarks.landmark image_height, image_width, _ = image.shape # 定义骨骼点索引 nose_idx = mp_pose.PoseLandmark.NOSE.value left_shoulder_idx = mp_pose.PoseLandmark.LEFT_SHOULDER.value right_shoulder_idx = mp_pose.PoseLandmark.RIGHT_SHOULDER.value left_elbow_idx = mp_pose.PoseLandmark.LEFT_ELBOW.value right_elbow_idx = mp_pose.PoseLandmark.RIGHT_ELBOW.value left_wrist_idx = mp_pose.PoseLandmark.LEFT_WRIST.value right_wrist_idx = mp_pose.PoseLandmark.RIGHT_WRIST.value left_hip_idx = mp_pose.PoseLandmark.LEFT_HIP.value right_hip_idx = mp_pose.PoseLandmark.RIGHT_HIP.value left_knee_idx = mp_pose.PoseLandmark.LEFT_KNEE.value right_knee_idx = mp_pose.PoseLandmark.RIGHT_KNEE.value left_ankle_idx = mp_pose.PoseLandmark.LEFT_ANKLE.value right_ankle_idx = mp_pose.PoseLandmark.RIGHT_ANKLE.value # 骨骼点字典 keypoints = {} # 检查并获取每个关键点的坐标 def get_coord(idx): landmark = landmarks[idx] if landmark.visibility > 0 and 0 <= landmark.x <= 1 and 0 <= landmark.y <=1: x = int(landmark.x * image_width) y = int(landmark.y * image_height) return (x, y) else: return None # 获取关键点坐标 keypoints['head'] = get_coord(nose_idx) keypoints['left_shoulder'] = get_coord(left_shoulder_idx) keypoints['right_shoulder'] = get_coord(right_shoulder_idx) keypoints['left_elbow'] = get_coord(left_elbow_idx) keypoints['right_elbow'] = get_coord(right_elbow_idx) keypoints['left_wrist'] = get_coord(left_wrist_idx) keypoints['right_wrist'] = get_coord(right_wrist_idx) keypoints['left_hip'] = get_coord(left_hip_idx) keypoints['right_hip'] = get_coord(right_hip_idx) keypoints['left_knee'] = get_coord(left_knee_idx) keypoints['right_knee'] = get_coord(right_knee_idx) keypoints['left_ankle'] = get_coord(left_ankle_idx) keypoints['right_ankle'] = get_coord(right_ankle_idx) # 计算颈部骨骼点(左右肩膀的中点) if keypoints['left_shoulder'] and keypoints['right_shoulder']: neck_x = int((keypoints['left_shoulder'][0] + keypoints['right_shoulder'][0]) / 2) neck_y = int((keypoints['left_shoulder'][1] + keypoints['right_shoulder'][1]) / 2) keypoints['neck'] = (neck_x, neck_y) else: keypoints['neck'] = None # 计算盆骨骨骼点(左右臀部的中点) if keypoints['left_hip'] and keypoints['right_hip']: pelvis_x = int((keypoints['left_hip'][0] + keypoints['right_hip'][0]) / 2) pelvis_y = int((keypoints['left_hip'][1] + keypoints['right_hip'][1]) / 2) keypoints['pelvis'] = (pelvis_x, pelvis_y) else: keypoints['pelvis'] = None # 定义连接关系 connections = [ ('head', 'neck'), ('neck', 'left_shoulder'), ('neck', 'right_shoulder'), ('left_shoulder', 'left_elbow'), ('right_shoulder', 'right_elbow'), ('left_elbow', 'left_wrist'), ('right_elbow', 'right_wrist'), ('neck', 'pelvis'), ('pelvis', 'left_knee'), ('pelvis', 'right_knee'), ('left_knee', 'left_ankle'), ('right_knee', 'right_ankle'), ] # 绘制骨骼 for connection in connections: partA, partB = connection if keypoints.get(partA) and keypoints.get(partB): cv2.line(image, keypoints[partA], keypoints[partB], Color.GREEN, 2) # 绘制头部方框 if keypoints['head']: head_size = 20 # 方框大小,可根据需要调整 top_left = (keypoints['head'][0] - head_size, keypoints['head'][1] - head_size) bottom_right = (keypoints['head'][0] + head_size, keypoints['head'][1] + head_size) cv2.rectangle(image, top_left, bottom_right, Color.BLUE, 2) # 绘制包围人物的矩形框(基于所有可见关键点) x_values = [pt[0] for pt in keypoints.values() if pt] y_values = [pt[1] for pt in keypoints.values() if pt] if x_values and y_values: min_x = min(x_values) - 20 max_x = max(x_values) + 20 min_y = min(y_values) - 20 max_y = max(y_values) + 20 # 确保坐标在图像范围内 min_x = max(0, min_x) min_y = max(0, min_y) max_x = min(image_width, max_x) max_y = min(image_height, max_y) cv2.rectangle(image, (min_x, min_y), (max_x, max_y), Color.RED, 2) def __del__(self): if hasattr(self, 'pose'): self.pose.close()def capture_screen(monitor: MonitorConfig, frame_queue: Queue, stop_event: threading.Event): """捕获屏幕内容并将帧放入队列。""" with mss.mss() as sct: monitor_dict = { "top": monitor.top, "left": monitor.left, "width": monitor.width, "height": monitor.height } while not stop_event.is_set(): screen = sct.grab(monitor_dict) frame = np.array(screen) frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
# 将帧放入队列 if not frame_queue.full(): frame_queue.put(frame) else: # 丢弃旧的帧,避免队列阻塞 frame_queue.get() frame_queue.put(frame) # 控制帧率 time.sleep(0.01)def calculate_fps(prev_time: float) -> Tuple[float, float]: """计算并返回 FPS。""" current_time = time.time() fps = 1.0 / (current_time - prev_time) if current_time - prev_time > 0 else 0.0 return fps, current_time
def display_fps(frame: np.ndarray, fps: float): """在图像上显示 FPS。""" cv2.putText( frame, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, Color.WHITE, 2 )
def main(): # 初始化配置 monitor_config = MonitorConfig() estimator_config = PoseEstimatorConfig() frame_queue = Queue(maxsize=5) # 限制队列大小,防止内存占用过大 stop_event = threading.Event()
# 初始化窗口 window_name = "Pose Estimation" cv2.namedWindow(window_name, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) cv2.setWindowProperty(window_name, cv2.WND_PROP_TOPMOST, 1) # 设置窗口为最顶层 # 初始化姿态估计器 pose_estimator = PoseEstimator(estimator_config) # 启动屏幕捕获线程 capture_thread = threading.Thread(target=capture_screen, args=(monitor_config, frame_queue, stop_event)) capture_thread.start() prev_time = time.time() try: while True: if not frame_queue.empty(): frame = frame_queue.get() # 处理图像 results = pose_estimator.process(frame) # 绘制结果 pose_estimator.draw(frame, results) # 计算并显示 FPS fps, prev_time = calculate_fps(prev_time) display_fps(frame, fps) # 显示图像,调整窗口大小以适应大分辨率 cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, 1280, 720) # 您可以根据需要调整窗口大小 cv2.imshow(window_name, frame) # 检查是否按下了 'q' 键 if cv2.waitKey(1) & 0xFF == ord('q'): logging.info("用户退出程序。") break except KeyboardInterrupt: logging.info("程序被手动中断。") except Exception as e: logging.exception(f"发生错误:{e}") finally: stop_event.set() capture_thread.join() cv2.destroyAllWindows()if name == "main": main()详细仔细分析代码
- Assistant
以下是对您提供的Python代码的详细分析。该代码的主要功能是使用MediaPipe实现姿态估计,从屏幕捕获实时图像,进行姿态检测,并在图像上绘制检测结果,包括骨骼、关键点和包围人物的矩形框。
1. 导入必要的库和模块
import cv2 import numpy as np import mediapipe as mp import mss import time import logging import threading from dataclasses import dataclass from typing import Tuple, Any from queue import Queue- cv2:OpenCV库,用于图像处理和计算机视觉任务。
- numpy:用于处理多维数组和矩阵运算。
- mediapipe:谷歌开源的跨平台机器学习框架,用于媒体处理,这里用于姿态估计。
- mss:用于截取屏幕快照。
- time:提供时间相关的函数。
- logging:用于记录日志信息,便于调试和监控程序运行。
- threading:提供多线程支持,使程序可以并发执行。
- dataclasses:提供数据类支持,使定义类更简洁。
- typing:提供类型提示支持。
- Queue:线程安全的队列,用于在线程之间传递数据。
2. 设置日志配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')- logging.basicConfig:配置日志的基本设置。
- level=logging.INFO:日志级别为INFO,意味着INFO级别及以上的日志都会被记录。
- format:指定日志的输出格式,包括时间、日志级别和消息内容。
3. 初始化MediaPipe Pose模块
mp_drawing = mp.solutions.drawing_utils mp_pose = mp.solutions.pose- mp_drawing:MediaPipe提供的绘图工具,用于在图像上绘制关键点和连接线。
- mp_pose:MediaPipe的姿态估计模块。
4. 定义颜色类
class Color: WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (0, 0, 255) BLUE = (255, 0, 0)- Color类定义了一些常用的颜色,用于在绘图时指定颜色。
- WHITE:白色。
- GREEN:绿色。
- RED:红色。
- BLUE:蓝色。
5. 定义屏幕监控配置的数据类
@dataclass class MonitorConfig: """屏幕监控配置""" top: int = 0 left: int = 0 width: int = 2880 # 修改为您的屏幕宽度 height: int = 1800 # 修改为您的屏幕高度- MonitorConfig数据类用于存储屏幕截取区域的配置。
- top:截取区域的上边缘。
- left:截取区域的左边缘。
- width:截取区域的宽度,需要根据实际屏幕尺寸修改。
- height:截取区域的高度,需要根据实际屏幕尺寸修改。
6. 定义姿态估计器的配置数据类
@dataclass class PoseEstimatorConfig: """姿态估计器配置""" min_detection_confidence: float = 0.3 # 降低置信度阈值 min_tracking_confidence: float = 0.3 # 降低置信度阈值- PoseEstimatorConfig数据类用于存储姿态估计器的配置参数。
- min_detection_confidence:最小检测置信度阈值。检测到的关键点置信度低于该值会被忽略。
- min_tracking_confidence:最小跟踪置信度阈值。跟踪到的关键点置信度低于该值会被忽略。
7. 定义姿态估计器类
class PoseEstimator: def __init__(self, config: PoseEstimatorConfig): self.pose = mp_pose.Pose( min_detection_confidence=config.min_detection_confidence, min_tracking_confidence=config.min_tracking_confidence )- PoseEstimator类封装了姿态估计的相关操作。
- **init**方法:
- self.pose:创建了一个MediaPipe Pose对象,使用传入的配置参数。
7.1. 处理图像并进行姿态检测
def process(self, image: np.ndarray) -> Any: """处理图像并进行姿态检测。""" image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_rgb.flags.writeable = False results = self.pose.process(image_rgb) return results- process方法:
- 将图像从BGR转换为RGB,因为MediaPipe使用RGB格式的图像。
- 将图像设置为不可写,以提高处理效率。
- 调用**self.pose.process(image_rgb)**进行姿态检测,返回结果。
7.2. 在图像上绘制姿态估计结果
def draw(self, image: np.ndarray, results: Any): """在图像上绘制13个骨骼点的骨架、人物矩形框以及头部方框。""" if results.pose_landmarks: # 获取关节点坐标 landmarks = results.pose_landmarks.landmark ...- draw方法:
- 检查results.pose_landmarks是否存在,即是否检测到了姿态。
- landmarks:获取所有检测到的关键点。
7.2.1. 获取图像尺寸
image_height, image_width, _ = image.shape- 获取图像的高度和宽度,用于将归一化的关键点坐标转换为像素坐标。
7.2.2. 定义骨骼点索引
# 定义骨骼点索引 nose_idx = mp_pose.PoseLandmark.NOSE.value left_shoulder_idx = mp_pose.PoseLandmark.LEFT_SHOULDER.value # ...(省略其他关键点索引)- 定义需要使用的关键点的索引,使用MediaPipe提供的PoseLandmark枚举。
7.2.3. 初始化关键点字典
# 骨骼点字典 keypoints = {}- keypoints字典用于存储关键点的像素坐标。
7.2.4. 定义获取关键点坐标的函数
def get_coord(idx): landmark = landmarks[idx] if landmark.visibility > 0 and 0 <= landmark.x <= 1 and 0 <= landmark.y <=1: x = int(landmark.x * image_width) y = int(landmark.y * image_height) return (x, y) else: return None- get_coord函数:
- 检查关键点的可见度(visibility)是否大于0,以及坐标是否在合理范围内(0到1之间)。
- 将归一化的坐标转换为像素坐标。
- 如果条件不满足,返回None。
7.2.5. 获取各个关键点的坐标
# 获取关键点坐标 keypoints['head'] = get_coord(nose_idx) keypoints['left_shoulder'] = get_coord(left_shoulder_idx) # ...(省略其他关键点获取)- 使用get_coord函数获取需要的关键点坐标,并存储在keypoints字典中。
7.2.6. 计算颈部和盆骨的中点
# 计算颈部骨骼点(左右肩膀的中点) if keypoints['left_shoulder'] and keypoints['right_shoulder']: neck_x = int((keypoints['left_shoulder'][0] + keypoints['right_shoulder'][0]) / 2) neck_y = int((keypoints['left_shoulder'][1] + keypoints['right_shoulder'][1]) / 2) keypoints['neck'] = (neck_x, neck_y) else: keypoints['neck'] = None # 计算盆骨骨骼点(左右臀部的中点) if keypoints['left_hip'] and keypoints['right_hip']: pelvis_x = int((keypoints['left_hip'][0] + keypoints['right_hip'][0]) / 2) pelvis_y = int((keypoints['left_hip'][1] + keypoints['right_hip'][1]) / 2) keypoints['pelvis'] = (pelvis_x, pelvis_y) else: keypoints['pelvis'] = None- **颈部点(neck)**是左右肩膀的中点。
- **盆骨点(pelvis)**是左右臀部的中点。
- 如果组成中点的关键点都存在,则计算中点坐标;否则,设为None。
7.2.7. 定义骨骼连接关系
# 定义连接关系 connections = [ ('head', 'neck'), ('neck', 'left_shoulder'), # ...(省略其他连接关系) ]- connections列表定义了关键点之间的连接,用于绘制骨架。
7.2.8. 绘制骨架
# 绘制骨骼 for connection in connections: partA, partB = connection if keypoints.get(partA) and keypoints.get(partB): cv2.line(image, keypoints[partA], keypoints[partB], Color.GREEN, 2)- 遍历connections列表,对于每一对关键点,如果都存在,使用cv2.line绘制连接线。
- 绘制的颜色为绿色,线宽为2。
7.2.9. 绘制头部方框
# 绘制头部方框 if keypoints['head']: head_size = 20 # 方框大小,可根据需要调整 top_left = (keypoints['head'][0] - head_size, keypoints['head'][1] - head_size) bottom_right = (keypoints['head'][0] + head_size, keypoints['head'][1] + head_size) cv2.rectangle(image, top_left, bottom_right, Color.BLUE, 2)- 如果头部关键点存在,绘制一个以头部为中心的方框。
- 方框的大小由head_size控制。
- 使用cv2.rectangle绘制矩形,颜色为蓝色,线宽为2。
7.2.10. 绘制包围人物的矩形框
# 绘制包围人物的矩形框(基于所有可见关键点) x_values = [pt[0] for pt in keypoints.values() if pt] y_values = [pt[1] for pt in keypoints.values() if pt] if x_values and y_values: min_x = min(x_values) - 20 max_x = max(x_values) + 20 min_y = min(y_values) - 20 max_y = max(y_values) + 20 # 确保坐标在图像范围内 min_x = max(0, min_x) min_y = max(0, min_y) max_x = min(image_width, max_x) max_y = min(image_height, max_y) cv2.rectangle(image, (min_x, min_y), (max_x, max_y), Color.RED, 2)- 收集所有可见关键点的x和y坐标。
- 计算x和y的最小值和最大值,并适当增加边距(这里增加了20像素)。
- 确保坐标在图像范围内,避免越界。
- 使用cv2.rectangle绘制包围人物的矩形框,颜色为红色,线宽为2。
7.3. 释放资源
def __del__(self): if hasattr(self, 'pose'): self.pose.close()- **del**方法在对象被删除时调用。
- 关闭MediaPipe的Pose对象,释放资源。
8. 捕获屏幕内容并将帧放入队列
def capture_screen(monitor: MonitorConfig, frame_queue: Queue, stop_event: threading.Event): ...- capture_screen函数用于截取屏幕内容,并将截取到的帧放入队列。
- 参数:
- monitor:屏幕监控配置。
- frame_queue:帧队列,用于传递图像数据。
- stop_event:线程事件,用于控制线程的停止。
8.1. 截取屏幕并放入队列
with mss.mss() as sct: monitor_dict = { "top": monitor.top, "left": monitor.left, "width": monitor.width, "height": monitor.height } while not stop_event.is_set(): screen = sct.grab(monitor_dict) frame = np.array(screen) frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR) # 将帧放入队列 if not frame_queue.full(): frame_queue.put(frame) else: # 丢弃旧的帧,避免队列阻塞 frame_queue.get() frame_queue.put(frame) # 控制帧率 time.sleep(0.01)- 使用mss.mss()创建截屏对象sct。
- monitor_dict:根据配置创建截屏区域的字典。
- 在循环中:
- screen = sct.grab(monitor_dict):截取屏幕图像。
- 将图像转换为numpy数组,并从BGRA转换为BGR格式。
- 将帧放入队列。如果队列已满,先取出一个旧的帧,然后再放入新的帧,避免队列阻塞。
- 通过**time.sleep(0.01)**控制截屏的频率。
9. 计算并返回FPS
def calculate_fps(prev_time: float) -> Tuple[float, float]: """计算并返回 FPS。""" current_time = time.time() fps = 1.0 / (current_time - prev_time) if current_time - prev_time > 0 else 0.0 return fps, current_time- calculate_fps函数用于计算每秒帧数(FPS)。
- 参数:
- prev_time:上一帧的时间戳。
- 返回值:
- fps:计算得到的FPS值。
- current_time:当前的时间戳,供下一次计算使用。
10. 在图像上显示FPS
def display_fps(frame: np.ndarray, fps: float): """在图像上显示 FPS。""" cv2.putText( frame, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, Color.WHITE, 2 )- display_fps函数用于在图像上绘制FPS信息。
- 参数:
- frame:要绘制的图像帧。
- fps:要显示的FPS值。
- 使用cv2.putText在图像上写入文本信息。
11. 主函数
def main(): # 初始化配置 monitor_config = MonitorConfig() estimator_config = PoseEstimatorConfig() frame_queue = Queue(maxsize=5) # 限制队列大小,防止内存占用过大 stop_event = threading.Event() ...- main函数是程序的入口点,负责整体流程控制。
11.1. 初始化配置和对象
- monitor_config:初始化屏幕监控配置。
- estimator_config:初始化姿态估计器配置。
- frame_queue:创建帧队列,最大容量为5,防止内存占用过大。
- stop_event:创建线程事件对象,用于控制线程的停止。
11.2. 设置窗口属性
# 初始化窗口 window_name = "Pose Estimation" cv2.namedWindow(window_name, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) cv2.setWindowProperty(window_name, cv2.WND_PROP_TOPMOST, 1) # 设置窗口为最顶层- cv2.namedWindow:创建一个窗口,名称为**"Pose Estimation"**,窗口大小可调整,保持宽高比。
- cv2.setWindowProperty:将窗口设置为最顶层,确保窗口不被其他窗口遮挡。
11.3. 初始化姿态估计器
# 初始化姿态估计器 pose_estimator = PoseEstimator(estimator_config)- 创建PoseEstimator对象,传入姿态估计器配置。
11.4. 启动屏幕捕获线程
# 启动屏幕捕获线程 capture_thread = threading.Thread(target=capture_screen, args=(monitor_config, frame_queue, stop_event)) capture_thread.start()- 创建一个线程,目标函数为capture_screen,传入必要的参数。
- 启动线程,开始屏幕捕获。
11.5. 主循环
prev_time = time.time() try: while True: if not frame_queue.empty(): frame = frame_queue.get() # 处理图像 results = pose_estimator.process(frame) # 绘制结果 pose_estimator.draw(frame, results) # 计算并显示 FPS fps, prev_time = calculate_fps(prev_time) display_fps(frame, fps) # 显示图像,调整窗口大小以适应大分辨率 cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, 1280, 720) # 您可以根据需要调整窗口大小 cv2.imshow(window_name, frame) # 检查是否按下了 'q' 键 if cv2.waitKey(1) & 0xFF == ord('q'): logging.info("用户退出程序。") break except KeyboardInterrupt: logging.info("程序被手动中断。") except Exception as e: logging.exception(f"发生错误:{e}") finally: stop_event.set() capture_thread.join() cv2.destroyAllWindows()-
prev_time:记录上一帧的时间戳,初始化为当前时间。
-
try...except...finally结构用于捕获异常,确保程序能够正确退出。
11.5.1. 循环处理帧
-
while True:主循环。
-
if not frame_queue.empty():检查帧队列是否有数据。
-
frame = frame_queue.get():从队列中获取一帧图像。
-
results = pose_estimator.process(frame):对图像进行姿态估计,得到结果。
-
pose_estimator.draw(frame, results):在图像上绘制姿态估计的结果。
-
fps, prev_time = calculate_fps(prev_time):计算FPS,更新prev_time。
-
display_fps(frame, fps):在图像上显示FPS。
-
调整窗口大小,确保适应不同分辨率。
-
cv2.imshow(window_name, frame):显示图像。
-
-
cv2.waitKey(1) & 0xFF == ord('q'):检测用户是否按下了'q'键,如果是,退出循环。
11.5.2. 异常处理
-
except KeyboardInterrupt:捕获键盘中断(Ctrl+C),记录日志信息。
-
except Exception as e:捕获其他异常,记录异常信息。
11.5.3. 程序结束处理
-
finally块中,确保以下操作一定会执行:
-
stop_event.set():设置停止事件,通知屏幕捕获线程停止。
-
capture_thread.join():等待屏幕捕获线程结束。
-
cv2.destroyAllWindows():关闭所有OpenCV窗口。
-
12. 运行主函数
if __name__ == "__main__": main()- 检查当前文件是否作为主程序运行,如果是,则调用**main()**函数,开始程序执行。
总结
该代码的主要流程如下:
-
初始化配置:设置屏幕截取区域和姿态估计器的参数。
-
创建窗口:设置显示窗口的属性。
-
启动屏幕捕获线程:在一个单独的线程中,不断截取屏幕图像,并将其放入帧队列。
-
主循环处理:
- 从帧队列中获取最新的帧。
- 进行姿态估计,得到关键点和姿态信息。
- 绘制骨骼、关键点、头部方框和包围人物的矩形框。
- 计算并显示FPS。
- 将处理后的图像显示在窗口中。
-
用户交互:检测用户是否按下'q'键,或者是否发生异常,决定程序是否继续运行。
-
释放资源:在程序结束时,停止屏幕捕获线程,关闭所有窗口,释放占用的资源。
注意事项
-
屏幕尺寸配置:需要根据实际使用的屏幕尺寸修改MonitorConfig中的width和height参数,确保截取到的区域正确。
-
性能优化:为了减少CPU和内存占用,使用了多线程和队列,限制了队列的大小,避免因为处理速度跟不上而导致内存占用过大。
-
关键点可见性检查:在获取关键点坐标时,检查了关键点的可见性和坐标范围,确保绘制时不会出现错误。
-
异常处理:程序中加入了异常处理,确保在发生错误时能正确地记录日志,并释放资源。
-
FPS显示:通过计算当前时间和上一帧时间的差,动态计算并显示当前的FPS,方便观察程序的性能表现。
该代码适用于需要对屏幕上的人物进行实时姿态估计的场景,比如监控、人体姿态分析等。通过MediaPipe高效的姿态估计算法,能够在较低的计算资源下实现实时的姿态跟踪。