mi-task/task_4/task_4.py
Havoc c2b29f18f3 重构任务4和任务5,更新任务流程和参数
- 在main.py中注释掉run_task_2函数,确保任务执行流程的简化。
- 在task_4.py中添加go_straight_until_sky_ratio_below函数以实现基于灰色天空比例的直线移动。
- 更新README.md以反映任务4和任务5的最新描述,合并相关内容。
- 删除task_5中的多个不再使用的文件,优化代码结构。
2025-05-27 01:18:10 +08:00

114 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import time
import sys
import os
import cv2
import numpy as np
# 添加父目录到路径以便能够导入utils
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from base_move.turn_degree import turn_degree
from base_move.go_straight import go_straight
from utils.log_helper import LogHelper, get_logger, section, info, debug, warning, error, success, timing
from utils.gray_sky_analyzer import analyze_gray_sky_ratio
# 创建本模块特定的日志记录器
logger = get_logger("任务4")
def run_task_4(ctrl, msg):
"""
参数:
ctrl: Robot_Ctrl对象
msg: 控制消息对象
image_processor: 可选的图像处理器实例
"""
section('任务4-1直线移动', "移动")
go_straight(ctrl, msg, distance=6)
section('任务4-2移动直到灰色天空比例小于阈值', "天空检测")
go_straight_until_sky_ratio_below(ctrl, msg, sky_ratio_threshold=0.2)
def go_straight_until_sky_ratio_below(ctrl, msg, sky_ratio_threshold=0.2, step_distance=0.5, max_distance=10, speed=0.3):
"""
控制机器人沿直线行走,直到灰色天空比例小于指定阈值
参数:
ctrl: Robot_Ctrl对象
msg: 控制命令消息对象
sky_ratio_threshold: 灰色天空比例阈值,当检测到的比例小于此值时停止
step_distance: 每次移动的步长(米)
max_distance: 最大移动距离(米),防止无限前进
speed: 移动速度(米/秒)
返回:
bool: 是否成功找到天空比例小于阈值的位置
"""
total_distance = 0
success_flag = False
# 设置移动命令
msg.mode = 11 # Locomotion模式
msg.gait_id = 26 # 自变频步态
msg.step_height = [0.06, 0.06] # 抬腿高度
while total_distance < max_distance:
# 获取当前图像
current_image = ctrl.image_processor.get_current_image()
if current_image is None:
warning("无法获取图像,等待...", "图像")
time.sleep(0.5)
continue
# 保存当前图像用于分析
temp_image_path = "/tmp/current_sky_image.jpg"
cv2.imwrite(temp_image_path, current_image)
# 分析灰色天空比例
try:
sky_ratio = analyze_gray_sky_ratio(temp_image_path)
info(f"当前灰色天空比例: {sky_ratio:.2%}", "分析")
# 如果天空比例小于阈值,停止移动
if sky_ratio < sky_ratio_threshold:
success(f"检测到灰色天空比例({sky_ratio:.2%})小于阈值({sky_ratio_threshold:.2%}),停止移动", "完成")
success_flag = True
break
except Exception as e:
error(f"分析图像时出错: {e}", "错误")
# 继续前进一段距离
info(f"继续前进 {step_distance} 米...", "移动")
# 设置移动速度和方向
msg.vel_des = [speed, 0, 0] # [前进速度, 侧向速度, 角速度]
msg.duration = 0 # wait next cmd
msg.life_count += 1
# 发送命令
ctrl.Send_cmd(msg)
# 估算前进时间
move_time = step_distance / speed
time.sleep(move_time)
# 累计移动距离
total_distance += step_distance
info(f"已移动总距离: {total_distance:.2f}", "距离")
# 平滑停止
if hasattr(ctrl.base_msg, 'stop_smooth'):
ctrl.base_msg.stop_smooth()
else:
ctrl.base_msg.stop()
if not success_flag and total_distance >= max_distance:
warning(f"已达到最大移动距离 {max_distance} 米,但未找到天空比例小于 {sky_ratio_threshold:.2%} 的位置", "超时")
return success_flag