streetframe 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- streetframe/__init__.py +10 -0
- streetframe/bridge/__init__.py +0 -0
- streetframe/bridge/projectsidewalk.py +86 -0
- streetframe/core/__init__.py +4 -0
- streetframe/core/collection.py +210 -0
- streetframe/core/conventions.py +76 -0
- streetframe/core/schema.py +80 -0
- streetframe/coverage.py +125 -0
- streetframe/geometry/__init__.py +5 -0
- streetframe/geometry/align.py +73 -0
- streetframe/geometry/camera.py +302 -0
- streetframe/geometry/cyclic.py +74 -0
- streetframe/geometry/equirect.py +132 -0
- streetframe/geometry/ground.py +73 -0
- streetframe/geometry/register.py +260 -0
- streetframe/geometry/resample.py +83 -0
- streetframe/geometry/rotation.py +99 -0
- streetframe/inspect/__init__.py +7 -0
- streetframe/inspect/checks.py +143 -0
- streetframe/inspect/corrections.py +50 -0
- streetframe/inspect/html.py +199 -0
- streetframe/inspect/overlay.py +67 -0
- streetframe/inspect/plot.py +93 -0
- streetframe/models.py +121 -0
- streetframe/rank.py +55 -0
- streetframe/reconstruct/__init__.py +5 -0
- streetframe/reconstruct/colmap.py +280 -0
- streetframe/results.py +114 -0
- streetframe/sources/__init__.py +7 -0
- streetframe/sources/base.py +42 -0
- streetframe/sources/http.py +39 -0
- streetframe/sources/local.py +253 -0
- streetframe/sources/mapillary.py +157 -0
- streetframe/sources/panoramax.py +159 -0
- streetframe/sources/projectsidewalk.py +102 -0
- streetframe/store.py +151 -0
- streetframe/transfer.py +82 -0
- streetframe-0.0.1.dist-info/METADATA +51 -0
- streetframe-0.0.1.dist-info/RECORD +40 -0
- streetframe-0.0.1.dist-info/WHEEL +4 -0
streetframe/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""StreetFrame: provider-neutral street-level imagery as GeoDataFrames.
|
|
2
|
+
|
|
3
|
+
PROTOTYPE. The frame record is provisional (see DESIGN.md and PLAN.md).
|
|
4
|
+
"""
|
|
5
|
+
from .core import SCHEMA_VERSION, FrameCollection, SchemaError, make_frame_id
|
|
6
|
+
from .sources import LocalSource, SourceError
|
|
7
|
+
|
|
8
|
+
__version__ = "0.0.1"
|
|
9
|
+
__all__ = ["FrameCollection", "SchemaError", "make_frame_id", "SCHEMA_VERSION",
|
|
10
|
+
"LocalSource", "SourceError", "__version__"]
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Model detections in the form Project Sidewalk's AI endpoint accepts
|
|
2
|
+
(``POST /ai/submitLabelsOnPano``; DESIGN.md section 14).
|
|
3
|
+
|
|
4
|
+
This module only builds the request body. It does not send anything:
|
|
5
|
+
submitting writes labels into a live deployment and needs its maintainers'
|
|
6
|
+
agreement and credentials.
|
|
7
|
+
|
|
8
|
+
The shape was read from ``AiLabelsSubmission`` and ``PanoSubmission`` in
|
|
9
|
+
Project Sidewalk's ``app/formats/json/ExploreFormats.scala`` (snake-case
|
|
10
|
+
JSON) on 6 December 2026 and is to be confirmed with the maintainers.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
from ..core.collection import FrameCollection
|
|
20
|
+
from ..results import Observations
|
|
21
|
+
|
|
22
|
+
#: Project Sidewalk's names for imagery sources that this library also knows.
|
|
23
|
+
PANO_SOURCES = {"gsv": "gsv", "mapillary": "mapillary", "panoramax": "panoramax", "infra3d": "infra3d"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PayloadError(ValueError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def submission_payloads(observations: Observations, frames: FrameCollection, *, api_version: str,
|
|
31
|
+
overwrite: bool = False) -> list[dict[str, Any]]:
|
|
32
|
+
"""One request body per (panorama, label type) for a model's detections.
|
|
33
|
+
|
|
34
|
+
The observations must come from a model (``producer_kind == "model"``),
|
|
35
|
+
carry ``x_norm``, ``y_norm`` and ``confidence``, and their provenance must
|
|
36
|
+
name the model (``producer``) and its training date
|
|
37
|
+
(``model_training_date``). Every frame must be an equirectangular
|
|
38
|
+
panorama from a source Project Sidewalk knows, with size, position and heading.
|
|
39
|
+
"""
|
|
40
|
+
prov = observations.provenance
|
|
41
|
+
if not prov.get("model_training_date"):
|
|
42
|
+
raise PayloadError("provenance needs model_training_date")
|
|
43
|
+
o = observations.gdf
|
|
44
|
+
if (o["producer_kind"] != "model").any():
|
|
45
|
+
raise PayloadError("only model detections are submitted through this endpoint")
|
|
46
|
+
for col in ("x_norm", "y_norm", "confidence"):
|
|
47
|
+
if o[col].isna().any():
|
|
48
|
+
raise PayloadError(f"every detection needs {col}")
|
|
49
|
+
by_id = frames.gdf.set_index("frame_id")
|
|
50
|
+
missing = sorted(set(o["frame_id"]) - set(by_id.index))
|
|
51
|
+
if missing:
|
|
52
|
+
raise PayloadError(f"frames not in the collection: {missing[:3]}")
|
|
53
|
+
out = []
|
|
54
|
+
for (frame_id, label), grp in o.groupby(["frame_id", "label"], sort=True):
|
|
55
|
+
f = by_id.loc[frame_id]
|
|
56
|
+
if f["source"] not in PANO_SOURCES:
|
|
57
|
+
raise PayloadError(f"{frame_id}: Project Sidewalk has no imagery source {f['source']!r}")
|
|
58
|
+
if f["projection"] != "equirectangular":
|
|
59
|
+
raise PayloadError(f"{frame_id}: only panoramas can be submitted")
|
|
60
|
+
need = {k: f[k] for k in ("width_px", "height_px", "heading_deg")}
|
|
61
|
+
if any(pd.isna(v) for v in need.values()):
|
|
62
|
+
raise PayloadError(f"{frame_id}: needs width, height and heading")
|
|
63
|
+
w, h = int(f["width_px"]), int(f["height_px"])
|
|
64
|
+
meta = None if pd.isna(f["source_metadata"]) else json.loads(f["source_metadata"])
|
|
65
|
+
out.append({
|
|
66
|
+
"label_type": label, "model_id": f"{prov['producer']}@{prov['producer_version']}",
|
|
67
|
+
"model_training_date": prov["model_training_date"], "api_version": api_version,
|
|
68
|
+
"overwrite": overwrite,
|
|
69
|
+
"pano": {
|
|
70
|
+
"pano_id": f["native_id"], "source": PANO_SOURCES[f["source"]],
|
|
71
|
+
"capture_date": "" if pd.isna(f["captured_at"]) else f["captured_at"].strftime("%Y-%m"),
|
|
72
|
+
"width": w, "height": h, "tile_width": None, "tile_height": None,
|
|
73
|
+
"lat": float(f.geometry.y), "lng": float(f.geometry.x),
|
|
74
|
+
"camera_heading": float(f["heading_deg"]),
|
|
75
|
+
"camera_pitch": None if pd.isna(f["pitch_deg"]) else float(f["pitch_deg"]),
|
|
76
|
+
"camera_roll": None if pd.isna(f["roll_deg"]) else float(f["roll_deg"]),
|
|
77
|
+
"links": [], "history": [], "address": None,
|
|
78
|
+
"copyright": None if pd.isna(f["copyright"]) else f["copyright"],
|
|
79
|
+
"license": None if pd.isna(f["license"]) else f["license"],
|
|
80
|
+
"source_metadata": meta if isinstance(meta, dict) else None,
|
|
81
|
+
},
|
|
82
|
+
"labels": [{"pano_x": int(round(x * w)) % w, "pano_y": min(int(round(y * h)), h - 1),
|
|
83
|
+
"confidence": float(c)}
|
|
84
|
+
for x, y, c in zip(grp["x_norm"], grp["y_norm"], grp["confidence"])],
|
|
85
|
+
})
|
|
86
|
+
return out
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""FrameCollection: a validated GeoDataFrame of frames (DESIGN.md section 6.3)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Iterable, Mapping
|
|
8
|
+
|
|
9
|
+
import geopandas as gpd
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from shapely.geometry import Point
|
|
13
|
+
|
|
14
|
+
from . import schema
|
|
15
|
+
from .conventions import CRS
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SchemaError(ValueError):
|
|
19
|
+
"""A table of frames does not follow the frame record."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def make_frame_id(source: str, native_id: str) -> str:
|
|
23
|
+
"""The library-wide identifier of a frame.
|
|
24
|
+
|
|
25
|
+
>>> make_frame_id("mapillary", "123")
|
|
26
|
+
'mapillary:123'
|
|
27
|
+
"""
|
|
28
|
+
if ":" in source:
|
|
29
|
+
raise ValueError(f"source name may not contain ':': {source!r}")
|
|
30
|
+
return f"{source}:{native_id}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _to_utc(values: pd.Series) -> pd.Series:
|
|
34
|
+
"""Timestamps in UTC. Providers mix formats (with and without fractions of a second)."""
|
|
35
|
+
if pd.api.types.is_datetime64_any_dtype(values):
|
|
36
|
+
return pd.to_datetime(values, utc=True)
|
|
37
|
+
return pd.to_datetime(values, utc=True, format="mixed")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _json_text(v):
|
|
41
|
+
if isinstance(v, str):
|
|
42
|
+
return v
|
|
43
|
+
if v is None or v is pd.NA or (isinstance(v, float) and v != v):
|
|
44
|
+
return pd.NA
|
|
45
|
+
return json.dumps(v, sort_keys=True, default=str)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _coerce(gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
|
49
|
+
"""Add missing optional columns and give every column its schema type."""
|
|
50
|
+
out = gdf.copy()
|
|
51
|
+
for f in schema.FIELDS:
|
|
52
|
+
if f.name == "geometry":
|
|
53
|
+
continue
|
|
54
|
+
if f.name not in out.columns:
|
|
55
|
+
out[f.name] = pd.NA
|
|
56
|
+
if f.kind == "timestamp":
|
|
57
|
+
out[f.name] = _to_utc(out[f.name])
|
|
58
|
+
elif f.kind == "json":
|
|
59
|
+
out[f.name] = out[f.name].map(_json_text).astype("string")
|
|
60
|
+
else:
|
|
61
|
+
out[f.name] = out[f.name].astype(schema.PANDAS_DTYPES[f.kind])
|
|
62
|
+
extra = [c for c in out.columns if c not in schema.FIELD_NAMES]
|
|
63
|
+
cols = [n for n in schema.FIELD_NAMES if n != "geometry"] + extra + ["geometry"]
|
|
64
|
+
return out[cols]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def validate(gdf: gpd.GeoDataFrame) -> None:
|
|
68
|
+
"""Raise :class:`SchemaError` listing every way ``gdf`` breaks the record."""
|
|
69
|
+
problems: list[str] = []
|
|
70
|
+
missing = [n for n in schema.REQUIRED if n not in gdf.columns]
|
|
71
|
+
if missing:
|
|
72
|
+
raise SchemaError(f"missing required columns: {missing}")
|
|
73
|
+
if gdf.crs is None or gdf.crs.to_string() != CRS:
|
|
74
|
+
problems.append(f"crs must be {CRS}, got {gdf.crs}")
|
|
75
|
+
for name in schema.REQUIRED:
|
|
76
|
+
if name != "geometry" and gdf[name].isna().any():
|
|
77
|
+
problems.append(f"{name}: {int(gdf[name].isna().sum())} missing values")
|
|
78
|
+
if gdf.geometry.isna().any() or gdf.geometry.is_empty.any():
|
|
79
|
+
problems.append("geometry: missing or empty positions")
|
|
80
|
+
elif not (gdf.geometry.geom_type == "Point").all():
|
|
81
|
+
problems.append("geometry: every position must be a Point")
|
|
82
|
+
elif not (np.isfinite(gdf.geometry.x) & np.isfinite(gdf.geometry.y)).all():
|
|
83
|
+
problems.append("geometry: positions with coordinates that are not numbers")
|
|
84
|
+
else:
|
|
85
|
+
if ((gdf.geometry.x < -180) | (gdf.geometry.x > 180)).any():
|
|
86
|
+
problems.append("geometry: longitude outside [-180, 180]")
|
|
87
|
+
if ((gdf.geometry.y < -90) | (gdf.geometry.y > 90)).any():
|
|
88
|
+
problems.append("geometry: latitude outside [-90, 90]")
|
|
89
|
+
if gdf["frame_id"].duplicated().any():
|
|
90
|
+
problems.append(f"frame_id: {int(gdf['frame_id'].duplicated().sum())} duplicates")
|
|
91
|
+
expected = gdf["source"].astype(str) + ":" + gdf["native_id"].astype(str)
|
|
92
|
+
if not (gdf["frame_id"].astype(str) == expected).all():
|
|
93
|
+
problems.append("frame_id must equal source + ':' + native_id")
|
|
94
|
+
for f in schema.FIELDS:
|
|
95
|
+
if f.values and f.name in gdf.columns:
|
|
96
|
+
bad = set(gdf[f.name].dropna().unique()) - set(f.values)
|
|
97
|
+
if bad:
|
|
98
|
+
problems.append(f"{f.name}: values {sorted(bad)} not in {list(f.values)}")
|
|
99
|
+
unknown = set(gdf["schema_version"].dropna()) - {schema.SCHEMA_VERSION}
|
|
100
|
+
if unknown:
|
|
101
|
+
problems.append(f"schema_version {sorted(unknown)} is not one this version reads ({schema.SCHEMA_VERSION})")
|
|
102
|
+
for name in ("intrinsics", "source_metadata"):
|
|
103
|
+
if name in gdf.columns:
|
|
104
|
+
for fid, text in zip(gdf["frame_id"], gdf[name]):
|
|
105
|
+
if isinstance(text, str):
|
|
106
|
+
try:
|
|
107
|
+
json.loads(text)
|
|
108
|
+
except ValueError:
|
|
109
|
+
problems.append(f"{name} of {fid} is not JSON")
|
|
110
|
+
break
|
|
111
|
+
if "heading_deg" in gdf.columns:
|
|
112
|
+
h = gdf["heading_deg"].dropna().astype(float)
|
|
113
|
+
if ((h < 0) | (h >= 360)).any():
|
|
114
|
+
problems.append("heading_deg outside [0, 360)")
|
|
115
|
+
if "pitch_deg" in gdf.columns:
|
|
116
|
+
p = gdf["pitch_deg"].dropna().astype(float)
|
|
117
|
+
if (p.abs() > 90).any():
|
|
118
|
+
problems.append("pitch_deg outside [-90, 90]")
|
|
119
|
+
if "roll_deg" in gdf.columns:
|
|
120
|
+
r = gdf["roll_deg"].dropna().astype(float)
|
|
121
|
+
if ((r < -180) | (r >= 180)).any():
|
|
122
|
+
problems.append("roll_deg outside [-180, 180)")
|
|
123
|
+
if problems:
|
|
124
|
+
raise SchemaError("; ".join(problems))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class FrameCollection:
|
|
128
|
+
"""A thin, validated wrapper around a GeoDataFrame of frames.
|
|
129
|
+
|
|
130
|
+
``.gdf`` is the plain GeoDataFrame, so any GeoPandas operation works without
|
|
131
|
+
this class.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def __init__(self, gdf: gpd.GeoDataFrame):
|
|
135
|
+
gdf = _coerce(gdf)
|
|
136
|
+
validate(gdf)
|
|
137
|
+
self.gdf = gdf.reset_index(drop=True)
|
|
138
|
+
|
|
139
|
+
# construction -----------------------------------------------------------
|
|
140
|
+
@classmethod
|
|
141
|
+
def from_records(cls, records: Iterable[Mapping[str, Any]]) -> "FrameCollection":
|
|
142
|
+
"""Build from dictionaries with ``lon`` and ``lat`` (or a ``geometry``).
|
|
143
|
+
|
|
144
|
+
``frame_id``, ``retrieved_at`` and ``schema_version`` are filled in when
|
|
145
|
+
absent. ``pose_quality`` and ``redistribution`` default to ``unknown``.
|
|
146
|
+
"""
|
|
147
|
+
now = datetime.now(timezone.utc)
|
|
148
|
+
rows = []
|
|
149
|
+
for rec in records:
|
|
150
|
+
r = dict(rec)
|
|
151
|
+
if "geometry" not in r:
|
|
152
|
+
r["geometry"] = Point(float(r.pop("lon")), float(r.pop("lat")))
|
|
153
|
+
r.setdefault("frame_id", make_frame_id(r["source"], str(r["native_id"])))
|
|
154
|
+
r.setdefault("pose_quality", "unknown")
|
|
155
|
+
r.setdefault("redistribution", "unknown")
|
|
156
|
+
r.setdefault("retrieved_at", now)
|
|
157
|
+
r.setdefault("schema_version", schema.SCHEMA_VERSION)
|
|
158
|
+
rows.append(r)
|
|
159
|
+
if not rows:
|
|
160
|
+
return cls.empty()
|
|
161
|
+
return cls(gpd.GeoDataFrame(rows, geometry="geometry", crs=CRS))
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def empty(cls) -> "FrameCollection":
|
|
165
|
+
gdf = gpd.GeoDataFrame({n: [] for n in schema.FIELD_NAMES if n != "geometry"},
|
|
166
|
+
geometry=gpd.GeoSeries([], crs=CRS), crs=CRS)
|
|
167
|
+
return cls(gdf)
|
|
168
|
+
|
|
169
|
+
@classmethod
|
|
170
|
+
def concat(cls, collections: Iterable["FrameCollection"]) -> "FrameCollection":
|
|
171
|
+
"""Frames from several sources in one table."""
|
|
172
|
+
frames = [c.gdf for c in collections if len(c)]
|
|
173
|
+
if not frames:
|
|
174
|
+
return cls.empty()
|
|
175
|
+
return cls(gpd.GeoDataFrame(pd.concat(frames, ignore_index=True), crs=CRS))
|
|
176
|
+
|
|
177
|
+
# storage ----------------------------------------------------------------
|
|
178
|
+
def to_parquet(self, path: str | Path) -> None:
|
|
179
|
+
"""Write GeoParquet. The table is checked again first, since ``.gdf`` can be changed freely."""
|
|
180
|
+
gdf = _coerce(self.gdf)
|
|
181
|
+
validate(gdf)
|
|
182
|
+
gdf.to_parquet(path, index=False)
|
|
183
|
+
|
|
184
|
+
@classmethod
|
|
185
|
+
def read_parquet(cls, path: str | Path) -> "FrameCollection":
|
|
186
|
+
return cls(gpd.read_parquet(path))
|
|
187
|
+
|
|
188
|
+
# access -----------------------------------------------------------------
|
|
189
|
+
def __len__(self) -> int:
|
|
190
|
+
return len(self.gdf)
|
|
191
|
+
|
|
192
|
+
def __repr__(self) -> str:
|
|
193
|
+
by = self.gdf["source"].value_counts().to_dict() if len(self) else {}
|
|
194
|
+
return f"FrameCollection({len(self)} frames, sources={by})"
|
|
195
|
+
|
|
196
|
+
def frame(self, frame_id: str) -> pd.Series:
|
|
197
|
+
"""One frame's record."""
|
|
198
|
+
hit = self.gdf[self.gdf["frame_id"] == frame_id]
|
|
199
|
+
if hit.empty:
|
|
200
|
+
raise KeyError(frame_id)
|
|
201
|
+
return hit.iloc[0]
|
|
202
|
+
|
|
203
|
+
def select(self, mask) -> "FrameCollection":
|
|
204
|
+
"""A collection of the rows where ``mask`` is true."""
|
|
205
|
+
return FrameCollection(self.gdf[mask])
|
|
206
|
+
|
|
207
|
+
def source_metadata(self, frame_id: str) -> Any:
|
|
208
|
+
"""The provider's original record for a frame, decoded."""
|
|
209
|
+
raw = self.frame(frame_id)["source_metadata"]
|
|
210
|
+
return None if pd.isna(raw) else json.loads(raw)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The conventions every frame follows (DESIGN.md section 6.2).
|
|
2
|
+
|
|
3
|
+
Stated once here and enforced where a source hands frames to the library.
|
|
4
|
+
|
|
5
|
+
- Angles are in degrees. Positions are longitude and latitude in EPSG:4326.
|
|
6
|
+
Distances are in meters.
|
|
7
|
+
- ``heading_deg`` is the compass bearing, clockwise from north, of the image
|
|
8
|
+
center, in [0, 360).
|
|
9
|
+
- ``pitch_deg`` is positive when the camera looks up.
|
|
10
|
+
- ``roll_deg`` is positive when the camera is rotated clockwise as seen from
|
|
11
|
+
behind it (its right-hand side dips).
|
|
12
|
+
- Pixel coordinates have the origin at the top-left corner of the image, ``x``
|
|
13
|
+
to the right and ``y`` down, and are continuous: the center of the top-left
|
|
14
|
+
pixel is (0.5, 0.5), the image spans [0, width] by [0, height].
|
|
15
|
+
- Normalized coordinates are pixel coordinates divided by the image size, so
|
|
16
|
+
they span [0, 1].
|
|
17
|
+
|
|
18
|
+
Sources that use other conventions convert on the way in with the functions
|
|
19
|
+
below. Known differences (from a reading of the code on 5 December 2026, to be
|
|
20
|
+
confirmed with the maintainers):
|
|
21
|
+
|
|
22
|
+
- RampNet ``perspective.heading_pitch_roll``: roll is positive when the
|
|
23
|
+
camera's right-hand side tilts *up*, the opposite sign.
|
|
24
|
+
- RampNet pixel indices ``c`` address pixel centers at ``c + 0.5``.
|
|
25
|
+
- ArtScape keeps headings in radians.
|
|
26
|
+
"""
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
CRS = "EPSG:4326"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def wrap360(deg):
|
|
35
|
+
"""Wrap degrees into [0, 360).
|
|
36
|
+
|
|
37
|
+
>>> float(wrap360(-90.0))
|
|
38
|
+
270.0
|
|
39
|
+
>>> float(wrap360(360.0))
|
|
40
|
+
0.0
|
|
41
|
+
"""
|
|
42
|
+
return np.asarray(deg, dtype=float) % 360.0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def wrap180(deg):
|
|
46
|
+
"""Wrap degrees into [-180, 180).
|
|
47
|
+
|
|
48
|
+
>>> float(wrap180(190.0))
|
|
49
|
+
-170.0
|
|
50
|
+
"""
|
|
51
|
+
return (np.asarray(deg, dtype=float) + 180.0) % 360.0 - 180.0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def angle_diff(a_deg, b_deg):
|
|
55
|
+
"""Signed smallest rotation from ``b`` to ``a``, in [-180, 180).
|
|
56
|
+
|
|
57
|
+
>>> float(angle_diff(10.0, 350.0))
|
|
58
|
+
20.0
|
|
59
|
+
"""
|
|
60
|
+
return wrap180(np.asarray(a_deg, dtype=float) - np.asarray(b_deg, dtype=float))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def heading_from_radians(rad):
|
|
64
|
+
"""A heading in radians (clockwise from north) to degrees in [0, 360)."""
|
|
65
|
+
return wrap360(np.degrees(rad))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def roll_from_right_side_up(roll_deg):
|
|
69
|
+
"""Roll given as "positive when the camera's right-hand side tilts up"
|
|
70
|
+
(RampNet's sign) to this library's sign."""
|
|
71
|
+
return -np.asarray(roll_deg, dtype=float)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def pixel_from_index(index):
|
|
75
|
+
"""An integer pixel index to the continuous coordinate of its center."""
|
|
76
|
+
return np.asarray(index, dtype=float) + 0.5
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The frame record (DESIGN.md section 6.1).
|
|
2
|
+
|
|
3
|
+
PROVISIONAL. This schema is a proposal to be settled with the Project Sidewalk
|
|
4
|
+
and RampNet maintainers; field names and types are expected to change. It
|
|
5
|
+
follows Project Sidewalk's ``pano_data`` table closely and adds what
|
|
6
|
+
perspective images need.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
SCHEMA_VERSION = "0.1-provisional"
|
|
13
|
+
|
|
14
|
+
PROJECTIONS = ("equirectangular", "perspective", "fisheye", "cubemap")
|
|
15
|
+
POSE_QUALITIES = ("reported", "computed", "reconstructed", "registered", "estimated", "unknown")
|
|
16
|
+
CAPTURED_PRECISIONS = ("year", "month", "day", "second")
|
|
17
|
+
REDISTRIBUTION = ("allowed", "allowed_with_attribution", "not_allowed", "unknown")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Field:
|
|
22
|
+
name: str
|
|
23
|
+
kind: str # string, float, int, bool, timestamp, category, json, geometry
|
|
24
|
+
required: bool = False
|
|
25
|
+
values: tuple[str, ...] | None = None
|
|
26
|
+
doc: str = ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
FIELDS: tuple[Field, ...] = (
|
|
30
|
+
Field("frame_id", "string", True, doc="source:native_id, unique across sources"),
|
|
31
|
+
Field("source", "string", True, doc="Registered source name"),
|
|
32
|
+
Field("native_id", "string", True, doc="The provider's identifier, unchanged"),
|
|
33
|
+
Field("instance", "string", doc="For federated providers"),
|
|
34
|
+
Field("geometry", "geometry", True, doc="Camera position, point, EPSG:4326"),
|
|
35
|
+
Field("elevation_m", "float"),
|
|
36
|
+
Field("position_accuracy_m", "float"),
|
|
37
|
+
Field("heading_deg", "float", doc="Compass bearing of the image center, [0, 360)"),
|
|
38
|
+
Field("pitch_deg", "float", doc="Positive looking up"),
|
|
39
|
+
Field("roll_deg", "float", doc="Positive clockwise seen from behind the camera"),
|
|
40
|
+
Field("pose_quality", "category", True, POSE_QUALITIES),
|
|
41
|
+
Field("levelled", "bool", doc="Whether the raster is already gravity-aligned"),
|
|
42
|
+
Field("projection", "category", True, PROJECTIONS),
|
|
43
|
+
Field("width_px", "int"),
|
|
44
|
+
Field("height_px", "int"),
|
|
45
|
+
Field("hfov_deg", "float", doc="For perspective and fisheye"),
|
|
46
|
+
Field("vfov_deg", "float"),
|
|
47
|
+
Field("intrinsics", "json", doc="Focal length, principal point, distortion"),
|
|
48
|
+
Field("captured_at", "timestamp", doc="UTC"),
|
|
49
|
+
Field("captured_precision", "category", values=CAPTURED_PRECISIONS),
|
|
50
|
+
Field("sequence_id", "string"),
|
|
51
|
+
Field("sequence_index", "int"),
|
|
52
|
+
Field("platform", "string"),
|
|
53
|
+
Field("camera_make", "string"),
|
|
54
|
+
Field("camera_model", "string"),
|
|
55
|
+
Field("copyright", "string", doc="Holder as the provider states it"),
|
|
56
|
+
Field("license", "string", doc="SPDX identifier when known, else the provider's text"),
|
|
57
|
+
Field("attribution", "string", doc="The line to display"),
|
|
58
|
+
Field("redistribution", "category", True, REDISTRIBUTION),
|
|
59
|
+
Field("available", "bool"),
|
|
60
|
+
Field("checked_at", "timestamp"),
|
|
61
|
+
Field("uri", "string", doc="Where the pixels can be obtained"),
|
|
62
|
+
Field("sha256", "string"),
|
|
63
|
+
Field("bytes", "int"),
|
|
64
|
+
Field("source_metadata", "json", doc="The provider's original record, unchanged"),
|
|
65
|
+
Field("retrieved_at", "timestamp", True),
|
|
66
|
+
Field("schema_version", "string", True),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
FIELD_NAMES = tuple(f.name for f in FIELDS)
|
|
70
|
+
REQUIRED = tuple(f.name for f in FIELDS if f.required)
|
|
71
|
+
BY_NAME = {f.name: f for f in FIELDS}
|
|
72
|
+
|
|
73
|
+
PANDAS_DTYPES = {
|
|
74
|
+
"string": "string",
|
|
75
|
+
"float": "Float64",
|
|
76
|
+
"int": "Int64",
|
|
77
|
+
"bool": "boolean",
|
|
78
|
+
"category": "string",
|
|
79
|
+
"json": "string",
|
|
80
|
+
}
|
streetframe/coverage.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Where and when imagery exists, from frame metadata alone (DESIGN.md section 10)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import geopandas as gpd
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from shapely.geometry import box
|
|
8
|
+
|
|
9
|
+
from .core.collection import FrameCollection
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _stats(frames: pd.DataFrame) -> dict:
|
|
13
|
+
t = frames["captured_at"].dropna()
|
|
14
|
+
return dict(n_frames=len(frames),
|
|
15
|
+
oldest=t.min() if len(t) else pd.NaT, newest=t.max() if len(t) else pd.NaT,
|
|
16
|
+
n_years=int(t.dt.year.nunique()), n_sources=int(frames["source"].nunique()),
|
|
17
|
+
n_sequences=int(frames["sequence_id"].nunique()),
|
|
18
|
+
share_panorama=float((frames["projection"] == "equirectangular").mean()) if len(frames) else np.nan)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def sun_elevation_deg(when: pd.Series, lon, lat) -> np.ndarray:
|
|
22
|
+
"""Approximate elevation of the sun above the horizon (degrees) at UTC times
|
|
23
|
+
and places; good to about a degree, which is enough to tell day from night."""
|
|
24
|
+
t = pd.to_datetime(when, utc=True)
|
|
25
|
+
doy = t.dt.day_of_year.to_numpy(dtype=float)
|
|
26
|
+
hours = (t.dt.hour + t.dt.minute / 60 + t.dt.second / 3600).to_numpy(dtype=float)
|
|
27
|
+
g = 2 * np.pi / 365.0 * (doy - 1 + (hours - 12) / 24)
|
|
28
|
+
decl = (0.006918 - 0.399912 * np.cos(g) + 0.070257 * np.sin(g) - 0.006758 * np.cos(2 * g)
|
|
29
|
+
+ 0.000907 * np.sin(2 * g) - 0.002697 * np.cos(3 * g) + 0.00148 * np.sin(3 * g))
|
|
30
|
+
eqtime = 229.18 * (0.000075 + 0.001868 * np.cos(g) - 0.032077 * np.sin(g) - 0.014615 * np.cos(2 * g)
|
|
31
|
+
- 0.040849 * np.sin(2 * g))
|
|
32
|
+
solar_hours = hours + (eqtime + 4 * np.asarray(lon, dtype=float)) / 60
|
|
33
|
+
ha = np.radians(15 * (solar_hours - 12))
|
|
34
|
+
la = np.radians(np.asarray(lat, dtype=float))
|
|
35
|
+
return np.degrees(np.arcsin(np.sin(la) * np.sin(decl) + np.cos(la) * np.cos(decl) * np.cos(ha)))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def frame_indicators(frames: FrameCollection) -> pd.DataFrame:
|
|
39
|
+
"""Per frame, from metadata alone: ``solar_hour`` (local solar time, 0 to
|
|
40
|
+
24), ``sun_elevation_deg``, ``daylight`` (day, twilight, night), ``season``
|
|
41
|
+
(by hemisphere), ``year``, and within its sequence ``speed_mps``.
|
|
42
|
+
Missing where the capture time is unknown or its precision is coarser than a second."""
|
|
43
|
+
g = frames.gdf
|
|
44
|
+
lon, lat = g.geometry.x.to_numpy(), g.geometry.y.to_numpy()
|
|
45
|
+
t = g["captured_at"]
|
|
46
|
+
exact = (t.notna() & (g["captured_precision"] == "second")).to_numpy()
|
|
47
|
+
out = pd.DataFrame({"frame_id": g["frame_id"].to_numpy()})
|
|
48
|
+
hours = (t.dt.hour + t.dt.minute / 60 + t.dt.second / 3600).to_numpy(dtype=float, na_value=np.nan)
|
|
49
|
+
out["solar_hour"] = np.where(exact, (hours + lon / 15.0) % 24, np.nan)
|
|
50
|
+
elev = np.full(len(g), np.nan)
|
|
51
|
+
if exact.any():
|
|
52
|
+
elev[exact] = sun_elevation_deg(t[exact], lon[exact], lat[exact])
|
|
53
|
+
out["sun_elevation_deg"] = elev
|
|
54
|
+
out["daylight"] = pd.Series(np.select([np.isnan(elev), elev > 0, elev > -6], [None, "day", "twilight"], "night"),
|
|
55
|
+
dtype="string")
|
|
56
|
+
month = t.dt.month.to_numpy(dtype=float, na_value=np.nan)
|
|
57
|
+
north = np.select([np.isin(month, (12, 1, 2)), np.isin(month, (3, 4, 5)), np.isin(month, (6, 7, 8)),
|
|
58
|
+
np.isin(month, (9, 10, 11))], ["winter", "spring", "summer", "autumn"], None)
|
|
59
|
+
flip = {"winter": "summer", "summer": "winter", "spring": "autumn", "autumn": "spring", None: None}
|
|
60
|
+
out["season"] = pd.Series([s if la >= 0 else flip[s] for s, la in zip(north, lat)], dtype="string")
|
|
61
|
+
out["year"] = t.dt.year.astype("Int64").to_numpy()
|
|
62
|
+
out["speed_mps"] = np.nan
|
|
63
|
+
from .geometry.ground import bearing_distance
|
|
64
|
+
for _, seq in g[g["sequence_id"].notna() & exact].groupby("sequence_id", sort=False):
|
|
65
|
+
if len(seq) < 2:
|
|
66
|
+
continue
|
|
67
|
+
seq = seq.sort_values("sequence_index" if seq["sequence_index"].notna().all() else "captured_at", kind="stable")
|
|
68
|
+
_, d = bearing_distance(seq.geometry.x.to_numpy()[:-1], seq.geometry.y.to_numpy()[:-1],
|
|
69
|
+
seq.geometry.x.to_numpy()[1:], seq.geometry.y.to_numpy()[1:])
|
|
70
|
+
dt = seq["captured_at"].diff().dt.total_seconds().to_numpy()[1:]
|
|
71
|
+
adjacent = (np.diff(seq["sequence_index"].to_numpy(dtype=float)) == 1
|
|
72
|
+
if seq["sequence_index"].notna().all() else np.ones(len(d), bool))
|
|
73
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
74
|
+
speed = np.where(adjacent & (dt > 0), d / dt, np.nan)
|
|
75
|
+
out.loc[g.index.get_indexer(seq.index[1:]), "speed_mps"] = speed
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def coverage_by_segment(frames: FrameCollection, segments: gpd.GeoDataFrame, *, reach_m: float = 15.0,
|
|
80
|
+
step_m: float = 5.0) -> gpd.GeoDataFrame:
|
|
81
|
+
"""For each line of ``segments``: the frames within ``reach_m`` of it and
|
|
82
|
+
the share of its length that has a frame within ``reach_m``.
|
|
83
|
+
|
|
84
|
+
Adds ``n_frames``, ``covered_share`` (0 to 1, sampled every ``step_m``),
|
|
85
|
+
``oldest``, ``newest``, ``n_years``, ``n_sources``, ``n_sequences``,
|
|
86
|
+
``share_panorama`` to a copy of ``segments``.
|
|
87
|
+
"""
|
|
88
|
+
crs = segments.estimate_utm_crs() if len(segments) else frames.gdf.estimate_utm_crs()
|
|
89
|
+
seg = segments.to_crs(crs)
|
|
90
|
+
pts = frames.gdf.to_crs(crs)
|
|
91
|
+
index = pts.sindex
|
|
92
|
+
xy = np.column_stack([pts.geometry.x, pts.geometry.y]) if len(pts) else np.empty((0, 2))
|
|
93
|
+
rows = []
|
|
94
|
+
for line in seg.geometry:
|
|
95
|
+
near = index.query(line.buffer(reach_m), predicate="intersects") if len(pts) else np.array([], dtype=int)
|
|
96
|
+
row = _stats(frames.gdf.iloc[near])
|
|
97
|
+
n = max(2, int(np.ceil(line.length / step_m)) + 1)
|
|
98
|
+
samples = np.array([line.interpolate(d).coords[0] for d in np.linspace(0, line.length, n)])
|
|
99
|
+
if len(near):
|
|
100
|
+
d2 = ((samples[:, None, :] - xy[near][None, :, :]) ** 2).sum(-1).min(1)
|
|
101
|
+
row["covered_share"] = float((d2 <= reach_m ** 2).mean())
|
|
102
|
+
else:
|
|
103
|
+
row["covered_share"] = 0.0
|
|
104
|
+
row["length_m"] = float(line.length)
|
|
105
|
+
rows.append(row)
|
|
106
|
+
out = segments.copy()
|
|
107
|
+
for col in ("n_frames", "covered_share", "length_m", "oldest", "newest", "n_years", "n_sources",
|
|
108
|
+
"n_sequences", "share_panorama"):
|
|
109
|
+
out[col] = [r[col] for r in rows]
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def coverage_by_cell(frames: FrameCollection, *, cell_m: float = 50.0) -> gpd.GeoDataFrame:
|
|
114
|
+
"""Frames counted on a square grid of ``cell_m`` meters (in the local UTM
|
|
115
|
+
zone); only cells with frames are returned, as polygons in EPSG:4326."""
|
|
116
|
+
if len(frames) == 0:
|
|
117
|
+
return gpd.GeoDataFrame({"n_frames": []}, geometry=[], crs="EPSG:4326")
|
|
118
|
+
crs = frames.gdf.estimate_utm_crs()
|
|
119
|
+
pts = frames.gdf.to_crs(crs)
|
|
120
|
+
ix, iy = np.floor(pts.geometry.x / cell_m).astype(int), np.floor(pts.geometry.y / cell_m).astype(int)
|
|
121
|
+
rows, geoms = [], []
|
|
122
|
+
for (cx, cy), grp in frames.gdf.groupby([ix.to_numpy(), iy.to_numpy()]):
|
|
123
|
+
rows.append(dict(cell_x=int(cx), cell_y=int(cy), **_stats(grp)))
|
|
124
|
+
geoms.append(box(cx * cell_m, cy * cell_m, (cx + 1) * cell_m, (cy + 1) * cell_m))
|
|
125
|
+
return gpd.GeoDataFrame(rows, geometry=geoms, crs=crs).to_crs("EPSG:4326")
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Camera geometry. Needs only numpy and pyproj."""
|
|
2
|
+
from . import align, camera, cyclic, equirect, ground, register, resample, rotation
|
|
3
|
+
from .camera import Camera, frame_camera
|
|
4
|
+
|
|
5
|
+
__all__ = ["Camera", "frame_camera", "align", "camera", "cyclic", "equirect", "ground", "register", "resample", "rotation"]
|