File size: 8,896 Bytes
1403119 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | 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")
|