U-EASWS / Processing_Code /estimate_vehicle_length.py
InterestingITS's picture
Upload 26 files
61c47a0 verified
Raw History Blame Contribute Delete
3.47 kB
"""Estimate fixed per-vehicle lengths using six-column pixel detections and calibration."""
import numpy as np
import pandas as pd
from _common import numeric, parser, read_csv, require, save_csv, unique
from coordinate_transform import load_calibration
def estimate(df, calibration, minimum_frames=5, iqr_factor=1.5):
df = df.copy()
numeric(df, ["Frame", "Vehicle_ID"], integer=True)
unique(df, ["Frame", "Vehicle_ID"])
cols = ["x_center_px", "y_center_px", "width_px", "height_px"]
require(df, cols)
if (not np.isfinite([minimum_frames, iqr_factor]).all() or minimum_frames < 5 or
int(minimum_frames) != minimum_frames or iqr_factor < 0):
raise ValueError("Require integer minimum_frames >= 5 and finite iqr_factor >= 0")
data = df[cols].apply(pd.to_numeric, errors="coerce").to_numpy(float)
x, y, w, h = data.T
valid = np.isfinite(data).all(axis=1) & (w > 0) & (h > 0)
length, width = np.full(len(df), np.nan), np.full(len(df), np.nan)
indexes = np.flatnonzero(valid)
for block in np.array_split(indexes, max(1, int(np.ceil(len(indexes) / 100000)))):
if not len(block):
continue
corners = np.stack([np.column_stack((x[block] + sx * w[block] / 2,
y[block] + sy * h[block] / 2))
for sx, sy in [(-1, -1), (1, -1), (1, 1), (-1, 1)]], axis=1)
metric = calibration.transform(corners.reshape(-1, 2).astype(np.float32)).reshape(-1, 4, 2)
length[block], width[block] = np.ptp(metric, axis=1).T
valid &= np.isfinite(length) & np.isfinite(width) & (length > 0) & (width > 0)
rows = []
for vehicle, indexes in df.groupby("Vehicle_ID", sort=True).indices.items():
selected = indexes[valid[indexes]]
before = len(selected)
if before >= 4:
q1, q3 = np.quantile(length[selected], [0.25, 0.75])
margin = iqr_factor * (q3 - q1)
selected = selected[(length[selected] >= q1 - margin) & (length[selected] <= q3 + margin)]
sufficient = len(selected) >= minimum_frames
rows.append({"Source_ID": calibration.source, "Vehicle_ID": vehicle,
"Vehicle_Length_m": np.quantile(length[selected], 0.25) if sufficient else np.nan,
"BBox_Lateral_Extent_Q25_m": np.quantile(width[selected], 0.25) if sufficient else np.nan,
"Input_Frames": len(indexes), "Valid_Before_IQR": before,
"Retained_Frames": len(selected), "Removed_By_IQR": before - len(selected),
"Quality": "good" if len(selected) >= 20 else "limited" if sufficient else "insufficient"})
return pd.DataFrame(rows)
def main():
p = parser(__doc__)
p.add_argument("--input", required=True, help="Six-column raw detection CSV; one source video")
p.add_argument("--calibration", required=True, help="Same scene calibration JSON used for centers")
p.add_argument("--source", required=True, help="Source video key in calibration JSON")
p.add_argument("--output", required=True, help="New per-vehicle metric length and QC CSV")
a = p.parse_args()
df = read_csv(a.input)
if "Source_ID" in df and not df.Source_ID.eq(a.source).all():
raise ValueError("Input must contain only the requested source")
save_csv(estimate(df, load_calibration(a.calibration, a.source)), a.output)
if __name__ == "__main__":
main()