Skip to content

Commit 8fa89b8

Browse files
committed
update code comment
1 parent 9db6a5a commit 8fa89b8

File tree

5 files changed

+39
-39
lines changed

5 files changed

+39
-39
lines changed

challenge/onsite_competition/sdk/cam.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import time
33
from typing import Dict, Optional, Tuple
44

5-
import cv2 # 仅用于极端兜底 resize,可去掉
5+
import cv2
66
import numpy as np
77
import pyrealsense2 as rs
88
from save_obs import save_obs
@@ -37,7 +37,7 @@ def start(self):
3737
cw, ch, cfps = self.color_res
3838
dw, dh, dfps = self.depth_res
3939

40-
# 开启彩色和深度流
40+
# open stream for color and depth
4141
cfg.enable_stream(rs.stream.color, cw, ch, rs.format.bgr8, cfps)
4242
cfg.enable_stream(rs.stream.depth, dw, dh, rs.format.z16, dfps)
4343

@@ -47,23 +47,22 @@ def start(self):
4747
depth_sensor = profile.get_device().first_depth_sensor()
4848
self.depth_scale = float(depth_sensor.get_depth_scale())
4949

50-
# 对齐到彩色
50+
# align to color
5151
self.align = rs.align(rs.stream.color)
5252

53-
# 预热
53+
# warm up
5454
for _ in range(self.warmup_frames):
5555
self.pipeline.wait_for_frames()
5656

57-
# 做一次对齐检查,确保后续帧尺寸一致
57+
# align check
5858
frames = self.pipeline.wait_for_frames()
5959
frames = self.align.process(frames)
6060
color = frames.get_color_frame()
6161
depth = frames.get_depth_frame()
62-
assert color and depth, "预热对齐失败:未获得 color/depth 帧"
62+
assert color and depth, "warm up align failed"
6363
rgb = np.asanyarray(color.get_data())
6464
depth_raw = np.asanyarray(depth.get_data())
6565
if depth_raw.shape != rgb.shape[:2]:
66-
# 理论上不应发生;发生时先兜底到相同尺寸(注意:仅尺寸匹配,几何可能不严格)
6766
depth_raw = cv2.resize(depth_raw, (rgb.shape[1], rgb.shape[0]), interpolation=cv2.INTER_NEAREST)
6867
self.started = True
6968

@@ -98,12 +97,12 @@ def get_observation(self, timeout_ms: int = 1000) -> Dict:
9897
color = frames.get_color_frame()
9998
depth = frames.get_depth_frame()
10099
if not color or not depth:
101-
raise RuntimeError("未获得对齐后的 color/depth ")
100+
raise RuntimeError("can not align color/depth frame")
102101

103102
rgb = np.asanyarray(color.get_data()) # HxWx3, uint8 (BGR)
104103
depth_raw = np.asanyarray(depth.get_data()) # HxW, uint16
105104
if depth_raw.shape != rgb.shape[:2]:
106-
# 极端兜底(理论上 align 后应一致)
105+
# Extreme fallback (theoretically should be consistent after alignment).
107106
depth_raw = cv2.resize(depth_raw, (rgb.shape[1], rgb.shape[0]), interpolation=cv2.INTER_NEAREST)
108107

109108
depth_m = depth_raw.astype(np.float32) * float(self.depth_scale)
@@ -113,7 +112,6 @@ def get_observation(self, timeout_ms: int = 1000) -> Dict:
113112
return {"rgb": rgb, "depth": depth_m, "timestamp_s": ts_s}
114113

115114

116-
# --- 最小示例 ---
117115
if __name__ == "__main__":
118116
with AlignedRealSense(serial_no=None) as cam:
119117
obs = cam.get_observation()

challenge/onsite_competition/sdk/control.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,63 +18,63 @@ def __init__(self):
1818
self.current_yaw = 0.0
1919
self.start_yaw = None
2020
self.turning = False
21-
self.turn_angle = math.radians(90) # 角度调这里
22-
self.angular_speed = -0.2 # 方向和速度调这里
21+
self.turn_angle = math.radians(90) # angle
22+
self.angular_speed = -0.2 # dirention and speed
2323
self.rate = rospy.Rate(10) # 10Hz
2424

2525
def odom_callback(self, msg):
26-
# 从四元数获取偏航角
26+
# Get the yaw angle from a quaternion.
2727
orientation = msg.pose.pose.orientation
2828
quaternion = [orientation.x, orientation.y, orientation.z, orientation.w]
2929
_, _, yaw = euler_from_quaternion(quaternion)
3030

3131
self.current_yaw = yaw
3232

33-
# 初始化起始偏航角
33+
# initialize the start yaw
3434
if self.start_yaw is None and not self.turning:
3535
self.start_yaw = yaw
36-
rospy.loginfo(f"起始偏航角: {math.degrees(self.start_yaw):.2f}")
36+
rospy.loginfo(f"start yaw: {math.degrees(self.start_yaw):.2f}")
3737

3838
def execute_turn(self):
3939
if self.start_yaw is None:
40-
rospy.loginfo("等待初始位姿数据...")
40+
rospy.loginfo("wait for init yaw state...")
4141
return False
4242

4343
if not self.turning:
4444
self.turning = True
45-
rospy.loginfo("开始原地转弯90度")
45+
rospy.loginfo("start to turn")
4646

47-
# 计算已转过的角度
47+
# compute turned angle
4848
current_angle = self.current_yaw - self.start_yaw
4949

50-
# 处理角度超过π或小于-π的情况(角度归一化)
50+
# normalize the angle
5151
if current_angle > math.pi:
5252
current_angle -= 2 * math.pi
5353
elif current_angle < -math.pi:
5454
current_angle += 2 * math.pi
5555

56-
# 计算还需转过的角度
56+
# compute remaining angle
5757
remaining_angle = self.turn_angle - abs(current_angle)
5858

59-
# 创建 Twist 消息
59+
# create Twist msg
6060
twist = Twist()
6161

62-
# 如果还没达到目标角度,继续旋转
63-
if remaining_angle > 0.05: # 留一点余量(约2.86度
62+
# if not reach the goal angle, keep turning
63+
if remaining_angle > 0.05: # allow some diff (about 2.86 degree
6464
twist.angular.z = self.angular_speed * min(1.0, remaining_angle * 6)
6565
print(f"twist.angular.z {twist.angular.z} remaining_angle {remaining_angle}")
6666
self.cmd_vel_pub.publish(twist)
6767
return False
6868
else:
6969
twist.angular.z = 0.0
7070
self.cmd_vel_pub.publish(twist)
71-
rospy.loginfo(f"完成转弯,最终偏航角: {math.degrees(self.current_yaw):.2f}")
71+
rospy.loginfo(f"finish turn, final yaw: {math.degrees(self.current_yaw):.2f}")
7272
return True
7373

7474
def run(self):
7575
while not rospy.is_shutdown():
7676
if self.execute_turn():
77-
rospy.loginfo("任务完成,退出节点")
77+
rospy.loginfo("Task finished")
7878
break
7979
self.rate.sleep()
8080

@@ -112,7 +112,7 @@ def move_forward(self, distance=0.25):
112112
rospy.loginfo("Move forward command executed.")
113113

114114
def turn_left(self, angle=15, speed=0.2):
115-
self.turn_angle = math.radians(angle) # 角度调这里
115+
self.turn_angle = math.radians(angle) # update angle
116116
self.angular_speed = speed # Set positive angular speed for left turn
117117
self.start_yaw = None # Reset start yaw to current position
118118
self.turning = False # Reset turning flag
@@ -121,7 +121,7 @@ def turn_left(self, angle=15, speed=0.2):
121121
rospy.loginfo("Turn left command executed.")
122122

123123
def turn_right(self, angle=15, speed=-0.2):
124-
self.turn_angle = math.radians(angle) # 角度调这里
124+
self.turn_angle = math.radians(angle) # update angle
125125
self.angular_speed = speed # Set positive angular speed for left turn
126126
self.start_yaw = None # Reset start yaw to current position
127127
self.turning = False # Reset turning flag

challenge/onsite_competition/sdk/real_world_env.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
from cam import AlignedRealSense
22
from control import DiscreteRobotController
33

4+
from internnav.env import Env
45

5-
class RealWorldEnv:
6+
7+
class RealWorldEnv(Env):
68
def __init__(self):
79
self.node = DiscreteRobotController()
810
self.cam = AlignedRealSense()

challenge/onsite_competition/sdk/save_obs.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,13 @@ def save_obs(
1313
obs: dict,
1414
outdir: str = "./captures",
1515
prefix: str = None,
16-
max_depth_m: float = 3.0, # 伪彩可视化的裁剪上限
16+
max_depth_m: float = 3.0,
1717
save_rgb: bool = True,
1818
save_depth_16bit: bool = True,
1919
save_depth_vis: bool = True,
2020
):
2121
"""
22-
将 obs = {"rgb": HxWx3 uint8 (BGR), "depth": HxW float32 (m), "timestamp_s": float, "intrinsics": {...}}
23-
保存到磁盘。
22+
save obs = {"rgb": HxWx3 uint8 (BGR), "depth": HxW float32 (m), "timestamp_s": float, "intrinsics": {...}}
2423
"""
2524
Path(outdir).mkdir(parents=True, exist_ok=True)
2625

@@ -31,13 +30,13 @@ def save_obs(
3130
rgb = obs.get("rgb", None)
3231
depth_m = obs.get("depth", None)
3332

34-
# 1) 保存 RGB(BGR 排列,cv2 直接写
33+
# 1) save RGB(BGR,cv2)
3534
rgb_path = None
3635
if save_rgb and rgb is not None:
3736
rgb_path = os.path.join(outdir, f"{prefix}_rgb.jpg")
3837
cv2.imwrite(rgb_path, rgb)
3938

40-
# 2) 保存 16-bit 深度(单位毫米
39+
# 2) save 16-bit depth(unit: mm
4140
depth16_path = None
4241
vis_path = None
4342
if depth_m is not None and (save_depth_16bit or save_depth_vis):
@@ -47,16 +46,16 @@ def save_obs(
4746
depth16_path = os.path.join(outdir, f"{prefix}_depth_mm.png")
4847
cv2.imwrite(depth16_path, depth_mm)
4948

50-
# 3) 保存伪彩(仅用于查看)
49+
# 3) save depth vis
5150
if save_depth_vis:
5251
d_clip = np.clip(d, 0.0, max_depth_m)
53-
# 近处亮一些:先归一化到 0~255,再取反做色图
52+
# Brighten the near field: first normalize to 0–255, then invert and apply a colormap.
5453
d_norm = (d_clip / max_depth_m * 255.0).astype(np.uint8)
5554
depth_color = cv2.applyColorMap(255 - d_norm, cv2.COLORMAP_JET)
5655
vis_path = os.path.join(outdir, f"{prefix}_depth_vis.png")
5756
cv2.imwrite(vis_path, depth_color)
5857

59-
# 4) 元信息
58+
# 4) meta info
6059
meta = {
6160
"timestamp_s": ts,
6261
"paths": {
@@ -65,7 +64,7 @@ def save_obs(
6564
"depth_vis": vis_path,
6665
},
6766
"intrinsics": obs.get("intrinsics", {}),
68-
"notes": "depth_mm.png 是以毫米存储的 16-bit PNGdepth_vis.png 仅用于可视化。",
67+
"notes": "depth_mm.png 是以毫米存储的 16-bit PNG, depth_vis.png 仅用于可视化。",
6968
}
7069
with open(os.path.join(outdir, f"{prefix}_meta.json"), "w") as f:
7170
json.dump(meta, f, indent=2, ensure_ascii=False)
@@ -86,7 +85,7 @@ def _resolve(base: str, p: Optional[str]) -> Optional[str]:
8685

8786
def load_obs_from_meta(meta_path: str, nan_for_zeros: bool = False) -> Dict:
8887
"""
89-
读取由 save_obs() 生成的 meta.json并还原为 obs dict:
88+
读取由 save_obs() 生成的 meta.json, 并还原为 obs dict:
9089
{
9190
"rgb": uint8[H,W,3] (BGR),
9291
"depth": float32[H,W] (meters) 或 None,

challenge/onsite_competition/sdk/test_agent.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ def test_agent(cfg_path=None, obs=None):
4646
'rgb': np.load('challenge/onsite_competition/captures/sim_rgb.npy'),
4747
'depth': np.load('challenge/onsite_competition/captures/sim_depth.npy'),
4848
}
49-
print(sim_obs['rgb'].shape, sim_obs['depth'].shape) # TODO: test dtype (uint8 and float32) and value range
49+
print(sim_obs['rgb'].shape, sim_obs['depth'].shape) # dtype (uint8 and float32) and value range
50+
# TODO: crop to 256,256, test with fake_obs_256
5051

5152
# work in progress, baseline model will be updated soon
5253
# test_agent(cfg_path=cfg_path, obs=fake_obs_256)

0 commit comments

Comments
 (0)