def get_split_cam_configs_and_sync_data(argoverse_tracking_root_dir, split_dir, camera_list, source_views_indexes): """ Returns a dictionary giving the intrinsics/extrinsics/resolution of given cameras for each sequence. Parameters ---------- split_dir: pathlib Path argoverse-tracking split root dir, e.g.: path_to_data/argoverse-tracking/train1 camera_list: list list of camera for which to load the parameters. Must be in Argoverse's CAMERA_LIST Returns ------- dict A dictionary where the key is the log string and the value a dict corresponding to the cameras' parameters """ camera_configs = {} synchronized_data = [] db = SynchronizationDB(str(split_dir)) valid_logs = list(db.get_valid_logs()) # log_ids founds under split_dir split = split_dir.stem # e.g., train1 for log in valid_logs: camera_configs[log] = load_camera_config(str(split_dir / log / VEHICLE_CALIBRATION_INFO_FILENAME), camera_list) synchronized_data += get_synchronized_data(argoverse_tracking_root_dir, db, split, log, camera_list, source_views_indexes) return camera_configs, synchronized_data
def __init__( self, dataset_dir: str, experiment_prefix: str, use_existing_files: bool = True, log_id: str = None ) -> None: """We will cache the accumulated trajectories per city, per log, and per frame for the tracking benchmark. """ self.plot_lane_tangent_arrows = True self.plot_lidar_bev = True self.plot_lidar_in_img = False self.experiment_prefix = experiment_prefix self.dataset_dir = dataset_dir self.labels_dir = dataset_dir self.sdb = SynchronizationDB(self.dataset_dir) if log_id is None: tmp_dir = tempfile.gettempdir() per_city_traj_dict_fpath = f"{tmp_dir}/per_city_traj_dict_{experiment_prefix}.pkl" log_egopose_dict_fpath = f"{tmp_dir}/log_egopose_dict_{experiment_prefix}.pkl" log_timestamp_dict_fpath = f"{tmp_dir}/log_timestamp_dict_{experiment_prefix}.pkl" if not use_existing_files: # write the accumulate data dictionaries to disk PerFrameLabelAccumulator(dataset_dir, dataset_dir, experiment_prefix) self.per_city_traj_dict = load_pkl_dictionary(per_city_traj_dict_fpath) self.log_egopose_dict = load_pkl_dictionary(log_egopose_dict_fpath) self.log_timestamp_dict = load_pkl_dictionary(log_timestamp_dict_fpath) else: pfa = PerFrameLabelAccumulator(dataset_dir, dataset_dir, experiment_prefix, save=False) pfa.accumulate_per_log_data(log_id=log_id) self.per_city_traj_dict = pfa.per_city_traj_dict self.log_egopose_dict = pfa.log_egopose_dict self.log_timestamp_dict = pfa.log_timestamp_dict
def visualize_ground_lidar_pts(log_id: str, dataset_dir: str, experiment_prefix: str): """Process a log by drawing the LiDAR returns that are classified as belonging to the ground surface in a red to green colormap in the image. Args: log_id: The ID of a log dataset_dir: Where the dataset is stored experiment_prefix: Output prefix """ sdb = SynchronizationDB(dataset_dir, collect_single_log_id=log_id) city_info_fpath = f"{dataset_dir}/{log_id}/city_info.json" city_info = read_json_file(city_info_fpath) city_name = city_info["city_name"] avm = ArgoverseMap() ply_fpaths = sorted(glob.glob(f"{dataset_dir}/{log_id}/lidar/PC_*.ply")) for i, ply_fpath in enumerate(ply_fpaths): if i % 500 == 0: print(f"\tOn file {i} of {log_id}") lidar_timestamp_ns = ply_fpath.split("/")[-1].split(".")[0].split( "_")[-1] pose_fpath = f"{dataset_dir}/{log_id}/poses/city_SE3_egovehicle_{lidar_timestamp_ns}.json" if not Path(pose_fpath).exists(): continue pose_data = read_json_file(pose_fpath) rotation = np.array(pose_data["rotation"]) translation = np.array(pose_data["translation"]) city_to_egovehicle_se3 = SE3(rotation=quat2rotmat(rotation), translation=translation) lidar_pts = load_ply(ply_fpath) lidar_timestamp_ns = int(lidar_timestamp_ns) draw_ground_pts_in_image( sdb, lidar_pts, city_to_egovehicle_se3, avm, log_id, lidar_timestamp_ns, city_name, dataset_dir, experiment_prefix, ) for camera_name in CAMERA_LIST: if "stereo" in camera_name: fps = 5 else: fps = 10 cmd = f"ffmpeg -r {fps} -f image2 -i '{experiment_prefix}_ground_viz/{log_id}/{camera_name}/%*.jpg' {experiment_prefix}_ground_viz/{experiment_prefix}_{log_id}_{camera_name}_{fps}fps.mp4" print(cmd) run_command(cmd)
def __init__(self, data_dir: str, labels_dir: str) -> None: """ Args: data_dir: str, representing path to raw Argoverse data labels_dir: strrepresenting path to Argoverse data labels """ self.data_dir = data_dir self.labels_dir = labels_dir self.sdb = SynchronizationDB(data_dir)
def __init__(self, data_dir: str, labels_dir: str) -> None: """ Args: data_dir: str, representing path to raw Argoverse data labels_dir: str representing path to Argoverse data labels (e.g. labels or estimated detections/tracks) """ self.data_dir = data_dir self.labels_dir = labels_dir self.sdb = SynchronizationDB(data_dir)
def __init__(self, root_dir: str) -> None: # initialize class member self.CAMERA_LIST = CAMERA_LIST self._log_list: Optional[List[str]] = [None] self._image_list: Optional[Dict[str, Dict[str, List[str]]]] = None self._image_list_sync: Optional[Dict[str, Dict[str, List[np.ndarray]]]] = None self._lidar_list: Optional[Dict[str, List[str]]] = None self._image_timestamp_list: Optional[Dict[str, Dict[str, List[int]]]] = None self._timestamp_image_dict: Optional[Dict[str, Dict[str, Dict[int, str]]]] = None self._image_timestamp_list_sync: Optional[Dict[str, Dict[str, List[int]]]] = None self._lidar_timestamp_list: Optional[Dict[str, List[int]]] = None self._timestamp_lidar_dict: Optional[Dict[str, Dict[int, str]]] = None self._label_list: Optional[Dict[str, List[str]]] = None self._calib: Optional[Dict[str, Dict[ str, Calibration]]] = None # { log_name: { camera_name: Calibration } } self._city_name = None self.counter: int = 0 self.image_count: int = 0 self.lidar_count: int = 0 self.root_dir: str = root_dir self.current_log = self.log_list[self.counter] assert self.image_list is not None assert self.lidar_list is not None assert self.label_list is not None # load calibration file self.calib_filename: str = os.path.join( self.root_dir, self.current_log, "vehicle_calibration_info.json") # lidar @10hz, ring camera @30hz, stereo camera @5hz self.num_lidar_frame: int = len(self.lidar_timestamp_list) self.num_ring_camera_frame: int = len( self.image_timestamp_list[RING_CAMERA_LIST[0]]) self.num_stereo_camera_frame: int = len( self.image_timestamp_list[STEREO_CAMERA_LIST[0]]) self.sync: SynchronizationDB = SynchronizationDB(root_dir) assert self.image_list_sync is not None assert self.calib is not None
def __init__(self, dataset_dir: str, experiment_prefix: str, tf_record_prefix: str) -> None: """We will cache the accumulated trajectories per city, per log, and per frame for the tracking benchmark. """ self.experiment_prefix = experiment_prefix self.tf_record_prefix = tf_record_prefix self.dataset_dir = dataset_dir self.labels_dir = dataset_dir self.sdb = SynchronizationDB(self.dataset_dir) self.per_city_traj_dict = None self.log_egopose_dict = None self.log_timestamp_dict = None self.timestamps = None
def main(argo_tracking_root_dir, output_dir, cameras, acc_sweeps, ip_basic): print('Preprocessing data....') print("INPUT DIR: ", argo_tracking_root_dir) print("OUTPUT DIR: ", output_dir) if cameras is None: cameras = CAMERA_LIST else: cameras = validate_camera_option(cameras) print(cameras) argo_tracking_root_dir = Path(argo_tracking_root_dir).expanduser() output_dir = Path(output_dir).expanduser() split_namedirs = ["train1", "train2", "train3", "train4", "test", "val"] split_dirs = [ argo_tracking_root_dir / split_namedir for split_namedir in split_namedirs ] for split_dir in split_dirs: db = SynchronizationDB(str(split_dir)) log_dirs = sorted(list(split_dir.iterdir())) for log_dir in log_dirs: lidar_dir = log_dir / "lidar" lidar_filepaths = [f for f in sorted(list(lidar_dir.iterdir()))] total = len(lidar_filepaths) calib_filepath = str(log_dir / "vehicle_calibration_info.json") output_base_path = output_dir / split_dir.stem / log_dir.stem with open(calib_filepath, "r") as f: calib_data = json.load(f) args = (output_base_path, calib_data, cameras, db, acc_sweeps, ip_basic) with tqdm(lidar_filepaths, desc=f"{split_dir.stem} | log {log_dir.stem} ", total=total) as progress: for lidar_filepath in progress: project_and_save(lidar_filepath, *args) print('Preprocessing of LiDAR data Finished.')
def __init__( self, dataset_dir: str, labels_dir: str, experiment_prefix: str, bboxes_3d: bool = False, save: bool = True, ) -> None: """Initialize PerFrameLabelAccumulator object for use with tracking benchmark data. Args: dataset_dir (str): Dataset directory. labels_dir (str): Labels directory. experiment_prefix (str): Prefix for experimint to use. bboxes_3d (bool, optional): to use 3d bounding boxes (True) or 2d bounding boxes (False). """ self.bboxes_3d = bboxes_3d self.dataset_dir = dataset_dir self.labels_dir = labels_dir tmp_dir = tempfile.gettempdir() per_city_traj_dict_fpath = f"{tmp_dir}/per_city_traj_dict_{experiment_prefix}.pkl" log_egopose_dict_fpath = f"{tmp_dir}/log_egopose_dict_{experiment_prefix}.pkl" log_timestamp_dict_fpath = f"{tmp_dir}/log_timestamp_dict_{experiment_prefix}.pkl" # coordinate system is the map world frame self.per_city_traj_dict: Dict[str, List[Tuple[np.ndarray, str]]] = { "MIA": [], "PIT": [], } # all the trajectories for these 2 cities self.log_egopose_dict: Dict[str, Dict[int, Dict[str, np.ndarray]]] = {} self.log_timestamp_dict: Dict[str, Dict[int, List[FrameRecord]]] = {} self.sdb = SynchronizationDB(self.dataset_dir) if save: self.accumulate_per_log_data() save_pkl_dictionary(per_city_traj_dict_fpath, self.per_city_traj_dict) save_pkl_dictionary(log_egopose_dict_fpath, self.log_egopose_dict) save_pkl_dictionary(log_timestamp_dict_fpath, self.log_timestamp_dict)
def generate_vehicle_bev(dataset_dir="", log_id="", output_dir=""): argoverse_loader = ArgoverseTrackingLoader(dataset_dir) argoverse_data = argoverse_loader.get(log_id) camera = argoverse_loader.CAMERA_LIST[7] calib = argoverse_data.get_calibration(camera) sdb = SynchronizationDB(dataset_dir, collect_single_log_id=log_id) calib_path = f"{dataset_dir}/{log_id}/vehicle_calibration_info.json" calib_data = read_json_file(calib_path) ind = 0 for i in range(9): if calib_data['camera_data_'][i]['key'] == \ 'image_raw_stereo_front_left': ind = i break rotation = np.array(calib_data['camera_data_'][ind]['value'] ['vehicle_SE3_camera_']['rotation']['coefficients']) translation = np.array(calib_data['camera_data_'][ind]['value'] ['vehicle_SE3_camera_']['translation']) egovehicle_SE3_cam = SE3(rotation=quat2rotmat(rotation), translation=translation) if not os.path.exists(os.path.join(output_dir, log_id, "car_bev_gt")): os.makedirs(os.path.join(output_dir, log_id, "car_bev_gt")) lidar_dir = os.path.join(dataset_dir, log_id, "lidar") ply_list = os.listdir(lidar_dir) pfa = PerFrameLabelAccumulator(dataset_dir, dataset_dir, "argoverse_bev_viz", save=False, bboxes_3d=True) pfa.accumulate_per_log_data(log_id) log_timestamp_dict = pfa.log_timestamp_dict for i, ply_name in enumerate(ply_list): lidar_timestamp = ply_name.split('.')[0].split('_')[1] lidar_timestamp = int(lidar_timestamp) cam_timestamp = sdb.get_closest_cam_channel_timestamp( lidar_timestamp, "stereo_front_left", str(log_id)) image_path = os.path.join( output_dir, str(log_id), "car_bev_gt", "stereo_front_left_" + str(cam_timestamp) + ".jpg") objects = log_timestamp_dict[log_id][lidar_timestamp] top_view = np.zeros((256, 256)) all_occluded = True for frame_rec in objects: if frame_rec.occlusion_val != IS_OCCLUDED_FLAG: all_occluded = False if not all_occluded: for i, frame_rec in enumerate(objects): bbox_ego_frame = frame_rec.bbox_ego_frame uv = calib.project_ego_to_image(bbox_ego_frame).T idx_ = np.all( np.logical_and( np.logical_and( np.logical_and(uv[0, :] >= 0.0, uv[0, :] < size[1] - 1.0), np.logical_and(uv[1, :] >= 0.0, uv[1, :] < size[0] - 1.0)), uv[2, :] > 0)) if not idx_: continue bbox_cam_fr = egovehicle_SE3_cam.inverse().\ transform_point_cloud(bbox_ego_frame) X = bbox_cam_fr[:, 0] Z = bbox_cam_fr[:, 2] if (frame_rec.occlusion_val != IS_OCCLUDED_FLAG and frame_rec.obj_class_str == "VEHICLE"): y_img = (-Z / res).astype(np.int32) x_img = (X / res).astype(np.int32) x_img -= int(np.floor(-20 / res)) y_img += int(np.floor(40 / res)) box = np.array([x_img[2], y_img[2]]) box = np.vstack((box, [x_img[6], y_img[6]])) box = np.vstack((box, [x_img[7], y_img[7]])) box = np.vstack((box, [x_img[3], y_img[3]])) cv2.drawContours(top_view, [box], 0, 255, -1) cv2.imwrite(image_path, top_view)
def generate_road_bev(dataset_dir="", log_id="", output_dir=""): argoverse_loader = ArgoverseTrackingLoader(dataset_dir) argoverse_data = argoverse_loader.get(log_id) city_name = argoverse_data.city_name avm = ArgoverseMap() sdb = SynchronizationDB(dataset_dir, collect_single_log_id=log_id) try: path = os.path.join(output_dir, log_id, 'road_gt') command = "rm -r " + path os.system(command) except BaseException: pass try: os.makedirs(os.path.join(output_dir, log_id, 'road_gt')) except BaseException: pass ply_fpath = os.path.join(dataset_dir, log_id, 'lidar') ply_locs = [] for idx, ply_name in enumerate(os.listdir(ply_fpath)): ply_loc = np.array([idx, int(ply_name.split('.')[0].split('_')[-1])]) ply_locs.append(ply_loc) ply_locs = np.array(ply_locs) lidar_timestamps = sorted(ply_locs[:, 1]) calib_path = f"{dataset_dir}/{log_id}/vehicle_calibration_info.json" calib_data = read_json_file(calib_path) ind = 0 for i in range(9): if calib_data['camera_data_'][i]['key'] ==\ 'image_raw_stereo_front_left': ind = i break rotation = np.array(calib_data['camera_data_'][ind]['value'] ['vehicle_SE3_camera_']['rotation']['coefficients']) translation = np.array(calib_data['camera_data_'][ind]['value'] ['vehicle_SE3_camera_']['translation']) egovehicle_SE3_cam = SE3(rotation=quat2rotmat(rotation), translation=translation) for idx in range(len(lidar_timestamps)): lidar_timestamp = lidar_timestamps[idx] cam_timestamp = sdb.get_closest_cam_channel_timestamp( lidar_timestamp, "stereo_front_left", str(log_id)) occupancy_map = np.zeros((256, 256)) pose_fpath = os.path.join( dataset_dir, log_id, "poses", "city_SE3_egovehicle_" + str(lidar_timestamp) + ".json") if not Path(pose_fpath).exists(): continue pose_data = read_json_file(pose_fpath) rotation = np.array(pose_data["rotation"]) translation = np.array(pose_data["translation"]) xcenter = translation[0] ycenter = translation[1] city_to_egovehicle_se3 = SE3(rotation=quat2rotmat(rotation), translation=translation) ego_car_nearby_lane_ids = avm.get_lane_ids_in_xy_bbox( xcenter, ycenter, city_name, 50.0) occupancy_map = get_lane_bev(ego_car_nearby_lane_ids, avm, city_name, city_to_egovehicle_se3, egovehicle_SE3_cam, occupancy_map, res, 255) output_loc = os.path.join( output_dir, log_id, 'road_gt', 'stereo_front_left_' + str(cam_timestamp) + '.png') cv2.imwrite(output_loc, occupancy_map)