Datasets:
File size: 4,621 Bytes
985d351 | 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 | # Visualize ground-truth 6-DoF poses by projecting the spacecraft body axes
# onto dataset images.
#
# Requirements (see requirements.txt):
# numpy
# pandas
# matplotlib
# scipy
#
# Usage: python visualize_data.py [--split train|test] [--sequence RT500]
# [--seed 42] [--save out.png]
import argparse
import json
import os
import random
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.spatial.transform import Rotation
def project(q, r, K):
""" Projecting points to image frame to draw axes """
# reference points in satellite frame for drawing axes
p_axes = np.array([[0, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1]])
points_body = np.transpose(p_axes)
# transformation to camera frame
pose_mat = np.hstack((Rotation.from_quat(q).as_matrix(), np.expand_dims(r, 1)))
p_cam = np.dot(pose_mat, points_body)
# getting homogeneous coordinates
points_camera_frame = p_cam / p_cam[2]
# projection to image plane
points_image_plane = K.dot(points_camera_frame)
x, y = (points_image_plane[0], points_image_plane[1])
return x, y
def visualize(img, q, r, K, ax=None):
""" Visualizing image, with ground truth pose with axes projected to training image. """
if ax is None:
ax = plt.gca()
ax.imshow(img)
xa, ya = project(q, r, K)
scale = 150
c = np.array([[xa[0]],
[ya[0]]
])
p = np.array([[xa[1], xa[2], xa[3]],
[ya[1], ya[2], ya[3]]
])
v = p - c
v = scale * v / np.linalg.norm(v, axis=0)
ax.arrow(c[0, 0], c[1, 0], v[0, 0], v[1, 0], head_width=10, color='r')
ax.arrow(c[0, 0], c[1, 0], v[0, 1], v[1, 1], head_width=10, color='g')
ax.arrow(c[0, 0], c[1, 0], v[0, 2], v[1, 2], head_width=10, color='b')
return
def parse_args():
parser = argparse.ArgumentParser(description="Visualize ground-truth poses on dataset images.")
parser.add_argument('--data-dir', default=os.path.dirname(os.path.abspath(__file__)),
help="Dataset root containing K.txt, train.csv and train/ (default: script directory)")
parser.add_argument('--split', default='train', choices=['train', 'test'],
help="Dataset split to visualize (default: train)")
parser.add_argument('--sequence', default=None,
help="Trajectory ID to visualize, e.g. RT500 (default: random)")
parser.add_argument('--seed', type=int, default=None,
help="Random seed for reproducible image selection")
parser.add_argument('--save', default=None,
help="Save the figure to this path instead of showing it")
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
if args.seed is not None:
random.seed(args.seed)
split_dir = os.path.join(args.data_dir, args.split)
sequences = sorted(d for d in os.listdir(split_dir)
if os.path.isdir(os.path.join(split_dir, d)))
if not sequences:
raise SystemExit(f"No sequence folders found in {split_dir}")
traj_dir = args.sequence or random.choice(sequences)
image_path = os.path.join(split_dir, traj_dir)
if not os.path.isdir(image_path):
raise SystemExit(f"Sequence folder not found: {image_path}")
with open(os.path.join(args.data_dir, 'K.txt'), 'r') as file:
K = np.array(json.load(file))
data = pd.read_csv(os.path.join(args.data_dir, f"{args.split}.csv"))
files = sorted(f for f in os.listdir(image_path) if f.endswith('.jpg'))
rows = 3
cols = 3
picks = random.sample(files, min(rows * cols, len(files)))
fig, axes = plt.subplots(rows, cols, figsize=(20, 20))
for ax, image_id in zip(axes.flat, picks):
i_data = data.loc[data['filename'] == image_id]
if i_data.empty:
print(f"No annotation found for {image_id}, skipping")
continue
r = i_data[['Tx', 'Ty', 'Tz']].to_numpy(dtype=float).squeeze()
# Qx, Qy, Qz, Qw (scalar-last)
q = i_data[['Qx', 'Qy', 'Qz', 'Qw']].to_numpy(dtype=float).squeeze()
print(image_id, r, q)
image = plt.imread(os.path.join(image_path, image_id))
visualize(image, q, r, K, ax=ax)
for ax in axes.flat:
ax.axis('off')
fig.tight_layout()
if args.save:
fig.savefig(args.save, bbox_inches='tight')
print(f"Saved figure to {args.save}")
else:
plt.show()
|