File size: 13,336 Bytes
e5f58d9 de8ba40 e5f58d9 | 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | #!/usr/bin/env bash
#
# Build and verify four-view images for dataset trajectories.
#
# For each trajectory CSV, this script runs run.sh in dataset playback mode.
# The Gazebo plugin stops at every waypoint and captures front/down/left/right.
# After every run, this script verifies that all images referenced by the CSV
# exist and rejects near-uniform frames or low-texture gray render patches.
# Failed trajectories are restored and retried.
#
# Usage:
# ./datasets_construct.sh
# ./datasets_construct.sh gui
# ./datasets_construct.sh datasets/world_v3
# DATASET_ROOT=./datasets/world_v3 ./datasets_construct.sh
set -euo pipefail
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODE_ARGS=()
if [[ "${1:-}" == "gui" ]]; then
MODE_ARGS+=(gui)
shift
fi
ROOTS=()
if [[ $# -gt 0 ]]; then
for root in "$@"; do
ROOTS+=("${root}")
done
elif [[ -n "${DATASET_ROOT:-}" ]]; then
ROOTS+=("${DATASET_ROOT}")
else
ROOTS+=("${PROJECT_DIR}/datasets/world_v3")
fi
MAX_ATTEMPTS="${DATASET_CAPTURE_MAX_ATTEMPTS:-5}"
CAPTURE_LIMIT="${DATASET_CAPTURE_LIMIT:-}"
VALIDATOR_PY="$(mktemp /tmp/simple_drone_validate.XXXXXX.py)"
ORIGINAL_CSV=""
CURRENT_TRAJ=""
cleanup() {
rm -f "${VALIDATOR_PY}"
if [[ -n "${ORIGINAL_CSV}" && -f "${ORIGINAL_CSV}" && -n "${CURRENT_TRAJ}" ]]; then
cp "${ORIGINAL_CSV}" "${CURRENT_TRAJ}" 2>/dev/null || true
fi
if [[ -n "${ORIGINAL_CSV}" && -f "${ORIGINAL_CSV}" ]]; then
rm -f "${ORIGINAL_CSV}"
fi
}
trap cleanup EXIT
cat > "${VALIDATOR_PY}" <<'PY'
import csv
import os
import shutil
import sys
from pathlib import Path
try:
import numpy as np
from PIL import Image
except Exception as exc:
print(f"validator dependency error: {exc}", file=sys.stderr)
raise SystemExit(2)
VIEWS = ("front", "down", "left", "right")
GRAY_DELTA = int(os.environ.get("DATASET_GRAY_DELTA", "3"))
GRAY_MIN = int(os.environ.get("DATASET_GRAY_MIN", "120"))
GRAY_MAX = int(os.environ.get("DATASET_GRAY_MAX", "136"))
GRAY_MAX_RATIO = min(0.99, max(0.0, float(os.environ.get("DATASET_GRAY_MAX_RATIO", "0.12"))))
GRAY_TILE_RATIO = min(0.99, max(0.0, float(os.environ.get("DATASET_GRAY_TILE_RATIO", "0.90"))))
GRAY_SCANLINE_RATIO = min(0.99, max(0.0, float(os.environ.get("DATASET_GRAY_SCANLINE_RATIO", "0.95"))))
MIN_LUMA_STD = float(os.environ.get("DATASET_MIN_LUMA_STD", "4.0"))
MIN_RGB_RANGE = int(os.environ.get("DATASET_MIN_RGB_RANGE", "12"))
def rows_and_required(csv_path: Path):
with csv_path.open(newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
required = {
"capture_frame",
"captured_yaw_rad",
"captured_yaw_deg",
"front_image",
"down_image",
"left_image",
"right_image",
}
if not reader.fieldnames or not required.issubset(reader.fieldnames):
return None, "missing capture/image columns"
rows = list(reader)
if not rows:
return None, "empty trajectory CSV"
return rows, ""
def validate_image(path: Path):
try:
with Image.open(path) as image:
rgb = image.convert("RGB")
arr = np.asarray(rgb, dtype=np.uint8)
except Exception as exc:
return False, f"cannot open image: {path} ({exc})"
if arr.ndim != 3 or arr.shape[0] < 8 or arr.shape[1] < 8:
return False, f"bad image dimensions: {path}"
channel_min = arr.min(axis=2).astype(np.int16)
channel_max = arr.max(axis=2).astype(np.int16)
luma = arr.mean(axis=2)
rgb_range = int(arr.max()) - int(arr.min())
luma_std = float(luma.std())
if rgb_range < MIN_RGB_RANGE:
return False, f"all/near-gray image: {path} range={rgb_range} luma_std={luma_std:.3f}"
neutral = (channel_max - channel_min) <= GRAY_DELTA
medium_gray = (luma >= GRAY_MIN) & (luma <= GRAY_MAX)
gray_mask = neutral & medium_gray
gray_ratio = float(gray_mask.mean())
if gray_ratio > GRAY_MAX_RATIO:
return False, f"global gray ratio too high: {path} ratio={gray_ratio:.4f}"
buffer_mask = np.all(arr == 128, axis=2)
row_ratios = buffer_mask.mean(axis=1)
column_ratios = buffer_mask.mean(axis=0)
if float(row_ratios.max()) > GRAY_SCANLINE_RATIO:
row = int(row_ratios.argmax())
return False, (
f"gray render-buffer row: {path} row={row} "
f"ratio={float(row_ratios[row]):.4f}"
)
if float(column_ratios.max()) > GRAY_SCANLINE_RATIO:
column = int(column_ratios.argmax())
return False, (
f"gray render-buffer column: {path} column={column} "
f"ratio={float(column_ratios[column]):.4f}"
)
height, width = gray_mask.shape
tile_h = max(1, height // 8)
tile_w = max(1, width // 8)
for y0 in range(0, height, tile_h):
for x0 in range(0, width, tile_w):
tile = gray_mask[y0:min(y0 + tile_h, height), x0:min(x0 + tile_w, width)]
tile_ratio = float(tile.mean()) if tile.size else 0.0
tile_luma = luma[y0:min(y0 + tile_h, height), x0:min(x0 + tile_w, width)]
tile_rgb = arr[y0:min(y0 + tile_h, height), x0:min(x0 + tile_w, width), :]
tile_std = float(tile_luma.std()) if tile_luma.size else 0.0
tile_range = int(tile_rgb.max()) - int(tile_rgb.min()) if tile_rgb.size else 0
if tile_ratio > GRAY_TILE_RATIO and tile_std < MIN_LUMA_STD and tile_range < MIN_RGB_RANGE:
return False, (
f"large low-texture gray tile: {path} "
f"tile_ratio={tile_ratio:.4f} range={tile_range} luma_std={tile_std:.3f}"
)
return True, ""
def validate(dataset_root: Path, csv_path: Path):
rows, reason = rows_and_required(csv_path)
if rows is None:
return False, reason
image_root = dataset_root / "images" / csv_path.stem
for index, row in enumerate(rows):
if not row.get("capture_frame") or not row.get("captured_yaw_rad") or not row.get("captured_yaw_deg"):
return False, f"row {index} missing capture metadata"
for view in VIEWS:
image_name = row.get(f"{view}_image", "")
if not image_name:
return False, f"row {index} missing {view}_image"
image_path = image_root / f"images_{view}" / image_name
if not image_path.is_file():
return False, f"missing image: {image_path}"
ok, detail = validate_image(image_path)
if not ok:
return False, detail
return True, "ok"
def quick_complete(dataset_root: Path, csv_path: Path):
rows, reason = rows_and_required(csv_path)
if rows is None:
return False, reason
image_root = dataset_root / "images" / csv_path.stem
for index, row in enumerate(rows):
if not row.get("capture_frame") or not row.get("captured_yaw_rad") or not row.get("captured_yaw_deg"):
return False, f"row {index} missing capture metadata"
for view in VIEWS:
image_name = row.get(f"{view}_image", "")
if not image_name:
return False, f"row {index} missing {view}_image"
image_path = image_root / f"images_{view}" / image_name
if not image_path.is_file():
return False, f"missing image: {image_path}"
return True, "ok"
def clean(dataset_root: Path, csv_path: Path):
image_root = dataset_root / "images" / csv_path.stem
if image_root.exists():
shutil.rmtree(image_root)
def main():
if len(sys.argv) != 4:
raise SystemExit("usage: validator.py validate|clean DATASET_ROOT CSV")
command = sys.argv[1]
dataset_root = Path(sys.argv[2])
csv_path = Path(sys.argv[3])
if command == "validate":
ok, message = validate(dataset_root, csv_path)
print(message)
raise SystemExit(0 if ok else 1)
if command == "quick":
ok, message = quick_complete(dataset_root, csv_path)
print(message)
raise SystemExit(0 if ok else 1)
if command == "clean":
clean(dataset_root, csv_path)
raise SystemExit(0)
raise SystemExit(f"unknown command: {command}")
if __name__ == "__main__":
main()
PY
trajectory_complete() {
local dataset_root="$1"
local csv_path="$2"
if [[ "${DATASET_REVALIDATE_EXISTING:-0}" != "0" ]]; then
python3 "${VALIDATOR_PY}" validate "${dataset_root}" "${csv_path}" >/dev/null 2>&1
else
python3 "${VALIDATOR_PY}" quick "${dataset_root}" "${csv_path}" >/dev/null 2>&1
fi
}
validate_or_explain() {
local dataset_root="$1"
local csv_path="$2"
python3 "${VALIDATOR_PY}" validate "${dataset_root}" "${csv_path}"
}
clean_outputs() {
local dataset_root="$1"
local csv_path="$2"
python3 "${VALIDATOR_PY}" clean "${dataset_root}" "${csv_path}"
}
for root in "${ROOTS[@]}"; do
DATASET_ROOT_ABS="$(cd "${root}" && pwd)"
TRAJECTORY_DIR="${DATASET_ROOT_ABS}/trajectory"
if [[ ! -d "${TRAJECTORY_DIR}" ]]; then
echo "[datasets_construct] trajectory directory not found: ${TRAJECTORY_DIR}" >&2
exit 1
fi
mapfile -t ALL_TRAJECTORIES < <(find "${TRAJECTORY_DIR}" -maxdepth 1 -type f -name '*.csv' | sort)
if [[ -n "${DATASET_CAPTURE_TRAJECTORY:-}" ]]; then
REQUESTED_TRAJECTORY="${DATASET_CAPTURE_TRAJECTORY}"
if [[ "${REQUESTED_TRAJECTORY}" != /* ]]; then
REQUESTED_TRAJECTORY="${TRAJECTORY_DIR}/${REQUESTED_TRAJECTORY}"
fi
if [[ ! -f "${REQUESTED_TRAJECTORY}" ]]; then
echo "[datasets_construct] requested trajectory not found: ${REQUESTED_TRAJECTORY}" >&2
exit 1
fi
ALL_TRAJECTORIES=("$(cd "$(dirname "${REQUESTED_TRAJECTORY}")" && pwd)/$(basename "${REQUESTED_TRAJECTORY}")")
fi
if [[ "${#ALL_TRAJECTORIES[@]}" -eq 0 ]]; then
echo "[datasets_construct] no trajectory CSV files found in ${TRAJECTORY_DIR}" >&2
exit 1
fi
echo "[datasets_construct] dataset -> ${DATASET_ROOT_ABS}"
echo "[datasets_construct] total trajectories -> ${#ALL_TRAJECTORIES[@]}"
echo "[datasets_construct] scanning existing captures..."
TRAJECTORIES=()
scanned=0
for traj in "${ALL_TRAJECTORIES[@]}"; do
scanned=$((scanned + 1))
if (( scanned % 100 == 0 )); then
echo "[datasets_construct] scanned ${scanned}/${#ALL_TRAJECTORIES[@]}"
fi
if trajectory_complete "${DATASET_ROOT_ABS}" "${traj}"; then
echo "[datasets_construct] skip verified $(basename "${traj}")"
else
TRAJECTORIES+=("${traj}")
if [[ -n "${CAPTURE_LIMIT}" && "${#TRAJECTORIES[@]}" -ge "${CAPTURE_LIMIT}" ]]; then
echo "[datasets_construct] reached DATASET_CAPTURE_LIMIT=${CAPTURE_LIMIT}; stopping scan early"
break
fi
fi
done
echo "[datasets_construct] remaining trajectories -> ${#TRAJECTORIES[@]}"
echo "[datasets_construct] max attempts -> ${MAX_ATTEMPTS}"
if [[ "${#TRAJECTORIES[@]}" -eq 0 ]]; then
echo "[datasets_construct] complete: all trajectories are already verified"
continue
fi
skipped_timeouts=0
for i in "${!TRAJECTORIES[@]}"; do
traj="${TRAJECTORIES[$i]}"
CURRENT_TRAJ="${traj}"
idx=$((i + 1))
echo "[datasets_construct] ${idx}/${#TRAJECTORIES[@]} running $(basename "${traj}")"
ORIGINAL_CSV="$(mktemp /tmp/simple_drone_csv.XXXXXX)"
cp "${traj}" "${ORIGINAL_CSV}"
attempt=1
timed_out=0
while [[ "${attempt}" -le "${MAX_ATTEMPTS}" ]]; do
echo "[datasets_construct] attempt ${attempt}/${MAX_ATTEMPTS} $(basename "${traj}")"
cp "${ORIGINAL_CSV}" "${traj}"
clean_outputs "${DATASET_ROOT_ABS}" "${traj}"
if DATASET_ROOT="${DATASET_ROOT_ABS}" SIMPLE_DRONE_QUIT_ON_FINISH=1 \
SIMPLE_DRONE_RENDER_BACKEND="${SIMPLE_DRONE_RENDER_BACKEND:-system}" \
SIMPLE_DRONE_SINGLE_CAMERA_SWEEP="${SIMPLE_DRONE_SINGLE_CAMERA_SWEEP:-0}" \
"${PROJECT_DIR}/run.sh" "${MODE_ARGS[@]}" "${traj}"; then
if validate_or_explain "${DATASET_ROOT_ABS}" "${traj}"; then
echo "[datasets_construct] verified $(basename "${traj}")"
rm -f "${ORIGINAL_CSV}"
ORIGINAL_CSV=""
CURRENT_TRAJ=""
break
fi
else
run_status=$?
if [[ "${run_status}" -eq 124 ]]; then
timed_out=1
echo "[datasets_construct] timeout after ${SIMPLE_DRONE_RUN_TIMEOUT:-900}s; skipping $(basename "${traj}")" >&2
break
fi
echo "[datasets_construct] run.sh failed for $(basename "${traj}") status=${run_status}" >&2
fi
attempt=$((attempt + 1))
if [[ "${attempt}" -le "${MAX_ATTEMPTS}" ]]; then
echo "[datasets_construct] retrying $(basename "${traj}")"
sleep 1
fi
done
if [[ -n "${ORIGINAL_CSV}" ]]; then
cp "${ORIGINAL_CSV}" "${traj}"
rm -f "${ORIGINAL_CSV}"
ORIGINAL_CSV=""
CURRENT_TRAJ=""
if [[ "${timed_out}" -ne 0 ]]; then
clean_outputs "${DATASET_ROOT_ABS}" "${traj}"
skipped_timeouts=$((skipped_timeouts + 1))
continue
fi
echo "[datasets_construct] failed after ${MAX_ATTEMPTS} attempts: ${traj}" >&2
exit 1
fi
done
if [[ "${skipped_timeouts}" -gt 0 ]]; then
echo "[datasets_construct] skipped timed-out trajectories -> ${skipped_timeouts}" >&2
exit 1
fi
done
echo "[datasets_construct] complete"
|