Skip to content

Commit

Permalink
optimize file handling
Browse files Browse the repository at this point in the history
  • Loading branch information
anathonic authored and luigifreda committed Sep 23, 2024
1 parent 49927ff commit 60c3130
Showing 1 changed file with 9 additions and 17 deletions.
26 changes: 9 additions & 17 deletions trajectory_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,13 @@ def __init__(self, format_type: str, filename: str = None) -> None:
self.file = None

def open_file(self):
self._create_file()
self.file = open(self.filename, 'w')

def close_file(self):
if self.file:
self.file.close()
self.file = None

def _create_file(self):
if os.path.exists(self.filename):
os.remove(self.filename)
open(self.filename, 'w').close()

def write_trajectory(self, R, t, timestamp):
write_func = self.FORMAT_FUNCTIONS.get(self.format_type)
if write_func:
Expand All @@ -69,22 +64,19 @@ def write_trajectory(self, R, t, timestamp):
raise UnsupportedFormatException(self.format_type)

def _write_kitti_trajectory(self, R, t, timestamp) -> None:
with open(self.filename, 'a') as file:
file.write(f"{R[0, 0]:.9f} {R[0, 1]:.9f} {R[0, 2]:.9f} {t[0]:.9f} " \
self.file.write(f"{R[0, 0]:.9f} {R[0, 1]:.9f} {R[0, 2]:.9f} {t[0]:.9f} " \
f"{R[1, 0]:.9f} {R[1, 1]:.9f} {R[1, 2]:.9f} {t[1]:.9f} " \
f"{R[2, 0]:.9f} {R[2, 1]:.9f} {R[2, 2]:.9f} {t[2]:.9f}" + "\n")
f"{R[2, 0]:.9f} {R[2, 1]:.9f} {R[2, 2]:.9f} {t[2]:.9f}\n")

def _write_tum_trajectory(self, R, t, timestamp) -> None:
with open(self.filename, 'a') as file:
q = quaternion.from_rotation_matrix(R)
file.write(f"{timestamp:.6f} {t[0]:.9f} {t[1]:.9f} {t[2]:.9f} {q.x:.9f} {q.y:.9f} {q.z:.9f} {q.w:.9f}\n")
q = quaternion.from_rotation_matrix(R)
self.file.write(f"{timestamp:.6f} {t[0]:.9f} {t[1]:.9f} {t[2]:.9f} {q.x:.9f} {q.y:.9f} {q.z:.9f} {q.w:.9f}\n")

def _write_euroc_trajectory(self, R, t, timestamp) -> None:
with open(self.filename, 'a') as file:
t_str = ', '.join(map(str, t))
q = quaternion.from_rotation_matrix(R)
pose_line = f"{timestamp:.6f}, {t_str}, {q.x:.9f}, {q.y:.9f}, {q.z:.9f}, {q.w:.9f}"
file.write(pose_line + '\n')
t_str = ', '.join(map(str, t))
q = quaternion.from_rotation_matrix(R)
pose_line = f"{timestamp:.6f}, {t_str}, {q.x:.9f}, {q.y:.9f}, {q.z:.9f}, {q.w:.9f}"
self.file.write(pose_line + '\n')

@staticmethod
def generate_filename():
Expand Down

0 comments on commit 60c3130

Please sign in to comment.