"""Shared orthographic observations and explicit unknown/occluded ground. Only the original systematic render tiles are used. A perspective road label is not an input. Context/ground depth agreement is a conservative observation test, not proof of pavement semantics or traversability. """ from functools import lru_cache from pathlib import Path import hashlib import json import time import cv2 import numpy as np from PIL import Image from fit_scene import project, world from row_evidence import choose_owners from paint_channels_fast import paint_mask VERSION = 'orthographic-ground-observations-v8' POLICY = dict(marking_domain='visible-plan-xy',local_depth_span_role='height-quality-only',alpha_min=.85, depth_agreement_m=.12, local_depth_span_m=.18, local_window_px=5, window_m=16., stride_m=8., core_fraction=.03) PHOTOMETRY = dict(cell_m=.025,context_m=1.2,calibration_observability='visible-plan-xy-v1', calibration='one immutable object observation frame, before pose search', threshold='Otsu, floor 15; exclusive declared white/yellow channels; brightness unchanged', query='same paint samples for proposal, placement and every verifier', anchor='first-pass semantic association; never fitted geometry', background='3m median illumination; no minimum propagation from dark cracks', filter_halo_m=1.5,calibration_scope='immutable object frame only; halo excluded') def sha(path): h = hashlib.sha256() with Path(path).open('rb') as f: for chunk in iter(lambda: f.read(1024*1024), b''): h.update(chunk) return h.hexdigest() def geometric_support(context, ground): if not (np.allclose(context['view'], ground['view']) and np.allclose(context['intrinsics'], ground['intrinsics'])): raise ValueError('Context/ground camera mismatch') a, b = context['depth'], ground['depth'] finite = np.isfinite(a) & np.isfinite(b) & (a > 0) & (b > 0) # Opacity and depth have different domains. A low-opacity neighbour is # not a zero-metre surface. Keep all 25 finite geometric measurements for # the same span test; opacity still gates the evaluated point itself. # Missing/nonfinite geometry still invalidates its whole neighbourhood. safe = np.where(finite, b, 0).astype('float32') ratio=b.shape[0]/int(ground.get('compatibility_resolution',b.shape[0])) width=2*int(np.ceil((POLICY['local_window_px']-1)/2*ratio))+1 kernel = np.ones((width,)*2, 'uint8') neighborhood = cv2.erode(finite.astype('uint8'), kernel) > 0 span = cv2.dilate(safe, kernel) - cv2.erode(safe, kernel) return finite & neighborhood & (span <= POLICY['local_depth_span_m']) def ground_support(context, ground): return (geometric_support(context,ground) & (context['alpha'] >= POLICY['alpha_min']) & (ground['alpha'] >= POLICY['alpha_min']) & (np.abs(context['depth']-ground['depth']) <= POLICY['depth_agreement_m'])) def read(array, uv, *, nearest=False): uv = np.asarray(uv, 'float32') return np.concatenate([ cv2.remap(array, q[:, 0, None], q[:, 1, None], cv2.INTER_NEAREST if nearest else cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0).reshape(len(q), -1) for q in np.array_split(uv, max(1, int(np.ceil(len(uv)/20000))))]) def sample_ground_support(context, ground, uv, geometry_mask=None): valid=geometric_support(context,ground) if geometry_mask is None else geometry_mask geometry=read(valid.astype('uint8'),uv,nearest=True).ravel()>0 a=read(context['alpha'].astype('float32',copy=False),uv).ravel() b=read(ground['alpha'].astype('float32',copy=False),uv).ravel() gap=np.abs(read(context['depth'],uv).ravel()-read(ground['depth'],uv).ravel()) return geometry & (a>=POLICY['alpha_min']) & (b>=POLICY['alpha_min']) & (gap<=POLICY['depth_agreement_m']) def sample_visible_support(context,ground,uv): """Visibility of paint in XY, separate from continuity of expected depth.""" if not (np.allclose(context['view'],ground['view']) and np.allclose(context['intrinsics'],ground['intrinsics'])): raise ValueError('Context/ground camera mismatch') a=read(context['alpha'].astype('float32',copy=False),uv).ravel();b=read(ground['alpha'].astype('float32',copy=False),uv).ravel() x=read(context['depth'],uv).ravel();y=read(ground['depth'],uv).ravel() return (np.isfinite(x)&np.isfinite(y)&(x>0)&(y>0)&(a>=POLICY['alpha_min'])&(b>=POLICY['alpha_min'])& (np.abs(x-y)<=POLICY['depth_agreement_m'])) def surface_sample_evidence(context, ground, uv, geometry_mask=None): """Explain the existing veto; never repair, smooth or replace a measurement. RGB+ED is the alpha-weighted mean of Gaussian centre depths, not a measured opaque surface. A discontinuity here must remain unresolved unless another qualified geometric observation establishes the surface. High alpha alone cannot establish that geometry. """ uv=np.asarray(uv,'float32') if not len(uv):return [] accepted=sample_ground_support(context,ground,uv,geometry_mask) ca=read(context['alpha'].astype('float32',copy=False),uv).ravel() ga=read(ground['alpha'].astype('float32',copy=False),uv).ravel() cd=read(context['depth'],uv).ravel();gd=read(ground['depth'],uv).ravel() a,b=context['depth'],ground['depth'];height,width=b.shape radius=int(np.ceil((POLICY['local_window_px']-1)/2*height/int(ground.get('compatibility_resolution',height)))) rows=[] for i,(x,y) in enumerate(np.rint(uv).astype(int)): causes=[];span=None;finite=False if not (0<=x0)&(bb>0) finite=bool(valid.all()) if not finite:causes.append('missing_or_nonpositive_depth') else: span=float(np.ptp(bb)) if span>POLICY['local_depth_span_m']:causes.append('rendered_depth_span') if not ca[i]>=POLICY['alpha_min']:causes.append('context_opacity') if not ga[i]>=POLICY['alpha_min']:causes.append('ground_opacity') gap=float(abs(cd[i]-gd[i])) if not gap<=POLICY['depth_agreement_m']:causes.append('context_ground_disagreement') if bool(accepted[i]) != (not causes):raise AssertionError('Surface explanation changed the gate') rows.append(dict(pixel=[int(x),int(y)],accepted=bool(accepted[i]),causes=causes, context_alpha=float(ca[i]),ground_alpha=float(ga[i]),depth_gap_m=gap if np.isfinite(gap) else None, local_depth_span_m=span,finite_neighborhood=finite)) return rows def metric_grid(region,cell,context): # Observation coordinates belong to the world lattice, not to a SAM # bounding box. A subpixel change of a proposal must not move the samples # used to judge the same physical paint. low=np.floor((np.asarray(region.bounds[:2])-context)/cell).astype('int64') high=np.ceil((np.asarray(region.bounds[2:])+context)/cell).astype('int64') if np.max((high-low)*cell)>20:raise ValueError('Object grid exceeds bounded footprint') x,y=np.meshgrid(np.arange(low[0],high[0])*cell,np.arange(low[1],high[1])*cell) return dict(lo=low*cell,points=np.c_[x.ravel(),y.ravel()],size=x.shape,cell=cell) class GroundObservations: def __init__(self, ortho='/ortho'): self.timings=dict(raw_view_seconds=0.) self.root = Path(ortho) self.native=Path('/native_geometry') if Path('/native_geometry/native-geometry.json').is_file() else None if self.native and not json.loads((self.native/'native-geometry.json').read_text())['complete']: raise ValueError('Native observation set is incomplete') self.tiles = [t for t in json.loads((self.root/'survey/tile-index.json').read_text())['tiles'] if t['status'] == 'surveyed'] if not self.tiles: raise ValueError('No orthographic observations') self.centers = np.array([np.mean(t['bounds_xy'], axis=0) for t in self.tiles]) @lru_cache(maxsize=None) def camera(self, name): # Coverage needs 25 numbers, not two 1200x1200 raster planes. np.load # is lazy: loading only these entries avoids decompressing depth/alpha # for every tile again at every candidate and every grid cell. with np.load(self.root/'survey'/name/'top.geometry.npz') as z: return {key:z[key] for key in ['view','intrinsics']} @lru_cache(maxsize=12) def geometry(self, name, ground=False): path = (self.root/'evidence'/(name+'.ground-dc.geometry.npz') if ground else self.root/'survey'/name/'top.geometry.npz') if self.native: path=self.native/(name+('.ground.npz' if ground else '.context.npz')) with np.load(path) as z: return dict(z) @lru_cache(maxsize=12) def support(self, name): return geometric_support(self.geometry(name), self.geometry(name, True)) @lru_cache(maxsize=4) def rgb(self, name): with Image.open(self.root/'evidence'/(name+'.ground.png')) as im: return np.asarray(im.convert('RGB')) def metric_surface(self, name, points): context=self.geometry(name);ground=self.geometry(name,True) uv=project(points,self.camera(name)) if self.native:uv=(uv+.5)*context['depth'].shape[0]/1200-.5 return sample_ground_support(context,ground,uv,self.support(name)) def surface(self,name,points): context=self.geometry(name);ground=self.geometry(name,True) uv=project(points,self.camera(name)) if self.native:uv=(uv+.5)*context['depth'].shape[0]/1200-.5 return sample_visible_support(context,ground,uv) def depth_quality(self,grid,polygon): import shapely points=grid['points'];target=shapely.contains_xy(polygon,points[:,0],points[:,1]);records=[] for rank,view in enumerate(grid['views']): known=target&view['observed'].ravel();owners=view['tile_indices'].ravel();stable=0 for owner in np.unique(owners[known]): selected=known&(owners==owner);name=self.tiles[int(owner)]['id'] stable+=int(self.metric_surface(name,points[selected]).sum()) records.append(dict(rank=rank,observed_samples=int(known.sum()),continuous_depth_samples=stable, continuous_depth_fraction=stable/int(known.sum()) if known.any() else None)) return dict(domain='Gaussian expected-depth continuity; not physical survey',records=records, affects_xy_admission=False,height_field_certified=False) def explain_object_surface(self, grid, polygon, pose): """Bounded final diagnostics from the same pixels; not a search objective.""" import collections import shapely points=grid['points'];inside=shapely.contains_xy(polygon,points[:,0],points[:,1]) if not inside.any():return [] t=(points-np.asarray(pose[:2]))@np.array([np.cos(pose[2]),np.sin(pose[2])]) masks=dict(object=inside,tail=inside&(tt[inside].max()-.20)) records=[] for rank,view in enumerate(grid['views']): owners=view['tile_indices'].ravel();known=view['observed'].ravel();allowed=view['allowed'].ravel() measurements={} indices=np.flatnonzero(inside&known&~allowed) for owner in np.unique(owners[indices]): selected=indices[owners[indices]==owner];name=self.tiles[int(owner)]['id'] context=self.geometry(name);ground=self.geometry(name,True) uv=project(points[selected],self.camera(name)) if self.native:uv=(uv+.5)*context['depth'].shape[0]/1200-.5 rows=surface_sample_evidence(context,ground,uv,self.support(name)) for index,row in zip(selected,rows):measurements[int(index)]=dict(row,tile=name,world_xy=points[index].tolist()) for part,mask in masks.items(): selected=mask&known;bad=np.flatnonzero(selected&~allowed) counts=collections.Counter(c for i in bad for c in measurements[int(i)]['causes']) spans=[measurements[int(i)]['local_depth_span_m'] for i in bad if measurements[int(i)]['local_depth_span_m'] is not None] records.append(dict(rank=rank,part=part,samples=int(mask.sum()),observed_samples=int(selected.sum()),valid_samples=int((selected&allowed).sum()), rejected_samples=len(bad),cause_counts=dict(counts),max_rejected_span_m=max(spans) if spans else None, examples=[measurements[int(i)] for i in bad[:8]],depth_semantics='alpha-weighted-Gaussian-centre-depth', physical_surface_cause='not_identified_from_rendered_depth_alone' if len(bad) else None, corrective_pose_search_authorized_by_diagnostic=False)) return records def inventory(self): paths = [self.root/'survey/tile-index.json'] for t in self.tiles: n = t['id'] paths.extend([self.root/'survey'/n/'top.geometry.npz', self.root/'evidence'/(n+'.ground-dc.geometry.npz'), self.root/'evidence'/(n+'.ground.png')]) files = {p.relative_to(self.root).as_posix(): sha(p) for p in paths} if self.native: manifest=json.loads((self.native/'native-geometry.json').read_text()) if manifest['tiles']!=len(self.tiles):raise ValueError('Native survey coverage mismatch') for r in manifest['records']: value=sha(self.native/r['file']) if value!=r['sha256']:raise ValueError('Native geometry bytes changed') files['native-geometry/'+r['file']]=value return dict(version=VERSION, policy=POLICY, photometry=PHOTOMETRY, files=files, snapshot=hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest(), perspective_input=False, independent_acquisitions=False) def raw_views(self,lattice): started=time.monotonic() points=lattice['points'];size=lattice['size'] # Reject only cameras whose projected world rectangle cannot overlap. # This is a broad-phase geometric test, independent of image content. low=points.min(0);high=points.max(0) corners=np.array([low,[high[0],low[1]],high,[low[0],high[1]]]) indices=[] for i,tile in enumerate(self.tiles): uv=project(corners,self.camera(tile['id'])) if np.any(uv.max(0)<20) or np.any(uv.min(0)>=1180):continue indices.append(i) distance=np.linalg.norm(points[:,None]-self.centers[indices][None],axis=2) cover=np.zeros(distance.shape,bool) for j,i in enumerate(indices): uv=project(points,self.camera(self.tiles[i]['id'])) cover[:,j]=(uv.min(1)>=20)&(uv.max(1)<1180) if indices: local_owners=choose_owners(distance,cover) owners=np.full(local_owners.shape,-1,int) present=local_owners>=0 owners[present]=np.asarray(indices)[local_owners[present]] else:owners=np.full((len(points),2),-1,int) rows=[] for rank in range(2): rgb=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool) observed=owners[:,rank]>=0;names=[] for i in np.unique(owners[:,rank]): if i<0:continue ix=np.flatnonzero(owners[:,rank]==i) name=self.tiles[i]['id'];names.append(name) raw=self.rgb(name);uv=project(points[ix],self.camera(name)) native=(uv+.5)*np.array(raw.shape[1::-1])/1200-.5 rgb[ix]=read(raw,native);allowed[ix]=self.surface(name,points[ix]) rows.append(dict(rgb=rgb.reshape(*size,3),allowed=allowed.reshape(size), observed=observed.reshape(size),names=names,tile_indices=owners[:,rank].reshape(size))) if hasattr(self,'timings'):self.timings['raw_view_seconds']+=time.monotonic()-started return rows @lru_cache(maxsize=128) def object_frame(self,wkb): import shapely region=shapely.from_wkb(wkb);cell=PHOTOMETRY['cell_m'];context=PHOTOMETRY['context_m'] coarse=metric_grid(region,.04,context) low=coarse['points'].min(0);high=coarse['points'].max(0) fine=metric_grid(shapely.box(*low,*high),cell,cell) # A spatial filter must see its whole physical neighbourhood. Padding # belongs to acquisition, never to the object/calibration domain. pad=int(round(PHOTOMETRY['filter_halo_m']/cell));height,width=fine['size'] start=np.rint(fine['lo']/cell).astype(int)-pad x,y=np.meshgrid(np.arange(start[0],start[0]+width+2*pad)*cell, np.arange(start[1],start[1]+height+2*pad)*cell) expanded=dict(lo=start*cell,points=np.c_[x.ravel(),y.ravel()],size=x.shape,cell=cell) surrounding=self.raw_views(expanded);views=[];crop=(slice(pad,pad+height),slice(pad,pad+width)) scope=shapely.contains_xy(region.buffer(.2),fine['points'][:,0],fine['points'][:,1]).reshape(fine['size']) for raw in surrounding: calibration=np.zeros(expanded['size'],bool);calibration[crop]=raw['allowed'][crop] measured=paint_mask(raw['rgb'],cell=cell,observed=raw['observed'],calibration=calibration,background='median') view={key:raw[key][crop].copy() for key in ['rgb','allowed','observed','tile_indices'] if key in raw} paint=measured[crop].copy();view.update(paint=paint,target=paint&view['allowed']&scope,names=raw['names']) views.append(view) fine['views']=views coarse_views=self.raw_views(coarse) uv=np.rint((coarse['points']-fine['lo'])/cell).astype(int) inside=(uv>=0).all(1)&(uv