industry_datasets / sfm_code /utilities_comb.py
FelixOtt's picture
Upload folder using huggingface_hub (part 6)
1403119 verified
Raw History Blame Contribute Delete
8.9 kB
import numpy as np
from tqdm import tqdm
def getError(posx, posq, actualx, actualq):
""" Calculates the position and rotation error """
q1 = actualq / np.linalg.norm(actualq)
q2 = posq / np.linalg.norm(posq)
d = abs(np.sum(np.multiply(q1, q2)))
theta = 2 * np.arccos(d) * 180 / np.pi
errx = np.linalg.norm(actualx - posx)
return errx, theta
# See https://answers.ros.org/question/388140/converting-a-rotation-matrix-to-quaternions-in-python/ ------------ #
def rotationMatrixToQuaternion(m):
""" Takes a rotation matrix and converts it to the corresponding quaternions """
t = np.matrix.trace(m)
q = np.asarray([0.0, 0.0, 0.0, 0.0], dtype=np.float64)
if t > 0:
t = np.sqrt(t + 1)
q[3] = 0.5 * t
t = 0.5/t
q[0] = (m[2, 1] - m[1, 2]) * t
q[1] = (m[0, 2] - m[2, 0]) * t
q[2] = (m[1, 0] - m[0, 1]) * t
else:
i = 0
if m[1, 1] > m[0, 0]:
i = 1
if m[2, 2] > m[i, i]:
i = 2
j = (i+1) % 3
k = (j+1) % 3
t = np.sqrt(m[i, i] - m[j, j] - m[k, k] + 1)
q[i] = 0.5 * t
t = 0.5 / t
q[3] = (m[k, j] - m[j, k]) * t
q[j] = (m[j, i] + m[i, j]) * t
q[k] = (m[k, i] + m[i, k]) * t
return q
# ------------------------------------------------------------------------------------------------------------------- #
# See https://automaticaddison.com/how-to-convert-a-quaternion-to-a-rotation-matrix/ ---------------------------- #
def quaternion_rotation_matrix(Q):
"""
Covert a quaternion into a full three-dimensional rotation matrix.
Input
:param Q: A 4 element array representing the quaternion (q0,q1,q2,q3)
Output
:return: A 3x3 element matrix representing the full 3D rotation matrix.
This rotation matrix converts a point in the local reference
frame to a point in the global reference frame.
"""
# Extract the values from Q
q0 = Q[0]
q1 = Q[1]
q2 = Q[2]
q3 = Q[3]
# First row of the rotation matrix
r00 = 2 * (q0 * q0 + q1 * q1) - 1
r01 = 2 * (q1 * q2 - q0 * q3)
r02 = 2 * (q1 * q3 + q0 * q2)
# Second row of the rotation matrix
r10 = 2 * (q1 * q2 + q0 * q3)
r11 = 2 * (q0 * q0 + q2 * q2) - 1
r12 = 2 * (q2 * q3 - q0 * q1)
# Third row of the rotation matrix
r20 = 2 * (q1 * q3 - q0 * q2)
r21 = 2 * (q2 * q3 + q0 * q1)
r22 = 2 * (q0 * q0 + q3 * q3) - 1
# 3x3 rotation matrix
rot_matrix = np.array([[r00, r01, r02],
[r10, r11, r12],
[r20, r21, r22]])
return rot_matrix
# ------------------------------------------------------------------------------------------------------------------- #
def get_training_data(dataset_abs, dataset_rel, backrot=False):
""" Reads in the predicted absolute/relative pos/rotation data as well as the ground truth """
print(dataset_abs, dataset_rel)
fnames_abs = []
lab_abs = []
pred_abs = []
# Read in the predicted absolute pos/rotation data and the ground truth
with open(dataset_abs, "r") as f:
for line in tqdm(f):
fname = int(line.split(",")[0].split("frame_")[1].split(".png")[0])
label = line.split("Label: ")[1].split(" Prediction")[0]
pred = line.split("Prediction: ")[1].split("\n")[0]
label_val = [float(x.split(": ")[1]) for x in label.split(", ")]
pred_val = [float(x.split(": ")[1]) for x in pred.split(", ")]
fnames_abs.append(fname)
lab_abs.append(label_val)
pred_abs.append(pred_val)
lab_abs = np.array(lab_abs)
pred_abs = np.array(pred_abs)
fnames_rel = []
lab_rel = []
pred_rel = []
# Read in the predicted relative pos/rotation data
with open(dataset_rel, "r") as f:
for line in tqdm(f):
fname = int(line.split(",")[0].split("frame_")[1].split(".npy")[0])
label = line.split("Label: ")[1].split(" Prediction")[0]
pred = line.split("Prediction: ")[1].split("\n")[0]
label_val = [float(x.split(": ")[1]) for x in label.split(", ")]
pred_val = [float(x.split(": ")[1]) for x in pred.split(", ")]
fnames_rel.append(fname)
lab_rel.append(label_val)
pred_rel.append(pred_val)
lab_rel = np.array(lab_rel)
pred_rel = np.array(pred_rel)
abs_frames = []
rel_frames = []
abs_counter = 0
rel_counter = 0
# compares the names of the absolute and relative frames and ensures, that they are matched correctly
while abs_counter < len(fnames_abs) and rel_counter < len(fnames_rel):
if fnames_abs[abs_counter] == fnames_rel[rel_counter]:
abs_frames.append(abs_counter)
rel_frames.append(rel_counter)
abs_counter += 1
rel_counter += 1
elif fnames_abs[abs_counter] > fnames_rel[rel_counter]:
rel_counter += 1
else:
abs_counter += 1
abs_frames = np.array(abs_frames)
rel_frames = np.array(rel_frames)
lab_abs = lab_abs[abs_frames]
pred_abs = pred_abs[abs_frames]
lab_rel = lab_rel[rel_frames]
pred_rel = pred_rel[rel_frames]
# if True, rotate the relative translation data from the perspective of the current image
# back to the world coordinate
if backrot:
for i in range(len(pred_rel)):
pred_rel[i][:3] = quaternion_rotation_matrix(pred_abs[i][-4:]).T @ pred_rel[i][:3]
# Remove outside of area values at the beginning ---- #
for j in range(2):
if pred_abs[0, j] < -1 or pred_abs[0, j] > 46:
pred_abs[0, j] = 0
if pred_abs[0, 2] < -1 or pred_abs[0, 2] > 8:
pred_abs[0, 2] = 0
# Replace any outside of area values with the values of the previous step ---- #
for i in range(len(pred_abs)):
for j in range(2):
if pred_abs[i, j] < -1 or pred_abs[i, j] > 46:
pred_abs[i, j] = pred_abs[i - 1, j]
if pred_abs[i, 2] < -1 or pred_abs[i, 2] > 8:
pred_abs[i, 2] = pred_abs[i - 1, 2]
# ---------------------------------- #
# --- Check Error --- #
# sanity check to see if the predicted values and ground truth values are aligned correctly
errxs = []
thetas = []
for i in range(len(lab_abs)):
posx = pred_abs[i][:3]
posq = pred_abs[i][3:]
actualx = lab_abs[i][:3]
actualq = lab_abs[i][3:]
errx, theta = getError(posx, posq, actualx, actualq)
errxs.append(errx)
thetas.append(theta)
print(np.median(errxs), np.median(thetas))
# ------------------- #
return pred_abs, pred_rel, lab_abs, lab_rel
def limited_gen_data(pred_abs, pred_rel, gt_abs, gt_rel, time_size):
""" Yields the input/ground truth data in batches of size 1. Can be used for evaluating the test dataset"""
indices = range(1, len(pred_abs) + 1)
for i in indices:
if i >= time_size:
input_data = np.concatenate([pred_abs[i - time_size: i], pred_rel[i - time_size: i]], axis=1)
else:
input_data = np.zeros((time_size, 14))
input_data[-i:] = np.concatenate([pred_abs[:i], pred_rel[:i]], axis=1)
output_data_x = gt_abs[i-1, :3]
output_data_q = gt_abs[i-1, 3:]
yield input_data, output_data_x, output_data_q
def gen_data(pred_abs, pred_rel, gt_abs, gt_rel, time_size):
""" Data generator that randomly shuffles the training data and yields them as single elements. """
while True:
indices = list(range(1, len(pred_abs) + 1))
np.random.shuffle(indices)
for i in indices:
if i >= time_size:
input_data = np.concatenate([pred_abs[i - time_size: i], pred_rel[i - time_size: i]], axis=1)
else:
input_data = np.zeros((time_size, 14))
input_data[-i:] = np.concatenate([pred_abs[:i], pred_rel[:i]], axis=1)
output_data_x = gt_abs[i-1, :3]
output_data_q = gt_abs[i-1, 3:]
yield input_data, output_data_x, output_data_q
def gen_data_batch(pred_abs, pred_rel, gt_abs, gt_rel, batchSize, time_size):
""" Uses the gen_data and yields batches of the size batchSize. """
data_gen = gen_data(pred_abs, pred_rel, gt_abs, gt_rel, time_size)
while True:
image_batch = []
pose_x_batch = []
pose_q_batch = []
for _ in range(batchSize):
image, pose_x, pose_q = next(data_gen)
image_batch.append(image)
pose_x_batch.append(pose_x)
pose_q_batch.append(pose_q)
yield np.asarray(image_batch).astype("float32"),\
np.concatenate([pose_x_batch, pose_q_batch], axis=1).astype("float32")