From 6cf06e0f9f7523bc0654cf739e59be2fe6443790 Mon Sep 17 00:00:00 2001 From: ly28266 <2826663494@qq.com> Date: Mon, 22 Dec 2025 10:51:04 +0800 Subject: [PATCH] Update main.py --- src/gesture_controll_drone/main.py | 387 ++++++++++++++--------------- 1 file changed, 183 insertions(+), 204 deletions(-) diff --git a/src/gesture_controll_drone/main.py b/src/gesture_controll_drone/main.py index 41f8485dfc..79cffab5a9 100644 --- a/src/gesture_controll_drone/main.py +++ b/src/gesture_controll_drone/main.py @@ -1,8 +1,3 @@ -""" -手势控制虚拟无人机系统 -基于MediaPipe的手部关键点检测 + Pygame的可视化模拟 -""" - import sys import time from typing import List, Tuple, Dict, Optional, Union @@ -12,17 +7,73 @@ import pygame import mediapipe as mp from pygame.locals import QUIT, KEYDOWN +from PIL import Image, ImageDraw, ImageFont # 引入Pillow处理中文显示 + # Pygame类型别名 ColorType = Tuple[int, int, int] PositionType = List[int] LandmarkType = List[Tuple[int, int]] -class VirtualDrone: + +# 全局工具函数:修复OpenCV/Pygame的中文显示 +def get_chinese_font(font_size: int = 24) -> ImageFont.FreeTypeFont: + """获取中文字体(兼容多系统)""" + # 优先尝试Windows系统字体 + font_paths = [ + "simhei.ttf", # Windows默认黑体 + "C:/Windows/Fonts/simhei.ttf", + "/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc", # Linux + "/Library/Fonts/PingFang.ttc" # macOS + ] + + for path in font_paths: + try: + return ImageFont.truetype(path, font_size, encoding="utf-8") + except: + continue + # fallback到默认字体(可能不支持中文) + print("⚠️ 未找到中文字体,使用默认字体") + return ImageFont.load_default() + + +def put_chinese_on_opencv(frame: np.ndarray, text: str, position: Tuple[int, int], + font_size: int = 24, color: Tuple[int, int, int] = (0, 255, 0), + bg_color: Tuple[int, int, int] = None) -> np.ndarray: """ - 虚拟无人机模拟器类 - 负责创建无人机可视化界面、管理无人机状态、执行控制命令 + 在OpenCV帧上绘制中文(新增背景色,提升可读性) + :param bg_color: 文本背景色,None则无背景 """ + # BGR转RGB + pil_frame = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(pil_frame) + font = get_chinese_font(font_size) + + # 绘制背景(可选) + if bg_color is not None: + text_bbox = draw.textbbox(position, text, font=font) + draw.rectangle(text_bbox, fill=bg_color) + + # 绘制中文 + draw.text(position, text, font=font, fill=(color[2], color[1], color[0])) + # RGB转BGR + return cv2.cvtColor(np.array(pil_frame), cv2.COLOR_RGB2BGR) + + +def put_chinese_on_pygame(surface: pygame.Surface, text: str, position: Tuple[int, int], + font_size: int = 24, color: Tuple[int, int, int] = (255, 255, 255)) -> None: + """在Pygame表面上绘制中文""" + # Pygame表面转PIL图像 + pil_surface = Image.fromarray(pygame.surfarray.array3d(surface).swapaxes(0, 1)) + draw = ImageDraw.Draw(pil_surface) + # 绘制中文 + draw.text(position, text, font=get_chinese_font(font_size), fill=color) + # PIL图像转Pygame表面 + pygame.surfarray.blit_array(surface, np.array(pil_surface).swapaxes(0, 1)) + + +class VirtualDrone: + """虚拟无人机模拟器类(修复Pygame中文显示)""" # 窗口配置常量 WINDOW_WIDTH: int = 400 WINDOW_HEIGHT: int = 300 @@ -67,17 +118,14 @@ def __init__(self) -> None: self.battery: float = self.INIT_BATTERY self.is_flying: bool = False - # 视觉样式 - self.font: pygame.font.Font = pygame.font.Font(None, 24) - - # 预计算的渲染位置(减少重复计算) + # 预计算的渲染位置 self._prop_positions: List[Tuple[int, int]] = [] self._update_prop_positions(150) # 初始位置 print("✅ 虚拟无人机模拟器已启动") def _update_prop_positions(self, drone_y: int) -> None: - """更新螺旋桨位置(减少重复计算)""" + """更新螺旋桨位置""" self._prop_positions = [ (self.position[0] - 20, drone_y - 12), (self.position[0] + 20, drone_y - 12), @@ -86,60 +134,46 @@ def _update_prop_positions(self, drone_y: int) -> None: ] def execute_command(self, command: str) -> bool: - """ - 执行无人机控制命令 - - 参数: - command: 控制命令字符串 - - 返回: - 命令是否成功执行 - """ + """执行无人机控制命令""" result: bool = False try: - # 命令执行逻辑 if command == "起飞" and not self.is_flying: self.is_flying = True self.altitude = 10.0 - print("🛫 无人机起飞") + print(f"🛫 无人机起飞 | 高度: {self.altitude}m") result = True - elif command == "降落" and self.is_flying: self.is_flying = False self.altitude = 0.0 - print("🛬 无人机降落") + print(f"🛬 无人机降落 | 高度: {self.altitude}m") result = True - elif command == "前进" and self.is_flying: self.position[1] = max(50, self.position[1] - self.SPEED) self.altitude = min(50.0, self.altitude + 0.5) - print("➡️ 无人机前进") + print(f"➡️ 无人机前进 | 位置: {self.position} | 高度: {self.altitude:.1f}m") result = True - elif command == "上升" and self.is_flying: self.altitude = min(100.0, self.altitude + 10.0) - print(f"⬆️ 无人机上升 | 当前高度: {self.altitude:.1f}m") + print(f"⬆️ 无人机上升 | 高度: {self.altitude:.1f}m") result = True - elif command == "紧急停止": self.is_flying = False self.altitude = 0.0 - print("🚨 紧急停止!") + print(f"🚨 无人机紧急停止 | 高度: {self.altitude}m") result = True - # 模拟电池消耗(仅飞行时) + # 模拟电池消耗 if self.is_flying: self.battery = max(0.0, self.battery - self.BATTERY_CONSUMPTION_RATE) except Exception as e: print(f"❌ 执行命令 '{command}' 时出错: {e}") - result = False return result def draw(self) -> None: - """绘制无人机界面和状态信息""" + """绘制无人机界面(修复中文显示)""" try: # 清屏 self.screen.fill(self.BG_COLOR) @@ -154,23 +188,16 @@ def draw(self) -> None: # 计算无人机Y坐标 drone_y: int = self.WINDOW_HEIGHT - 120 - int(self.altitude * 2) - # 选择无人机颜色 - drone_color: ColorType = self.DRONE_COLOR_FLYING if self.is_flying else self.DRONE_COLOR_GROUND - # 绘制无人机主体 - pygame.draw.circle( - self.screen, - drone_color, - (self.position[0], drone_y), - self.DRONE_RADIUS - ) + drone_color = self.DRONE_COLOR_FLYING if self.is_flying else self.DRONE_COLOR_GROUND + pygame.draw.circle(self.screen, drone_color, (self.position[0], drone_y), self.DRONE_RADIUS) - # 更新并绘制螺旋桨 + # 绘制螺旋桨 self._update_prop_positions(drone_y) for pos in self._prop_positions: pygame.draw.circle(self.screen, self.PROPELLER_COLOR, pos, self.PROPELLER_RADIUS) - # 绘制状态信息和控制说明 + # 绘制状态信息(用修复后的中文方法) self._draw_status_info() self._draw_control_instructions() @@ -181,25 +208,24 @@ def draw(self) -> None: print(f"❌ 绘制界面时出错: {e}") def _draw_status_info(self) -> None: - """绘制无人机状态信息""" - status: str = "飞行中" if self.is_flying else "在地面" - texts: List[str] = [ + """绘制无人机状态信息(中文)""" + status = "飞行中" if self.is_flying else "在地面" + texts = [ f"状态: {status}", f"高度: {self.altitude:.1f}m", f"电池: {self.battery:.1f}%", f"位置: ({self.position[0]}, {self.position[1]})" ] - # 批量渲染文本 - y_offset: int = 10 + # 用Pillow绘制中文 + y_offset = 10 for text in texts: - text_surface: pygame.Surface = self.font.render(text, True, self.TEXT_COLOR) - self.screen.blit(text_surface, (10, y_offset)) + put_chinese_on_pygame(self.screen, text, (10, y_offset), font_size=24, color=self.TEXT_COLOR) y_offset += 25 def _draw_control_instructions(self) -> None: - """绘制控制说明文本""" - controls: List[str] = [ + """绘制控制说明(中文)""" + controls = [ "控制说明:", "张开手掌 - 起飞", "握拳 - 降落", @@ -208,12 +234,11 @@ def _draw_control_instructions(self) -> None: "OK手势 - 紧急停止" ] - # 批量渲染文本 - y_offset: int = 10 - x_pos: int = self.WINDOW_WIDTH - 200 + # 用Pillow绘制中文 + y_offset = 10 + x_pos = self.WINDOW_WIDTH - 200 for text in controls: - text_surface: pygame.Surface = self.font.render(text, True, self.TEXT_COLOR) - self.screen.blit(text_surface, (x_pos, y_offset)) + put_chinese_on_pygame(self.screen, text, (x_pos, y_offset), font_size=24, color=self.TEXT_COLOR) y_offset += 25 def process_events(self) -> bool: @@ -222,19 +247,14 @@ def process_events(self) -> bool: for event in pygame.event.get(): if event.type == QUIT: return False - elif event.type == KEYDOWN: - # 提前处理退出按键(可选) - pass return True except Exception as e: print(f"❌ 处理窗口事件时出错: {e}") return False + class GestureRecognizer: - """ - 手势识别器类 - 基于MediaPipe实现手部关键点检测,识别预设手势并转换为控制命令 - """ + """手势识别器类""" # 摄像头配置 CAMERA_WIDTH: int = 640 CAMERA_HEIGHT: int = 480 @@ -278,21 +298,17 @@ def initialize_camera(self) -> bool: for cam_index in self.CAMERA_INDICES_TO_TRY: try: - # 修复:跨平台兼容的摄像头初始化 if sys.platform == "win32": self.cap = cv2.VideoCapture(cam_index, cv2.CAP_DSHOW) else: self.cap = cv2.VideoCapture(cam_index) if self.cap.isOpened(): - # 设置摄像头参数(一次性设置) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.CAMERA_WIDTH) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.CAMERA_HEIGHT) self.cap.set(cv2.CAP_PROP_FPS, 30) - self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) # 减少延迟 - + self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) print(f"✅ 找到摄像头在索引 {cam_index}") - print("✅ 摄像头初始化成功") return True except Exception as e: print(f"⚠️ 摄像头索引 {cam_index} 初始化失败: {e}") @@ -301,35 +317,25 @@ def initialize_camera(self) -> bool: raise Exception("❌ 无法找到可用的摄像头") def detect_gesture(self, frame: np.ndarray) -> Tuple[np.ndarray, str, str]: - """ - 检测帧中的手势 - - 返回: - 处理后的帧, 识别到的手势, 对应的命令 - """ + """检测帧中的手势""" gesture: str = "未检测到手势" command: str = "等待" try: - # 转换颜色空间(一次性转换) - rgb_frame: np.ndarray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) - - # 处理帧(禁用写操作以优化性能) + rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) rgb_frame.flags.writeable = False results = self.hands.process(rgb_frame) rgb_frame.flags.writeable = True - # 检测到手部 if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: - # 绘制关键点 + # 绘制关键点(更醒目的样式) self.mp_drawing.draw_landmarks( - frame, hand_landmarks, self.mp_hands.HAND_CONNECTIONS) - - # 提取关键点 - landmarks: LandmarkType = self._extract_landmarks(hand_landmarks, frame.shape) - - # 识别手势 + frame, hand_landmarks, self.mp_hands.HAND_CONNECTIONS, + self.mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=3), + self.mp_drawing.DrawingSpec(color=(255, 0, 0), thickness=2, circle_radius=1) + ) + landmarks = self._extract_landmarks(hand_landmarks, frame.shape) gesture = self._improved_classify_gesture(landmarks) command = self._gesture_to_command(gesture) @@ -338,43 +344,30 @@ def detect_gesture(self, frame: np.ndarray) -> Tuple[np.ndarray, str, str]: return frame, gesture, command - def _extract_landmarks(self, hand_landmarks, - frame_shape: Tuple[int, int, int]) -> LandmarkType: + def _extract_landmarks(self, hand_landmarks, frame_shape: Tuple[int, int, int]) -> LandmarkType: """提取手部关键点的像素坐标""" h, w, _ = frame_shape landmarks: LandmarkType = [] - - # 批量转换坐标 for lm in hand_landmarks.landmark: - px: int = int(lm.x * w) - py: int = int(lm.y * h) + px = int(lm.x * w) + py = int(lm.y * h) landmarks.append((px, py)) - return landmarks def _improved_classify_gesture(self, landmarks: LandmarkType) -> str: """改进的手势分类算法""" - # 校验关键点数量 if not landmarks or len(landmarks) < 21: return "未检测到手势" - # 获取关键点位 - thumb_tip: Tuple[int, int] = landmarks[self.THUMB_TIP] - index_tip: Tuple[int, int] = landmarks[self.INDEX_FINGER_TIP] - - # 检测手指状态 - fingers: List[bool] = self._detect_extended_fingers(landmarks) - extended_fingers: int = sum(fingers) + thumb_tip = landmarks[self.THUMB_TIP] + index_tip = landmarks[self.INDEX_FINGER_TIP] + fingers = self._detect_extended_fingers(landmarks) + extended_fingers = sum(fingers) # 检测OK手势 - thumb_index_dist: float = np.hypot( - thumb_tip[0] - index_tip[0], - thumb_tip[1] - index_tip[1] - ) - - if thumb_index_dist < self.OK_GESTURE_DISTANCE_THRESHOLD and extended_fingers <= 3: - if self._check_other_fingers_bent(landmarks): - return "OK手势" + thumb_index_dist = np.hypot(thumb_tip[0]-index_tip[0], thumb_tip[1]-index_tip[1]) + if thumb_index_dist < self.OK_GESTURE_DISTANCE_THRESHOLD and extended_fingers <=3 and self._check_other_fingers_bent(landmarks): + return "OK手势" # 基础手势分类 if extended_fingers == 5: @@ -390,32 +383,24 @@ def _improved_classify_gesture(self, landmarks: LandmarkType) -> str: def _detect_extended_fingers(self, landmarks: LandmarkType) -> List[bool]: """检测每根手指是否伸直""" - fingers: List[bool] = [] - - # 拇指检测 - fingers.append(landmarks[self.THUMB_TIP][0] < landmarks[self.THUMB_TIP-1][0]) - - # 其他手指检测(批量处理) - finger_indices: List[Tuple[int, int]] = [ + fingers = [landmarks[self.THUMB_TIP][0] < landmarks[self.THUMB_TIP-1][0]] + finger_indices = [ (self.INDEX_FINGER_TIP, self.INDEX_FINGER_TIP-2), (self.MIDDLE_FINGER_TIP, self.MIDDLE_FINGER_TIP-2), (self.RING_FINGER_TIP, self.RING_FINGER_TIP-2), (self.PINKY_TIP, self.PINKY_TIP-2) ] - for tip, pip in finger_indices: fingers.append(landmarks[tip][1] < landmarks[pip][1]) - return fingers def _check_other_fingers_bent(self, landmarks: LandmarkType) -> bool: """检查中指、无名指、小指是否弯曲""" - finger_checks: List[Tuple[int, int]] = [ + finger_checks = [ (self.MIDDLE_FINGER_TIP, self.MIDDLE_FINGER_TIP-2), (self.RING_FINGER_TIP, self.RING_FINGER_TIP-2), (self.PINKY_TIP, self.PINKY_TIP-2) ] - for tip, pip in finger_checks: if landmarks[tip][1] < landmarks[pip][1] - self.FINGER_BENT_THRESHOLD: return False @@ -423,7 +408,7 @@ def _check_other_fingers_bent(self, landmarks: LandmarkType) -> bool: def _gesture_to_command(self, gesture: str) -> str: """手势到命令的映射""" - command_map: Dict[str, str] = { + command_map = { "张开手掌": "起飞", "握拳": "降落", "食指指向": "前进", @@ -439,15 +424,12 @@ def release_camera(self) -> None: try: if self.cap and self.cap.isOpened(): self.cap.release() - print("✅ 摄像头资源已释放") except Exception as e: print(f"⚠️ 释放摄像头时出错: {e}") + class GestureDroneSystem: - """ - 手势控制无人机主系统类 - 整合手势识别和无人机模拟器 - """ + """手势控制无人机主系统类""" # 系统配置 COMMAND_INTERVAL: float = 1.0 EXIT_KEY: int = ord('q') @@ -461,17 +443,15 @@ def __init__(self) -> None: def initialize(self) -> bool: """初始化系统""" - print("=" * 50) - print("🤖 手势控制无人机系统") - print("=" * 50) + print("=" * 60) + print("🤖 手势控制无人机系统 (强化显示版)") + print("=" * 60) try: if not self.gesture_recognizer.initialize_camera(): return False - self._print_usage_instructions() return True - except Exception as e: print(f"❌ 系统初始化失败: {e}") self.cleanup() @@ -487,7 +467,7 @@ def _print_usage_instructions(self) -> None: print("✌️ 胜利手势 - 上升") print("👌 OK手势 - 紧急停止") print(f"\n⌨️ 按 '{chr(self.EXIT_KEY)}' 键退出程序") - print("=" * 50) + print("=" * 60) def run(self) -> None: """运行系统主循环""" @@ -497,45 +477,40 @@ def run(self) -> None: self.is_running = True print("▶️ 开始手势控制...") - # 性能统计 - frame_count: int = 0 - start_time: float = time.time() - last_command_time: float = 0.0 + frame_count = 0 + start_time = time.time() + last_command_time = 0.0 try: while self.is_running: - # 处理窗口事件 if not self.drone_simulator.process_events(): break - # 读取摄像头帧 - ret: bool - frame: np.ndarray ret, frame = self.gesture_recognizer.cap.read() - if not ret: time.sleep(0.1) continue - # 帧处理 frame_count += 1 - frame = cv2.flip(frame, 1) - - # 手势检测 + frame = cv2.flip(frame, 1) # 镜像翻转,操作更直观 processed_frame, gesture, command = self.gesture_recognizer.detect_gesture(frame) - # 命令执行控制 - current_time: float = time.time() - if (current_time - last_command_time > self.COMMAND_INTERVAL and - command != "等待"): + # 执行命令(加冷却,避免重复执行) + current_time = time.time() + if current_time - last_command_time > self.COMMAND_INTERVAL and command != "等待": if self.drone_simulator.execute_command(command): - print(f"✅ 执行命令: {command}") + print(f"✅ 执行命令: {command} (手势: {gesture})") last_command_time = current_time elif command != "等待": - print(f"⏳ 识别到: {gesture} -> {command} (冷却中)") + print(f"⏳ 识别到: {gesture} -> {command} (冷却中,剩余: {self.COMMAND_INTERVAL - (current_time - last_command_time):.1f}s)") - # 显示更新 - self._display_info(processed_frame, gesture, command, frame_count, start_time) + # 强化显示:在摄像头窗口绘制手势和无人机状态 + self._display_enhanced_info( + processed_frame, gesture, command, frame_count, start_time, + drone_status="飞行中" if self.drone_simulator.is_flying else "在地面", + drone_altitude=self.drone_simulator.altitude, + drone_battery=self.drone_simulator.battery + ) cv2.imshow(self.WINDOW_NAME, processed_frame) self.drone_simulator.draw() @@ -543,78 +518,82 @@ def run(self) -> None: if cv2.waitKey(1) & 0xFF == self.EXIT_KEY: print("\n🛑 用户请求退出程序") break - except KeyboardInterrupt: print("\n🛑 用户中断程序") except Exception as e: print(f"❌ 运行时错误: {e}") finally: self.cleanup() - - # 显示性能统计 self._show_performance_stats(start_time, frame_count) - def _display_info(self, frame: np.ndarray, gesture: str, command: str, - frame_count: int, start_time: float) -> None: - """在视频帧上绘制信息""" - # 计算FPS - elapsed_time: float = time.time() - start_time - fps: float = frame_count / elapsed_time if elapsed_time > 0 else 0.0 + def _display_enhanced_info(self, frame: np.ndarray, gesture: str, command: str, + frame_count: int, start_time: float, + drone_status: str, drone_altitude: float, drone_battery: float) -> None: + """ + 强化版显示:在摄像头窗口左侧醒目显示手势和无人机状态 + 布局:左上角固定区域,带背景色,字体更大更清晰 + """ + elapsed_time = time.time() - start_time + fps = frame_count / elapsed_time if elapsed_time > 0 else 0.0 + + # ===== 左侧核心信息显示区(带半透明背景,提升可读性)===== + # 1. 当前手势(大号字体,绿色,带黑色背景) + frame = put_chinese_on_opencv( + frame, f"当前手势: {gesture}", + position=(20, 20), font_size=32, + color=(0, 255, 0), bg_color=(0, 0, 0) + ) - # 文本配置(批量处理) - text_configs: List[Tuple[str, Tuple[int, int], ColorType, float, int]] = [ - (f"🤘 手势: {gesture}", (10, 30), (0, 255, 0), 0.7, 2), - (f"🎮 命令: {command}", (10, 60), (0, 255, 255), 0.7, 2), - (f"⚡ FPS: {fps:.1f}", (10, 90), (255, 255, 255), 0.6, 2), - (f"按 '{chr(self.EXIT_KEY)}' 退出", (10, 450), (255, 255, 255), 0.5, 1) - ] + # 2. 无人机状态(大号字体,黄色,带黑色背景) + frame = put_chinese_on_opencv( + frame, f"无人机状态: {drone_status}", + position=(20, 70), font_size=32, + color=(255, 255, 0), bg_color=(0, 0, 0) + ) - # 批量绘制文本 - for text, pos, color, scale, thickness in text_configs: - cv2.putText( - frame, text, pos, - cv2.FONT_HERSHEY_SIMPLEX, scale, color, thickness - ) + # 3. 补充信息(中号字体,白色) + frame = put_chinese_on_opencv( + frame, f"高度: {drone_altitude:.1f}m | 电池: {drone_battery:.1f}%", + position=(20, 120), font_size=24, + color=(255, 255, 255), bg_color=(0, 0, 0) + ) + + # 4. 对应命令(中号字体,青色) + frame = put_chinese_on_opencv( + frame, f"执行命令: {command}", + position=(20, 160), font_size=24, + color=(0, 255, 255), bg_color=(0, 0, 0) + ) + + # 5. 基础信息(小号字体) + cv2.putText( + frame, f"FPS: {fps:.1f} | 按 '{chr(self.EXIT_KEY)}' 退出", + (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2 + ) def _show_performance_stats(self, start_time: float, frame_count: int) -> None: """显示性能统计""" - total_time: float = time.time() - start_time - avg_fps: float = frame_count / total_time if total_time > 0 else 0.0 - - print("\n" + "=" * 50) + total_time = time.time() - start_time + avg_fps = frame_count / total_time if total_time > 0 else 0.0 + print("\n" + "=" * 60) print("📊 性能统计") - print("=" * 50) + print("=" * 60) print(f"⏱️ 总运行时间: {total_time:.2f} 秒") print(f"🖼️ 处理帧数: {frame_count}") print(f"⚡ 平均FPS: {avg_fps:.2f}") - print("=" * 50) + print("=" * 60) def cleanup(self) -> None: """清理系统资源""" self.is_running = False print("\n🧹 正在清理系统资源...") - - try: - self.gesture_recognizer.release_camera() - except Exception as e: - print(f"⚠️ 释放摄像头资源时出错: {e}") - - try: - cv2.destroyAllWindows() - print("✅ OpenCV窗口已关闭") - except Exception as e: - print(f"⚠️ 关闭OpenCV窗口时出错: {e}") - - try: - pygame.quit() - print("✅ Pygame资源已释放") - except Exception as e: - print(f"⚠️ 退出Pygame时出错: {e}") - + self.gesture_recognizer.release_camera() + cv2.destroyAllWindows() + pygame.quit() print("✅ 系统已安全关闭") + if __name__ == "__main__": - # 创建并运行系统 try: drone_system = GestureDroneSystem() drone_system.run()