129 lines
7.4 KiB
Python
129 lines
7.4 KiB
Python
"""Fuse depth-visible street-view observations into a metric surface atlas."""
|
|
import numpy as np
|
|
from PIL import Image
|
|
|
|
GROUND = [2, 7, 8, 9, 10, 11, 13, 14, 15, 23, 24]
|
|
|
|
|
|
def fuse(job, output, unproject, classes, write_json):
|
|
bounds = np.asarray(job['bounds_xy'], dtype=float)
|
|
cell = job.get('cell_m', .1)
|
|
width, height = np.ceil((bounds[1] - bounds[0]) / cell).astype(int)
|
|
count = width * height
|
|
evidence = np.zeros((len(GROUND), count), np.float32)
|
|
observed = np.zeros(count, np.uint16)
|
|
zsum = np.zeros(count, np.float64)
|
|
reference = next(v for v in job['views'] if v.get('projection') == 'ortho')
|
|
gtop = np.load(output / (reference['id'] + '.geometry.npz'))
|
|
vtop, ktop = gtop['view'], gtop['intrinsics']
|
|
if not np.allclose(vtop[2, :3], [0, 0, -1], atol=1e-6):
|
|
raise ValueError('The reference atlas requires a vertical orthographic view')
|
|
yy, xx = np.indices((height, width))
|
|
xyz = np.column_stack([bounds[0, 0] + (xx.ravel() + .5) * cell,
|
|
bounds[0, 1] + (height - yy.ravel() - .5) * cell,
|
|
np.zeros(count)])
|
|
projected = xyz @ vtop[:3, :3].T + vtop[:3, 3]
|
|
uv = projected[:, :2] * np.diag(ktop)[:2] + ktop[:2, 2] - .5
|
|
col, row = np.rint(uv).astype(int).T
|
|
th, tw = gtop['depth'].shape
|
|
inside = (col >= 0) & (col < tw) & (row >= 0) & (row < th)
|
|
col, row = np.clip(col, 0, tw - 1), np.clip(row, 0, th - 1)
|
|
xyz[:, 2] = vtop[2, 3] - gtop['depth'][row, col]
|
|
reference_valid = inside & (gtop['alpha'][row, col] >= .95) & np.isfinite(xyz).all(axis=1)
|
|
# Pull each metric cell into each camera. This covers the pixel footprint without
|
|
# interpolating labels across unobserved gaps between forward-projected rays.
|
|
for spec in job['views']:
|
|
if spec.get('projection', 'pinhole') != 'pinhole':
|
|
continue
|
|
labels = np.array(Image.open(output / (spec['id'] + '.labels.png')))
|
|
confidence = np.load(output / (spec['id'] + '.confidence.npy'))
|
|
g = np.load(output / (spec['id'] + '.geometry.npz'))
|
|
local = xyz @ g['view'][:3, :3].T + g['view'][:3, 3]
|
|
depth = local[:, 2]
|
|
uv = local[:, :2] / np.maximum(depth[:, None], .001) * np.diag(g['intrinsics'])[:2] + g['intrinsics'][:2, 2] - .5
|
|
col, row = np.rint(uv).astype(int).T
|
|
ih, iw = labels.shape
|
|
visible = reference_valid & (depth > .1) & (depth <= 30) & (col >= 0) & (col < iw) & (row >= 0) & (row < ih)
|
|
col, row = np.clip(col, 0, iw - 1), np.clip(row, 0, ih - 1)
|
|
seen_depth = g['depth'][row, col]
|
|
visible &= (g['alpha'][row, col] >= .95) & (np.abs(depth - seen_depth) <= np.maximum(.15, depth * .01))
|
|
sampled = labels[row, col]
|
|
visible &= np.isin(sampled, GROUND)
|
|
for i, label in enumerate(GROUND):
|
|
hit = visible & (sampled == label)
|
|
evidence[i, hit] += confidence[row[hit], col[hit]]
|
|
zsum[visible] += xyz[visible, 2]
|
|
observed[visible] += 1
|
|
winner = evidence.argmax(axis=0)
|
|
strength = evidence.max(axis=0) / np.maximum(evidence.sum(axis=0), 1e-6)
|
|
z = zsum / np.maximum(observed, 1)
|
|
accepted = (observed >= job.get('min_views', 1)) & (strength >= .7)
|
|
labels = np.where(accepted, np.asarray(GROUND)[winner], 255).reshape(height, width).astype(np.uint8)
|
|
z = z.reshape(height, width)
|
|
z[~accepted.reshape(height, width)] = np.nan
|
|
np.savez_compressed(output / 'surface-atlas.npz', labels=labels, z=z, views=observed.reshape(height, width),
|
|
confidence=strength.reshape(height, width), bounds=bounds, cell_m=cell)
|
|
rgb = np.full((height, width, 3), [25, 28, 32], np.uint8)
|
|
features = []
|
|
import rasterio.features
|
|
from affine import Affine
|
|
from shapely.geometry import shape
|
|
from shapely import make_valid
|
|
transform = Affine(cell, 0, bounds[0, 0], 0, -cell, bounds[0, 1] + height * cell)
|
|
for label in GROUND:
|
|
rgb[labels == label] = classes[label][1]
|
|
for geometry, value in rasterio.features.shapes(labels, mask=labels != 255, transform=transform, connectivity=4):
|
|
label = int(value)
|
|
# Raster diagonal contacts can produce point-touching rings. GEOS separates
|
|
# those contacts; retain only polygons and never expand into unknown cells.
|
|
candidate = make_valid(shape(geometry))
|
|
polygons = [candidate] if candidate.geom_type == 'Polygon' else [p for p in candidate.geoms if p.geom_type == 'Polygon']
|
|
def ring(coords):
|
|
result = []
|
|
for x, y in coords:
|
|
col = (x - bounds[0, 0]) / cell
|
|
row = (bounds[0, 1] + height * cell - y) / cell
|
|
adjacent = [(r, c) for r in [round(row) - 1, round(row)] for c in [round(col) - 1, round(col)]
|
|
if 0 <= r < height and 0 <= c < width and labels[r, c] == label and np.isfinite(z[r, c])]
|
|
if not adjacent:
|
|
raise ValueError('Contour vertex has no observed height support')
|
|
result.append([round(x, 4), round(y, 4), round(float(np.mean([z[r, c] for r, c in adjacent])), 4)])
|
|
return result
|
|
for polygon in polygons:
|
|
if polygon.area < .08:
|
|
continue
|
|
geometry3d = {'type': 'Polygon', 'coordinates': [ring(polygon.exterior.coords), *[ring(h.coords) for h in polygon.interiors]]}
|
|
name, color = classes[label]
|
|
features.append({'type': 'Feature', 'id': f'atlas-{label}-{len(features)}',
|
|
'properties': {'class': name, 'model_label': label, 'color': color, 'authority': 'observation-only',
|
|
'height_source': 'gaussian-depth-with-camera-visibility', 'review': 'required', 'route_permission': 'unassigned'},
|
|
'geometry': geometry3d})
|
|
Image.fromarray(rgb).save(output / 'surface-atlas.png')
|
|
document = {'schema_version': 'missioncore.urban-map/v1', 'type': 'FeatureCollection',
|
|
'coordinate_system': {'frame': 'scene-local', 'units': 'metres', 'up': 'Z', 'georeferenced': False},
|
|
'source': job['source'], 'model': job['model'], 'features': features,
|
|
'coverage': {'bounds_xy': bounds.tolist(), 'cell_m': cell, 'observed_cells': int((observed > 0).sum()),
|
|
'accepted_cells': int(accepted.sum()), 'multi_view_cells': int((accepted & (observed >= 2)).sum())},
|
|
'limitations': ['Partial observed surface; not a complete surveyed map',
|
|
'Unknown remains unknown; no hole filling', 'Crosswalk markings do not grant route permission',
|
|
'Gaussian depth is approximate; collision and live obstacles remain independent']}
|
|
write_json(output / 'urban-map.json', document)
|
|
export_dxf(document, output / 'urban-map.dxf')
|
|
return document
|
|
|
|
|
|
def export_dxf(document, path):
|
|
import ezdxf
|
|
drawing = ezdxf.new('R2013')
|
|
drawing.units = 6 # metres
|
|
for feature in document['features']:
|
|
name = feature['properties']['class']
|
|
if name not in drawing.layers:
|
|
layer = drawing.layers.new(name)
|
|
layer.rgb = tuple(feature['properties'].get('color', {'curb':[245,130,48], 'crosswalk_area':[255,225,35], 'crosswalk_marking':[255,225,35]}.get(name,[245,245,245])))
|
|
polygon = feature['geometry']['type'] == 'Polygon'
|
|
paths = feature['geometry']['coordinates'] if polygon else [feature['geometry']['coordinates']]
|
|
for ring in paths:
|
|
drawing.modelspace().add_polyline3d(ring[:-1] if polygon else ring, close=polygon, dxfattribs={'layer': name})
|
|
drawing.saveas(path)
|