Delete openscene-v1.1/process_data
Browse filesFiles changed (12)
- openscene-v1.1/process_data/__init__.pyDeleted
- openscene-v1.1/process_data/create_nuplan_data_with_vis.pyDeleted-446
- openscene-v1.1/process_data/driving_command.pyDeleted-178
- openscene-v1.1/process_data/helpers/__init__.pyDeleted
- openscene-v1.1/process_data/helpers/canbus.pyDeleted-50
- openscene-v1.1/process_data/helpers/multiprocess_helper.pyDeleted-32
- openscene-v1.1/process_data/helpers/multisweep_helper.pyDeleted-66
- openscene-v1.1/process_data/helpers/transformation.pyDeleted-138
- openscene-v1.1/process_data/helpers/viz.pyDeleted-93
- openscene-v1.1/process_data/helpers/viz_box.pyDeleted-102
- openscene-v1.1/process_data/helpers/viz_box_2d.pyDeleted-135
- openscene-v1.1/process_data/process.shDeleted-32
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446import argparseimport shutilfrom typing import Dict, List
# import mmcvimport numpy as npfrom os import listdirfrom os.path import isfile, join
from pyquaternion import Quaternion
import cv2
from tqdm import tqdm
import os
import multiprocessingimport picklefrom nuplan.common.actor_state.state_representation import StateSE2from nuplan.common.maps.abstract_map import AbstractMapfrom nuplan.common.maps.nuplan_map.map_factory import get_maps_api
from nuplan.database.nuplan_db_orm.nuplandb_wrapper import NuPlanDBWrapperfrom nuplan.database.nuplan_db_orm.lidar import Lidarfrom nuplan.database.nuplan_db.nuplan_scenario_queries import ( get_traffic_light_status_for_lidarpc_token_from_db, get_images_from_lidar_tokens, get_cameras,)from nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario import CameraChannelfrom navsim.common.extraction.driving_command import get_driving_command
from helpers.multiprocess_helper import get_scenes_per_threadfrom helpers.canbus import CanBusfrom helpers.multisweep_helper import obtain_sensor2top
NUPLAN_MAPS_ROOT = os.environ["NUPLAN_MAPS_ROOT"]filtered_classes = ["traffic_cone", "barrier", "czone_sign", "generic_object"]
def create_nuplan_info( nuplan_db_wrapper: NuPlanDBWrapper, db_names: List[str], args): nuplan_sensor_root = args.nuplan_sensor_path
# get all db files & assign db files for current thread.
scene_dict = {} log_sensors = os.listdir(nuplan_sensor_root)
# For each sequence... for log_db_name in db_names: log_db = nuplan_db_wrapper.get_log_db(log_db_name) log_name = log_db.log_name log_token = log_db.log.token map_location = log_db.log.location vehicle_name = log_db.log.vehicle_name
# NOTE: I am unsure why "us-nv-las-vegas-strip" is saved as "las_vegas" in db logs. map_name = map_location if map_location != "las_vegas" else "us-nv-las-vegas-strip" map_api = get_maps_api(NUPLAN_MAPS_ROOT, "nuplan-maps-v1.0", map_name) # NOTE: lru cached
log_file = os.path.join(nuplan_db_path, log_db_name + ".db") if log_db_name not in log_sensors: continue
frame_idx = 0
# list (sequence) of point clouds (each frame). lidar_pc_list = log_db.lidar_pc lidar_pcs = lidar_pc_list
# get log cam infos log_cam_infos = {} for cam in get_cameras(log_file, [str(channel.value) for channel in CameraChannel]): intrinsics = np.array(pickle.loads(cam.intrinsic), dtype=np.float32) translation = np.array(pickle.loads(cam.translation), dtype=np.float32) rotation = np.array(pickle.loads(cam.rotation), dtype=np.float32) rotation = Quaternion(rotation).rotation_matrix distortion = np.array(pickle.loads(cam.distortion), dtype=np.float32) c = dict( intrinsic=intrinsics, distortion=distortion, translation=translation, rotation=rotation, ) log_cam_infos[cam.token] = c
# Find the first valid point clouds, with all 8 cameras available. for start_idx in range(0, len(lidar_pcs)): retrieved_images = get_images_from_lidar_tokens( log_file, [lidar_pcs[start_idx].token], [str(channel.value) for channel in CameraChannel], ) if len(list(retrieved_images)) == 8: break
# Find the true LiDAR start_idx with the minimum timestamp difference with CAM_F0. retrieved_images_0 = get_images_from_lidar_tokens( log_file, [lidar_pcs[start_idx].token], ["CAM_F0"] ) diff_0 = abs(list(retrieved_images_0)[0].timestamp - lidar_pcs[start_idx].timestamp) retrieved_images_1 = get_images_from_lidar_tokens( log_file, [lidar_pcs[start_idx + 1].token], ["CAM_F0"] ) diff_1 = abs(list(retrieved_images_1)[0].timestamp - lidar_pcs[start_idx + 1].timestamp) start_idx = start_idx if diff_0 < diff_1 else start_idx + 1
# Find key_frames (controled by args.sample_interval) lidar_pc_list = lidar_pc_list[start_idx :: args.sample_interval] index = -1 for lidar_pc in tqdm(lidar_pc_list, dynamic_ncols=True): index += 1
# LiDAR attributes. lidar_pc_token = lidar_pc.token scene_token = lidar_pc.scene_token pc_file_name = lidar_pc.filename next_token = lidar_pc.next_token prev_token = lidar_pc.prev_token lidar_token = lidar_pc.lidar_token time_stamp = lidar_pc.timestamp scene_name = "log-" + lidar_pc.scene.name lidar_boxes = lidar_pc.lidar_boxes roadblock_ids = [ str(roadblock_id) for roadblock_id in str(lidar_pc.scene.roadblock_ids).split(" ") if len(roadblock_id) > 0 ]
# Saving configurations. if scene_token not in scene_dict.keys(): scene_dict[scene_token] = [] frame_idx = 0 if frame_idx == 0: scene_dict[scene_token] = []
can_bus = CanBus(lidar_pc).tensor lidar = log_db.session.query(Lidar).filter(Lidar.token == lidar_token).all() pc_file_path = os.path.join(args.nuplan_sensor_path, pc_file_name)
if not os.path.exists(pc_file_path): # some lidar files are missing. # print(pc_file_path) with open("./nofile.log", "a") as f: f.write(pc_file_path) f.write("\n") continue
traffic_lights = [] for traffic_light_status in get_traffic_light_status_for_lidarpc_token_from_db( log_file, lidar_pc_token ): lane_connector_id: int = traffic_light_status.lane_connector_id is_red: bool = traffic_light_status.status.value == 2 traffic_lights.append((lane_connector_id, is_red))
ego_pose = StateSE2( lidar_pc.ego_pose.x, lidar_pc.ego_pose.y, lidar_pc.ego_pose.quaternion.yaw_pitch_roll[0], ) driving_command = get_driving_command(ego_pose, map_api, roadblock_ids)
info = { "token": lidar_pc_token, "frame_idx": frame_idx, "timestamp": time_stamp, "log_name": log_name, "log_token": log_token, "scene_name": scene_name, "scene_token": scene_token, "map_location": map_location, "roadblock_ids": roadblock_ids, "vehicle_name": vehicle_name, "can_bus": can_bus, "lidar_path": pc_file_name, # use the relative path. "lidar2ego_translation": lidar[0].translation_np, "lidar2ego_rotation": [ lidar[0].rotation.w, lidar[0].rotation.x, lidar[0].rotation.y, lidar[0].rotation.z, ], "ego2global_translation": can_bus[:3], "ego2global_rotation": can_bus[3:7], "ego_dynamic_state": [ lidar_pc.ego_pose.vx, lidar_pc.ego_pose.vy, lidar_pc.ego_pose.acceleration_x, lidar_pc.ego_pose.acceleration_y, ], "traffic_lights": traffic_lights, "driving_command": driving_command, "cams": dict(), "prev_sweep_token": prev_token, "next_sweep_token": next_token, "sweeps": [], } info["sample_prev"] = None info["sample_next"] = None if index > 0: # find prev. info["sample_prev"] = lidar_pc_list[index - 1].token if index < len(lidar_pc_list) - 1: # find next. next_key_token = lidar_pc_list[index + 1].token next_key_scene = lidar_pc_list[index + 1].scene_token info["sample_next"] = next_key_token else: next_key_token, next_key_scene = None, None
if next_key_token == None or next_key_token == "": frame_idx = 0 else: if next_key_scene != scene_token: frame_idx = 0 else: frame_idx += 1
# Parse lidar2ego translation. l2e_r = info["lidar2ego_rotation"] l2e_t = info["lidar2ego_translation"] e2g_r = info["ego2global_rotation"] e2g_t = info["ego2global_translation"] l2e_r_mat = Quaternion(l2e_r).rotation_matrix e2g_r_mat = Quaternion(e2g_r).rotation_matrix
# add lidar2global: map point coord in lidar to point coord in the global l2e = np.eye(4) l2e[:3, :3] = l2e_r_mat l2e[:3, -1] = l2e_t e2g = np.eye(4) e2g[:3, :3] = e2g_r_mat e2g[:3, -1] = e2g_t lidar2global = np.dot(e2g, l2e) info["ego2global"] = e2g info["lidar2ego"] = l2e info["lidar2global"] = lidar2global
# obtain 8 image's information per frame retrieved_images = get_images_from_lidar_tokens( log_file, [lidar_pc.token], [str(channel.value) for channel in CameraChannel] ) cams = {} for img in retrieved_images: channel = img.channel filename = img.filename_jpg filepath = os.path.join(args.nuplan_sensor_path, filename) if not os.path.exists(filepath): frame_str = f"{log_db_name}, {lidar_pc_token}" tqdm.tqdm.write(f"camera file missing: {frame_str}") continue cam_info = log_cam_infos[img.camera_token] cams[channel] = dict( data_path=filename, # use the relative path. sensor2lidar_rotation=cam_info["rotation"], sensor2lidar_translation=cam_info["translation"], cam_intrinsic=cam_info["intrinsic"], distortion=cam_info["distortion"], ) if len(cams) != 8: frame_str = f"{log_db_name}, {lidar_pc_token}" tqdm.write(f"not all cameras are available: {frame_str}") continue info["cams"] = cams
# parse sweeps if assigned. sweeps = [] tmp_info = info count = 0 while len(sweeps) < args.max_sweeps: if tmp_info["prev_sweep_token"] == None: break
# Get the previous sweep and update info to previous sweep. sweep = obtain_sensor2top( tmp_info["prev_sweep_token"], log_db, l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, args )
# Save sweeps in every sweep_interval. tmp_info = sweep if count == args.sweep_interval: if os.path.exists(sweep["data_path"]): sweeps.append(sweep) count = 0 else: count += 1 info["sweeps"] = sweeps
# Parse 3D object labels. if not args.is_test: if args.filter_instance: fg_lidar_boxes = [ box for box in lidar_boxes if box.category.name not in filtered_classes ] else: fg_lidar_boxes = lidar_boxes
instance_tokens = [item.token for item in fg_lidar_boxes] track_tokens = [item.track_token for item in fg_lidar_boxes]
inv_ego_r = lidar_pc.ego_pose.trans_matrix_inv ego_yaw = lidar_pc.ego_pose.quaternion.yaw_pitch_roll[0]
locs = np.array( [ np.dot( inv_ego_r[:3, :3], (b.translation_np - lidar_pc.ego_pose.translation_np).T, ).T for b in fg_lidar_boxes ] ).reshape(-1, 3) dims = np.array([[b.length, b.width, b.height] for b in fg_lidar_boxes]).reshape( -1, 3 ) rots = np.array([b.yaw for b in fg_lidar_boxes]).reshape(-1, 1) rots = rots - ego_yaw
velocity = np.array([[b.vx, b.vy] for b in fg_lidar_boxes]).reshape(-1, 2) velocity_3d = np.array([[b.vx, b.vy, b.vz] for b in fg_lidar_boxes]).reshape(-1, 3)
# convert velo from global to lidar: only need the rotation matrix for i in range(len(fg_lidar_boxes)): velo = np.array([*velocity[i], 0.0]) velo = velo @ np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T velocity[i] = velo[:2]
for i in range(len(fg_lidar_boxes)): velo = velocity_3d[i] velo = velo @ np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T velocity_3d[i] = velo
names = [box.category.name for box in fg_lidar_boxes] names = np.array(names) gt_boxes_nuplan = np.concatenate([locs, dims, rots], axis=1) info["anns"] = dict( gt_boxes=gt_boxes_nuplan, gt_names=names, gt_velocity_3d=velocity_3d.reshape(-1, 3), instance_tokens=instance_tokens, track_tokens=track_tokens, ) scene_dict[scene_token].append(info) del map_api pkl_file_path = f"{args.out_dir}/{log_name}.pkl" os.makedirs(args.out_dir, exist_ok=True) with open(pkl_file_path, "wb") as f: pickle.dump(dict(scene_dict), f, protocol=pickle.HIGHEST_PROTOCOL)
def parse_args(): parser = argparse.ArgumentParser(description="Train a detector") parser.add_argument( "--thread-num", type=int, default=50, help="number of threads for multi-processing." )
# directory configurations. parser.add_argument("--nuplan-root-path", help="the path to nuplan root path.") parser.add_argument("--nuplan-db-path", help="the dir saving nuplan db.") parser.add_argument("--nuplan-sensor-path", help="the dir to nuplan sensor data.") parser.add_argument("--nuplan-map-version", help="nuplan mapping dataset version.") parser.add_argument("--nuplan-map-root", help="path to nuplan map data.") parser.add_argument("--out-dir", help="output path.")
# data configurations. parser.add_argument("--max-sweeps", type=int, default=10, help="number of point cloud sweeps.") parser.add_argument( "--sweep-interval", type=int, default=5, help="interval of point cloud sweeps." ) parser.add_argument( "--sample-interval", type=int, default=10, help="interval of key frame samples." ) parser.add_argument( "--scene-process-type", type=str, default="skip", help="process type when a scene is processed.", )
# TODO. parser.add_argument("--save-bev-images", action="store_true", help="XXX") parser.add_argument("--save_surround_images", action="store_true", help="XXX")
# split. parser.add_argument("--is-test", action="store_true", help="Dealing with Test set data.") parser.add_argument( "--filter-instance", action="store_true", help="Ignore instances in filtered_classes." ) parser.add_argument("--split", type=str, default="train", help="Train/Val/Test set.")
args = parser.parse_args() return args
if __name__ == "__main__": args = parse_args()
nuplan_root_path = args.nuplan_root_path nuplan_db_path = args.nuplan_db_path nuplan_sensor_path = args.nuplan_sensor_path nuplan_map_version = args.nuplan_map_version nuplan_map_root = args.nuplan_map_root out_dir = args.out_dir
nuplan_db_wrapper = NuPlanDBWrapper( data_root=nuplan_root_path, map_root=nuplan_map_root, db_files=nuplan_db_path, map_version=nuplan_map_version, ) nuplan_db_path = args.nuplan_db_path db_names_with_extension = [ f for f in listdir(nuplan_db_path) if isfile(join(nuplan_db_path, f)) ] db_names = [name[:-3] for name in db_names_with_extension] db_names.sort() print(db_names) db_names_split = np.split(np.array(db_names), args.thread_num)
manager = multiprocessing.Manager() # return_dict = manager.dict() threads = [] for x in range(args.thread_num): t = multiprocessing.Process( target=create_nuplan_info, name=str(x), args=(nuplan_db_wrapper, db_names_split[x], args), ) threads.append(t) for thr in threads: thr.start() for thr in threads: if thr.is_alive(): thr.join() # pkl_file_path = f"{args.out_dir}/{args.split}.pkl" # os.makedirs(args.out_dir, exist_ok=True) # with open(pkl_file_path, "wb") as f: # pickle.dump(dict(return_dict), f, protocol=pickle.HIGHEST_PROTOCOL)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178from re import Afrom typing import Dict, List, Tupleimport warnings
import numpy as npimport numpy.typing as npt
from shapely.geometry import Point
from nuplan.common.maps.abstract_map import AbstractMapfrom nuplan.common.actor_state.state_representation import StateSE2from nuplan.common.maps.maps_datatypes import SemanticMapLayerfrom nuplan.common.maps.abstract_map_objects import ( LaneGraphEdgeMapObject, RoadBlockGraphEdgeMapObject,)
from navsim.planning.simulation.planner.pdm_planner.utils.route_utils import ( route_roadblock_correction,)from navsim.planning.simulation.planner.pdm_planner.utils.graph_search.dijkstra import ( Dijkstra,)from navsim.planning.simulation.planner.pdm_planner.utils.pdm_path import PDMPathfrom navsim.planning.simulation.planner.pdm_planner.utils.pdm_geometry_utils import ( convert_absolute_to_relative_se2_array,)from navsim.planning.simulation.planner.pdm_planner.utils.pdm_enums import ( SE2Index,)
# shapely runtime warningwarnings.filterwarnings("ignore", category=RuntimeWarning)
def get_driving_command( ego_pose: StateSE2, map_api: AbstractMap, route_roadblock_ids: List[str], distance: float = 20, lateral_offset: float = 2,) -> npt.NDArray[np.int]: """ Creates the one-hot (left, forward, right)driving command for the ego vehicle :param ego_pose: (x, y, heading) object for global ego pose :param map_api: nuPlan's map interface :param route_roadblock_ids: roadblock ids of route :param distance: longitudinal distance to interpolate on th centerline, defaults to 10 :param lateral_offset: lateral offset for left/right threshold, to defaults to 2 :return: numpy one-hot array of driving_command """
driving_command = np.zeros((3,), dtype=int) # one-hot: (left, forward, right)
# If no route available, go straight if len(route_roadblock_ids) == 0: driving_command[1] = 1 return driving_command
# Apply route correction on route_roadblock_ids route_roadblock_dict, _ = get_route_dicts(map_api, route_roadblock_ids) corrected_route_roadblock_ids = route_roadblock_correction( ego_pose, map_api, route_roadblock_dict ) route_roadblock_dict, route_lane_dict = get_route_dicts(map_api, corrected_route_roadblock_ids)
# Find the nearest lane, graph search, and centerline extraction current_lane = get_current_lane(ego_pose, route_lane_dict) discrete_centerline = get_discrete_centerline( current_lane, route_roadblock_dict, route_lane_dict ) centerline = PDMPath(discrete_centerline)
# Interpolate target distance on centerline current_progress = centerline.project(Point(*ego_pose.array)) target_progress = current_progress + distance
current_pose_array, target_pose_array = centerline.interpolate( [current_progress, target_progress], as_array=True ) target_pose_array = convert_absolute_to_relative_se2_array( StateSE2(*current_pose_array), target_pose_array[None,...] )[0]
# Threshold for driving command if target_pose_array[SE2Index.Y] >= lateral_offset: driving_command[0] = 1 elif target_pose_array[SE2Index.Y] <= -lateral_offset: driving_command[2] = 1 else: driving_command[1] = 1
# delete some variables for memory management del route_roadblock_dict, route_lane_dict, _, centerline return driving_command
def get_route_dicts( map_api: AbstractMap, route_roadblock_ids: List[str]) -> Tuple[Dict[str, RoadBlockGraphEdgeMapObject], Dict[str, LaneGraphEdgeMapObject]]: """ Loads the roadblock and lane dicts :param map_api: nuPlan's map interface :param route_roadblock_ids: roadblock ids of route :return: tuple of roadblock and lane dicts """
# remove repeated ids while remaining order in list route_roadblock_ids = list(dict.fromkeys(route_roadblock_ids))
route_roadblock_dict: Dict[str, RoadBlockGraphEdgeMapObject] = {} route_lane_dict: Dict[str, LaneGraphEdgeMapObject] = {}
for id_ in route_roadblock_ids: block = map_api.get_map_object(id_, SemanticMapLayer.ROADBLOCK) block = block or map_api.get_map_object(id_, SemanticMapLayer.ROADBLOCK_CONNECTOR) route_roadblock_dict[block.id] = block for lane in block.interior_edges: route_lane_dict[lane.id] = lane
return route_roadblock_dict, route_lane_dict
def get_current_lane( ego_pose: StateSE2, route_lane_dict: Dict[str, LaneGraphEdgeMapObject]) -> LaneGraphEdgeMapObject: """ Find current lane, either if intersection with ego pose, or by distance. :param ego_pose: (x, y, heading) object for global ego pose :param route_lane_dict: Dictionary of roadblock ids and objects :return: Lane object """
closest_distance = np.inf starting_lane = None for edge in route_lane_dict.values(): if edge.contains_point(ego_pose): starting_lane = edge break
distance = edge.polygon.distance(Point(*ego_pose.array)) if distance < closest_distance: starting_lane = edge closest_distance = distance
return starting_lane
def get_discrete_centerline( current_lane: LaneGraphEdgeMapObject, route_roadblock_dict: Dict[str, RoadBlockGraphEdgeMapObject], route_lane_dict: Dict[str, LaneGraphEdgeMapObject], search_depth: int = 30,) -> List[StateSE2]: """ Given the current lane, apply graph search, and extract centerline. :param current_lane: Lane object closest to ego :param route_roadblock_dict: Dictionary of roadblock ids and objects :param route_lane_dict: Dictionary of lane ids and objects :param search_depth: max search depth of Dijkstra, defaults to 30 :return: List of (x, y, heading) objects """
roadblocks = list(route_roadblock_dict.values()) roadblock_ids = list(route_roadblock_dict.keys())
# find current roadblock index start_idx = np.argmax(np.array(roadblock_ids) == current_lane.get_roadblock_id()) roadblock_window = roadblocks[start_idx : start_idx + search_depth]
graph_search = Dijkstra(current_lane, list(route_lane_dict.keys())) route_plan, _ = graph_search.search(roadblock_window[-1])
centerline_discrete_path: List[StateSE2] = [] for lane in route_plan: centerline_discrete_path.extend(lane.baseline_path.discrete_path)
return centerline_discrete_path1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import numpy as np
class CanBus: """Wrapper class to convert lidar_can_bus to numpy array"""
def __init__(self, lidar_pc): self.x = lidar_pc.ego_pose.x self.y = lidar_pc.ego_pose.y self.z = lidar_pc.ego_pose.z
self.qw = lidar_pc.ego_pose.qw self.qx = lidar_pc.ego_pose.qx self.qy = lidar_pc.ego_pose.qy self.qz = lidar_pc.ego_pose.qz
self.acceleration_x = lidar_pc.ego_pose.acceleration_x self.acceleration_y = lidar_pc.ego_pose.acceleration_y self.acceleration_z = lidar_pc.ego_pose.acceleration_z
self.vx = lidar_pc.ego_pose.vx self.vy = lidar_pc.ego_pose.vy self.vz = lidar_pc.ego_pose.vz
self.angular_rate_x = lidar_pc.ego_pose.angular_rate_x self.angular_rate_y = lidar_pc.ego_pose.angular_rate_y self.angular_rate_z = lidar_pc.ego_pose.angular_rate_z
self.tensor = np.array( [ self.x, self.y, self.z, self.qw, self.qx, self.qy, self.qz, self.acceleration_x, self.acceleration_y, self.acceleration_z, self.vx, self.vy, self.vz, self.angular_rate_x, self.angular_rate_y, self.angular_rate_z, 0.0, 0.0, ] )1234567891011121314151617181920212223242526272829303132import numpy as npimport multiprocessing
def get_scenes_per_thread(scenes, thread_num): scenes = sorted(scenes) num_tasks = thread_num cur_id = int(multiprocessing.current_process().name)
num_scene = len(scenes) a = num_scene // num_tasks b = num_scene % num_tasks
if cur_id == 0: print("num_scene:", num_scene)
process_num = [] for id in range(num_tasks): if id >= b: process_num.append(a) else: process_num.append(a + 1) addsum = np.cumsum(process_num)
if cur_id == 0: start = 0 end = addsum[0] else: start = addsum[cur_id - 1] end = addsum[cur_id]
return scenes[start:end], start123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import osimport numpy as npfrom pyquaternion import Quaternion
from nuplan.database.nuplan_db_orm.lidar_pc import LidarPcfrom nuplan.database.nuplan_db_orm.lidar import Lidar
from navsim.common.extraction.helpers.canbus import CanBus
def obtain_sensor2top(lidar_token, log_db, l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, args): """Obtain the info with RT matric from other sensors to Top LiDAR.
Args: lidar_token (str): Sample data token corresponding to the specific sensor type. log_db: To obtain LiDAR of corresponding token. l2e_t (np.ndarray): Translation from lidar to ego in shape (1, 3). l2e_r_mat (np.ndarray): Rotation matrix from lidar to ego in shape (3, 3). e2g_t (np.ndarray): Translation from ego to global in shape (1, 3). e2g_r_mat (np.ndarray): Rotation matrix from ego to global in shape (3, 3).
Returns: sweep (dict): Sweep information after transformation. """ lidar_pc = log_db.session.query(LidarPc).filter(LidarPc.token == lidar_token).all() lidar_pc = lidar_pc[0] can_bus = CanBus(lidar_pc).tensor
lidar_sensor = log_db.session.query(Lidar).filter(Lidar.token == lidar_pc.lidar_token).all() lidar_sensor = lidar_sensor[0]
sweep = { "prev_sweep_token": lidar_pc.prev_token, "data_path": os.path.join(args.nuplan_sensor_path, lidar_pc.filename), "type": lidar_sensor.channel, "sample_data_token": lidar_pc.token, "sensor2ego_translation": lidar_sensor.translation_np, "sensor2ego_rotation": lidar_sensor.quaternion, "ego2global_translation": can_bus[:3], "ego2global_rotation": can_bus[3:7], "timestamp": lidar_pc.timestamp, }
l2e_r_s = sweep["sensor2ego_rotation"] l2e_t_s = sweep["sensor2ego_translation"] e2g_r_s = sweep["ego2global_rotation"] e2g_t_s = sweep["ego2global_translation"]
# obtain the RT from sensor to Top LiDAR # sweep->ego->global->ego'->lidar l2e_r_s_mat = Quaternion(l2e_r_s).rotation_matrix e2g_r_s_mat = Quaternion(e2g_r_s).rotation_matrix R = (l2e_r_s_mat.T @ e2g_r_s_mat.T) @ (np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T) T = (l2e_t_s @ e2g_r_s_mat.T + e2g_t_s) @ ( np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T ) T -= ( e2g_t @ (np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T) + l2e_t @ np.linalg.inv(l2e_r_mat).T ) sweep["sensor2lidar_rotation"] = R.T # points @ R.T + T sweep["sensor2lidar_translation"] = T return sweep123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import numpy as npfrom pyquaternion import Quaternion
from nuplan.database.utils.pointclouds.pointcloud import PointCloud
def _load_points(pc_file_name): pc = PointCloud.parse_from_file(pc_file_name).to_pcd_bin2().T return pc
def transform_pcs_to_images( pc, cam2lidar_rotation, cam2lidar_translation, cam_intrinsic, img_shape=None, eps=1e-3, return_depth=False,): """Transform point clouds from LiDAR coordinates to the camera coordinates.
Args: pc: a numpy array with shape [-1, 6] cam_infos: dict of camera information. Return: pc_cam: dict of 2d coordinates in corresponding camera space. """ pc_xyz = pc[:, :3]
lidar2cam_r = np.linalg.inv(cam2lidar_rotation) lidar2cam_t = cam2lidar_translation @ lidar2cam_r.T lidar2cam_rt = np.eye(4) lidar2cam_rt[:3, :3] = lidar2cam_r.T lidar2cam_rt[3, :3] = -lidar2cam_t
viewpad = np.eye(4) viewpad[: cam_intrinsic.shape[0], : cam_intrinsic.shape[1]] = cam_intrinsic lidar2img_rt = viewpad @ lidar2cam_rt.T
cur_pc_xyz = np.concatenate([pc_xyz, np.ones_like(pc_xyz)[:, :1]], -1) cur_pc_cam = lidar2img_rt @ cur_pc_xyz.T cur_pc_cam = cur_pc_cam.T
cur_pc_in_fov = cur_pc_cam[:, 2] > eps depth = cur_pc_cam[..., 2:3]
cur_pc_cam = cur_pc_cam[..., 0:2] / np.maximum( cur_pc_cam[..., 2:3], np.ones_like(cur_pc_cam[..., 2:3]) * eps ) if img_shape is not None: img_h, img_w = img_shape cur_pc_in_fov = ( cur_pc_in_fov & (cur_pc_cam[:, 0] < (img_w - 1)) & (cur_pc_cam[:, 0] > 0) & (cur_pc_cam[:, 1] < (img_h - 1)) & (cur_pc_cam[:, 1] > 0) ) if return_depth: cur_pc_cam = np.concatenate([cur_pc_cam, depth], axis=-1) return cur_pc_cam, cur_pc_in_fov
def transform_cam_to_img(pc_cam, cam_intrinsic, img_shape=None, eps=1e-3, return_depth=False): """Transform point clouds from LiDAR coordinates to the camera coordinates.
Args: pc: a numpy array with shape [-1, 6] cam_infos: dict of camera information. Return: pc_cam: dict of 2d coordinates in corresponding camera space. """ pc_cam = pc_cam[:, :3]
viewpad = np.eye(4) viewpad[: cam_intrinsic.shape[0], : cam_intrinsic.shape[1]] = cam_intrinsic
pc_img = np.concatenate([pc_cam, np.ones_like(pc_cam)[:, :1]], -1) pc_img = viewpad @ pc_img.T pc_img = pc_img.T
cur_pc_in_fov = pc_img[:, 2] > eps depth = pc_img[..., 2:3]
pc_img = pc_img[..., 0:2] / np.maximum(pc_img[..., 2:3], np.ones_like(pc_img[..., 2:3]) * eps) if img_shape is not None: img_h, img_w = img_shape cur_pc_in_fov = ( cur_pc_in_fov & (pc_img[:, 0] < (img_w - 1)) & (pc_img[:, 0] > 0) & (pc_img[:, 1] < (img_h - 1)) & (pc_img[:, 1] > 0) ) if return_depth: pc_img = np.concatenate([pc_img, depth], axis=-1) return pc_img, cur_pc_in_fov
def transform_nuplan_boxes_to_cam(box, cam2lidar_rotation, cam2lidar_translation): """Transform point clouds from LiDAR coordinates to the camera coordinates.
Args: box: a numpy array with shape [-1, 7] """ locs, dims, rots = box[:, :3], box[:, 3:6], box[:, 6:] dims_cams = dims[:, [0, 2, 1]] # l, w, h -> l, h, w
rots_cam = np.zeros_like(rots) for idx, rot in enumerate(rots): rot = Quaternion(axis=[0, 0, 1], radians=rot) rot = Quaternion(matrix=cam2lidar_rotation).inverse * rot rots_cam[idx] = -rot.yaw_pitch_roll[0]
lidar2cam_r = np.linalg.inv(cam2lidar_rotation) lidar2cam_t = cam2lidar_translation @ lidar2cam_r.T lidar2cam_rt = np.eye(4) lidar2cam_rt[:3, :3] = lidar2cam_r.T lidar2cam_rt[3, :3] = -lidar2cam_t
locs_cam = np.concatenate([locs, np.ones_like(locs)[:, :1]], -1) # -1, 4 locs_cam = lidar2cam_rt.T @ locs_cam.T locs_cam = locs_cam.T locs_cam = locs_cam[:, :-1] return np.concatenate([locs_cam, dims_cams, rots_cam], -1)
def transform_sweep_pc_to_lidar_top(sweep_pc, sensor2lidar_rotation, sensor2lidar_translation): sweep_xyz = sweep_pc[:, :3] sweep_xyz = np.concatenate([sweep_xyz, np.ones_like(sweep_xyz)[:, :1]], -1)
sensor2lidar_rt = np.eye(4) sensor2lidar_rt[:3, :3] = sensor2lidar_rotation.T sensor2lidar_rt[3, :3] = sensor2lidar_translation
sweep_xyz = sweep_xyz @ sensor2lidar_rt return sweep_xyz[:, :3]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import cv2import numpy as np
from navsim.common.extraction.helpers import transformation
def draw_pcs_on_images(pc, cam_infos, eps=1e-3): for cam_type, cam_info in cam_infos.items(): cur_img_path = cam_info["data_path"] cur_img = cv2.imread(cur_img_path) cur_img_h, cur_img_w = cur_img.shape[:2]
cur_pc_cam, cur_pc_in_fov = transformation.transform_pcs_to_images( pc, cam_info["sensor2lidar_rotation"], cam_info["sensor2lidar_translation"], cam_info["cam_intrinsic"], img_shape=(cur_img_h, cur_img_w), eps=eps, )
cur_pc_cam = cur_pc_cam[cur_pc_in_fov] for x, y in cur_pc_cam: cv2.circle(cur_img, (int(x), int(y)), 3, (255, 0, 0), 3) cv2.imwrite(f"dbg/{cam_type}.png", cur_img) return None
def draw_pcs(points, labels, color_map): """Draw point cloud from BEV
Args: points: A ndarray with shape as [-1, 3] labels: the label of each point with shape [-1] color_map: color of each label. """ import matplotlib.pyplot as plt
_, ax = plt.subplots(1, 1, figsize=(9, 9)) axes_limit = 40 # points: LiDAR points with shape [-1, 3] viz_points = points dists = np.sqrt(np.sum(viz_points[:, :2] ** 2, axis=1)) colors = np.minimum(1, dists / axes_limit / np.sqrt(2))
# prepare color_map points_color = color_map[labels] / 255.0 # -1, 3
point_scale = 0.2 scatter = ax.scatter(viz_points[:, 0], viz_points[:, 1], c=points_color, s=point_scale)
ax.plot(0, 0, "x", color="red") ax.set_xlim(-axes_limit, axes_limit) ax.set_ylim(-axes_limit, axes_limit) ax.axis("off") ax.set_aspect("equal") plt.savefig("dbg/dbg.png", bbox_inches="tight", pad_inches=0, dpi=200)
def draw_sweep_pcs(info, sweeps): cur_pc_file = info["lidar_path"] cur_pc = transformation._load_points(cur_pc_file) viz_pcs = [cur_pc[:, :3]] viz_labels = [np.ones_like(cur_pc)[:, 0] * 0.0]
for idx, sweep in enumerate(sweeps): sweep_pc_file = sweep["data_path"] sweep_pc = transformation._load_points(sweep_pc_file) sweep_pc = transformation.transform_sweep_pc_to_lidar_top( sweep_pc, sweep["sensor2lidar_rotation"], sweep["sensor2lidar_translation"] )
viz_pcs.append(sweep_pc) viz_labels.append(np.ones_like(sweep_pc)[:, 0] * (idx + 1))
viz_pcs = np.concatenate(viz_pcs, 0) viz_labels = np.concatenate(viz_labels, 0).astype(np.int) color_map = np.array( [ [245, 150, 100], [245, 230, 100], [250, 80, 100], [150, 60, 30], [255, 0, 0], [180, 30, 80], [255, 0, 0], [30, 30, 255], [200, 40, 255], [90, 30, 150], ] ) draw_pcs(viz_pcs, viz_labels, color_map) return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import numpy as np
from matplotlib.lines import Line2D
def rotz(t): """Rotation about the z-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
def draw_box_and_pc(points, boxes, names=None): import matplotlib.pyplot as plt
_, ax = plt.subplots(1, 1, figsize=(9, 9)) axes_limit = 40 # points: LiDAR points with shape [-1, 3] viz_points = points dists = np.sqrt(np.sum(viz_points[:, :2] ** 2, axis=1)) colors = np.minimum(1, dists / axes_limit / np.sqrt(2))
# prepare color_map points_color = np.array([[245, 150, 100]]).reshape(1, 3).repeat(points.shape[0], 0) points_color = points_color / 255.0 point_scale = 0.2 scatter = ax.scatter(viz_points[:, 0], viz_points[:, 1], c=points_color, s=point_scale)
ax.plot(0, 0, "x", color="red") ax.set_xlim(-axes_limit, axes_limit) ax.set_ylim(-axes_limit, axes_limit)
if names is None: draw_box_3d(boxes, ax) else: color_map = { "vehicle": "green", "bicycle": "blue", "pedestrian": "red", "traffic_cone": "darkred", "barrier": "peru", "czone_sign": "pink", "generic_object": "black", } colors = [color_map[name] for name in names] draw_box_3d(boxes, ax, linestyle="--", colors=colors)
ax.axis("off") ax.set_aspect("equal") plt.savefig("dbg/dbg.png", bbox_inches="tight", pad_inches=0, dpi=200)
def draw_box_3d(boxes, ax, linestyle="--", colors="cyan"): for o in range(len(boxes)): color = colors[o] obj = boxes[o] c_x, c_y, c_z, l, w, h, rz = obj[0], obj[1], obj[2], obj[3], obj[4], obj[5], obj[6]
R = rotz(rz)
# 3d bounding box corners x_corners = [l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2] y_corners = [w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2] z_corners = [h, h, h, h, 0, 0, 0, 0]
# rotate and translate 3d bounding box corners_3d = np.dot(R, np.vstack([x_corners, y_corners, z_corners]))
corners_3d[0, :] = corners_3d[0, :] + c_x corners_3d[1, :] = corners_3d[1, :] + c_y corners_3d[2, :] = corners_3d[2, :] + c_z
corners_3d_velo = np.transpose(corners_3d)
x1, x2, x3, x4 = corners_3d_velo[0:4, 0] y1, y2, y3, y4 = corners_3d_velo[0:4, 1]
polygon = np.zeros([5, 2], dtype=np.float32) polygon[0, 0] = x1 polygon[1, 0] = x2 polygon[2, 0] = x3 polygon[3, 0] = x4 polygon[4, 0] = x1
polygon[0, 1] = y1 polygon[1, 1] = y2 polygon[2, 1] = y3 polygon[3, 1] = y4 polygon[4, 1] = y1
line1 = [(x1, y1), (x2, y2)] line2 = [(x2, y2), (x3, y3)] line3 = [(x3, y3), (x4, y4)] line4 = [(x4, y4), (x1, y1)] (line1_xs, line1_ys) = zip(*line1) (line2_xs, line2_ys) = zip(*line2) (line3_xs, line3_ys) = zip(*line3) (line4_xs, line4_ys) = zip(*line4) ax.add_line(Line2D(line1_xs, line1_ys, linewidth=1, linestyle=linestyle, color=color)) ax.add_line(Line2D(line2_xs, line2_ys, linewidth=1, linestyle=linestyle, color=color)) ax.add_line(Line2D(line3_xs, line3_ys, linewidth=1, linestyle=linestyle, color=color)) ax.add_line(Line2D(line4_xs, line4_ys, linewidth=1, linestyle=linestyle, color=color))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Visualize 3D boxes in Image space.Align the setting in mmdetection3d: * Convert 3D box in nuplan coordinates to camera coordinates. * draw 3D box in camera."""
import cv2import numpy as npfrom navsim.common.extraction.helpers import transformation
def rotation_3d_in_axis(points, angles, axis=0): """Rotate points by angles according to axis.
Args: points (torch.Tensor): Points of shape (N, M, 3). angles (torch.Tensor): Vector of angles in shape (N,) axis (int, optional): The axis to be rotated. Defaults to 0.
Raises: ValueError: when the axis is not in range [0, 1, 2], it will \ raise value error.
Returns: torch.Tensor: Rotated points in shape (N, M, 3) """ rot_sin = np.sin(angles) rot_cos = np.cos(angles) ones = np.ones_like(rot_cos) zeros = np.zeros_like(rot_cos) if axis == 1: rot_mat_T = np.stack( [ np.stack([rot_cos, zeros, -rot_sin]), np.stack([zeros, ones, zeros]), np.stack([rot_sin, zeros, rot_cos]), ] ) elif axis == 2 or axis == -1: rot_mat_T = np.stack( [ np.stack([rot_cos, -rot_sin, zeros]), np.stack([rot_sin, rot_cos, zeros]), np.stack([zeros, zeros, ones]), ] ) elif axis == 0: rot_mat_T = np.stack( [ np.stack([zeros, rot_cos, -rot_sin]), np.stack([zeros, rot_sin, rot_cos]), np.stack([ones, zeros, zeros]), ] ) else: raise ValueError(f"axis should in range [0, 1, 2], got {axis}") return np.einsum("aij,jka->aik", points, rot_mat_T)
def plot_rect3d_on_img(img, num_rects, rect_corners, color=(0, 255, 0), thickness=1): """Plot the boundary lines of 3D rectangular on 2D images.
Args: img (numpy.array): The numpy array of image. num_rects (int): Number of 3D rectangulars. rect_corners (numpy.array): Coordinates of the corners of 3D rectangulars. Should be in the shape of [num_rect, 8, 2]. color (tuple[int]): The color to draw bboxes. Default: (0, 255, 0). thickness (int, optional): The thickness of bboxes. Default: 1. """ line_indices = ( (0, 1), (0, 3), (0, 4), (1, 2), (1, 5), (3, 2), (3, 7), (4, 5), (4, 7), (2, 6), (5, 6), (6, 7), ) for i in range(num_rects): corners = rect_corners[i].astype(np.int) for start, end in line_indices: cv2.line( img, (corners[start, 0], corners[start, 1]), (corners[end, 0], corners[end, 1]), color, thickness, cv2.LINE_AA, ) return img.astype(np.uint8)
def draw_boxes_nuplan_on_img(gt_boxes_nuplan, cam_infos, eps=1e-3): for cam_type, cam_info in cam_infos.items(): cur_img_path = cam_info["data_path"] cur_img = cv2.imread(cur_img_path) cur_img_h, cur_img_w = cur_img.shape[:2]
gt_boxes_cams = transformation.transform_nuplan_boxes_to_cam( gt_boxes_nuplan, cam_info["sensor2lidar_rotation"], cam_info["sensor2lidar_translation"], )
# Then convert gt_boxes_cams to corners. cur_locs, cur_dims, cur_rots = ( gt_boxes_cams[:, :3], gt_boxes_cams[:, 3:6], gt_boxes_cams[:, 6:], ) corners_norm = np.stack(np.unravel_index(np.arange(8), [2] * 3), axis=1) corners_norm = corners_norm[[0, 1, 3, 2, 4, 5, 7, 6]] corners_norm = corners_norm - np.array([0.5, 0.5, 0.5]) corners = cur_dims.reshape([-1, 1, 3]) * corners_norm.reshape([1, 8, 3]) corners = rotation_3d_in_axis(corners, cur_rots.squeeze(-1), axis=1) corners += cur_locs.reshape(-1, 1, 3)
# Then draw project corners to image. corners_img, corners_pc_in_fov = transformation.transform_cam_to_img( corners.reshape(-1, 3), cam_info["cam_intrinsic"], img_shape=(cur_img_h, cur_img_w) ) corners_img = corners_img.reshape(-1, 8, 2) corners_pc_in_fov = corners_pc_in_fov.reshape(-1, 8) valid_corners = corners_pc_in_fov.all(-1) corners_img = corners_img[valid_corners] cur_img = plot_rect3d_on_img(cur_img, len(corners_img), corners_img) cv2.imwrite(f"dbg/{cam_type}.png", cur_img) return None1234567891011121314151617181920212223242526272829303132# Scripts for processing nuplan data.# export PYTHONPATH=/cpfs01/user/yangzetong/code/workshop_codes/nuplan-devkit:${PYTHONPATH}
# export NUPLAN_DATA_ROOT="$HOME/nuplan/dataset/"# export NUPLAN_MAPS_ROOT="$HOME/nuplan/dataset/maps"# export NUPLAN_EXP_ROOT="$HOME/nuplan/exp"# export NUPLAN_DEVKIT_ROOT="$HOME/nuplan-devkit/"
# 0. Design nuPlan data path, and output data path.NUPLAN_PATH=$HOME/nuplan/dataset/nuplan-v1.1/NUPLAN_DB_PATH=$NUPLAN_PATH/splits/miniNUPLAN_SENSOR_PATH=${NUPLAN_PATH}/sensor_blobsNUPLAN_MAP_VERSION=nuplan-maps-v1.0NUPLAN_MAPS_ROOT=${HOME}/nuplan/dataset/maps
OUT_DIR=/home/daniel/navsim_logs/mini
# 1. TODO: Generate train/val pickle.python $NAVSIM_DEVKIT_ROOT/navsim/common/extraction/create_nuplan_data_with_vis.py \ --nuplan-root-path ${NUPLAN_PATH} \ --nuplan-db-path ${NUPLAN_DB_PATH} \ --nuplan-sensor-path ${NUPLAN_SENSOR_PATH} \ --nuplan-map-version ${NUPLAN_MAP_VERSION} \ --nuplan-map-root ${NUPLAN_MAPS_ROOT} \ --out-dir ${OUT_DIR} \ --split mini \ --thread-num 16
# 2. TODO: Extract Data Files from the generated pickle file.
# 3. TODO: Soft-link to some place similar to https://github.com/OpenDriveLab/OpenScene/blob/main/docs/dataset_stats.md#filesystem-hierarchyopenscene-v1.1/process_data/__init__.pyDeleted
openscene-v1.1/process_data/create_nuplan_data_with_vis.pyDeleted-446
openscene-v1.1/process_data/driving_command.pyDeleted-178
openscene-v1.1/process_data/helpers/__init__.pyDeleted
openscene-v1.1/process_data/helpers/canbus.pyDeleted-50
openscene-v1.1/process_data/helpers/multiprocess_helper.pyDeleted-32
openscene-v1.1/process_data/helpers/multisweep_helper.pyDeleted-66
openscene-v1.1/process_data/helpers/transformation.pyDeleted-138
openscene-v1.1/process_data/helpers/viz.pyDeleted-93
openscene-v1.1/process_data/helpers/viz_box.pyDeleted-102
openscene-v1.1/process_data/helpers/viz_box_2d.pyDeleted-135
openscene-v1.1/process_data/process.shDeleted-32