refactor(767-1): 안 쓰는 지면 필터 · 서피스 지움 — 필터 넷(CSF · 격자 최저 · PMF · RANSAC) · 표현 셋(TIN + Taubin 평활 · NURBS · meshfree) · 수치지형도 비교 방식 다섯 · 안 부르는 길 정리
- 필터 = 업체 분류 · 점진 TIN · 둘의 다듬기 판만 · 분석 허용 목록 = Ground 등록부(available_filters) 한 벌 - 표현 = DTM · implicit 만 · 평활 = DTM 만 · config 기본 목록 · PRECOMPUTE · 설정 사전 맞춤(설정 지문 바뀜 — 768 에서 다시 지음) - 등고선 = 격자 · 굳힌 격자만(삼각망 굽기 · 외곽 맞춤 · implicit RBF 폴백 걷음) · 표본기 · 경로 찾기 tin · nurbs · meshfree 갈래 걷음 - 수치지형도 = 라플라스만(TIN 둘 · TPS · ANUDEM형 · 다중해상도 걷음) · B04 단추 하나 - 안 부르는 길 — B04 JSON 점군 GET · ground-stats GET + TS · B07 옛 계획평면도(라이다) 짓기 · lidar_source · LIDAR_ID · plan_lidar 종류 이름 · SOURCE_FILTER_LABELS · MODEL_METHODS(py) · MESH_* 설정 - 옛 manifest 의 지운 갈래 줄은 DB 로 되살리지 않음 · 옛 csf 행은 미리보기 · 등고선 그대로 열림 · 지운 이름 요청 = 400 - 낡은 글 — Ground · Pipeline 머리 · WF1 「없으면 csf」 · B07 음영 기본 「csf」 → 빈 값 · 등고선 폴백 「csf」 → 404 · B04 3D 보기 처음값 · B05 Schema · B06 Prebuild · 씨닝 설명 - 시험 지움 2 — test_b04_contour_raster · test_b04_contour_equivalence(지운 삼각망 굽기 · 없는 프로젝트를 봐 건너뛰던 것) - 시험 덜어냄 — test_b04_ground_filters CSF · 격자 최저 네 경우(지운 필터) - 시험 고침 — 허용 목록 · 형 검사에 걸린 csf · tin · grid_min_z · meshfree · tin_sheet 견본을 ptd · implicit · laplace 로(54_22 · 238_1 · 443 · 342_2 · 346_3 · 351_1 · 442_2 · 271 + helper · 344_1 · 133_1 · 343_2 · 637 · 754_1 · 763_1 깨진 tin → 깨진 implicit · 763_3 · b05 둘 · b06 · sheet_surface TIN(도엽선) 경우 지움) · 이름만 바꿈(273_2 · 343_1 · 343_3 · 624_1) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,16 +1,13 @@
|
||||
"""B04 등고선 추출 엔진.
|
||||
|
||||
5종 표현(regular_grid/triangular_mesh/bspline_surface/local_rbf_height_field/
|
||||
meshfree_surfels)의 npz 모델에서 표고 격자를 환원하고, marching squares로
|
||||
지정 간격 등고선 라인을 추출한다. DTM valid_mask를 footprint로 사용해
|
||||
경계 누출을 차단한다.
|
||||
표현(regular_grid · local_rbf_height_field 굳힌 격자)의 표고 격자에서 marching
|
||||
squares로 지정 간격 등고선 라인을 추출한다. 격자 valid_mask가 경계 누출을 막는다.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from scipy.interpolate import RBFInterpolator
|
||||
from skimage import measure
|
||||
|
||||
# 등고선 캐시 형식/추출 규칙이 바뀔 때 증가시킨다.
|
||||
@@ -139,233 +136,6 @@ def contour_cache_is_stale(contour_path: Path, model_path: Path) -> bool:
|
||||
return any(path.is_file() and path.stat().st_mtime_ns > built for path in sources)
|
||||
|
||||
|
||||
def _load_footprint_mask(
|
||||
model_npz_path: Path, x_coords: np.ndarray, y_coords: np.ndarray
|
||||
) -> np.ndarray | None:
|
||||
"""같은 source filter의 DTM valid_mask를 현재 격자에 최근접 리샘플한다."""
|
||||
stem = Path(model_npz_path).stem
|
||||
if stem.endswith("_smooth"):
|
||||
stem = stem[:-7]
|
||||
parts = stem.split("_", 1)
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
filter_key = parts[1]
|
||||
dtm_path = Path(model_npz_path).parent / f"dtm_{filter_key}.npz"
|
||||
if not dtm_path.exists():
|
||||
return None
|
||||
try:
|
||||
with np.load(dtm_path) as d:
|
||||
dtm_x = np.asarray(d["x"]).ravel()
|
||||
dtm_y = np.asarray(d["y"]).ravel()
|
||||
dtm_mask = np.asarray(d["valid_mask"], dtype=bool)
|
||||
except Exception:
|
||||
return None
|
||||
if len(dtm_x) < 2 or len(dtm_y) < 2:
|
||||
return None
|
||||
|
||||
def _nearest_idx(axis: np.ndarray, coords: np.ndarray) -> np.ndarray:
|
||||
ascending = bool(axis[0] <= axis[-1])
|
||||
a = axis if ascending else axis[::-1]
|
||||
idx = np.clip(np.searchsorted(a, coords), 1, len(a) - 1)
|
||||
idx = np.where(np.abs(a[idx - 1] - coords) <= np.abs(a[idx] - coords), idx - 1, idx)
|
||||
return idx if ascending else (len(axis) - 1 - idx)
|
||||
|
||||
xi = _nearest_idx(dtm_x, np.asarray(x_coords, dtype=np.float64))
|
||||
yi = _nearest_idx(dtm_y, np.asarray(y_coords, dtype=np.float64))
|
||||
return dtm_mask[np.ix_(yi, xi)]
|
||||
|
||||
|
||||
def _apply_footprint(
|
||||
model_npz_path: Path, x_coords: np.ndarray, y_coords: np.ndarray, valid_mask: np.ndarray
|
||||
) -> np.ndarray:
|
||||
"""valid_mask에 DTM footprint를 교집합으로 적용한다 (형상 다르면 최근접 리샘플)."""
|
||||
fp = _load_footprint_mask(model_npz_path, x_coords, y_coords)
|
||||
if fp is not None:
|
||||
if fp.shape == valid_mask.shape:
|
||||
return valid_mask & fp
|
||||
from scipy.ndimage import zoom
|
||||
|
||||
zoom_y = valid_mask.shape[0] / fp.shape[0]
|
||||
zoom_x = valid_mask.shape[1] / fp.shape[1]
|
||||
fp_resized = zoom(fp.astype(float), (zoom_y, zoom_x), order=0) > 0.5
|
||||
if fp_resized.shape == valid_mask.shape:
|
||||
return valid_mask & fp_resized
|
||||
return valid_mask
|
||||
|
||||
|
||||
def _tin_face_coverage_mask(
|
||||
vertices: np.ndarray, faces: np.ndarray, xx: np.ndarray, yy: np.ndarray
|
||||
) -> np.ndarray:
|
||||
"""저장된 TIN 면이 실제로 덮는 XY 영역만 True로 반환한다."""
|
||||
vertices = np.asarray(vertices)
|
||||
faces = np.asarray(faces, dtype=np.int64)
|
||||
if vertices.ndim != 2 or vertices.shape[1] < 2 or not len(faces):
|
||||
return np.zeros(xx.shape, dtype=bool)
|
||||
|
||||
edges = np.vstack((faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]))
|
||||
edges = np.sort(edges, axis=1)
|
||||
unique_edges, counts = np.unique(edges, axis=0, return_counts=True)
|
||||
boundary_edges = unique_edges[counts == 1]
|
||||
if not len(boundary_edges):
|
||||
return np.zeros(xx.shape, dtype=bool)
|
||||
|
||||
import affine
|
||||
import rasterio.features
|
||||
from shapely import get_parts, linestrings, polygonize
|
||||
|
||||
boundary_lines = linestrings(vertices[boundary_edges, :2])
|
||||
polygons = list(get_parts(polygonize(boundary_lines)))
|
||||
if not polygons:
|
||||
return np.zeros(xx.shape, dtype=bool)
|
||||
|
||||
x_coords = xx[0, :]
|
||||
y_coords = yy[:, 0]
|
||||
dx = float(x_coords[1] - x_coords[0]) if len(x_coords) > 1 else 1.0
|
||||
dy = float(y_coords[1] - y_coords[0]) if len(y_coords) > 1 else 1.0
|
||||
|
||||
transform = affine.Affine(dx, 0.0, x_coords[0] - dx / 2.0, 0.0, dy, y_coords[0] - dy / 2.0)
|
||||
|
||||
mask = rasterio.features.rasterize(
|
||||
polygons, out_shape=xx.shape, transform=transform, fill=0, default_value=1, dtype="uint8"
|
||||
)
|
||||
return mask.astype(bool)
|
||||
|
||||
|
||||
def _grid_axes(x_min: float, x_max: float, y_min: float, y_max: float, target_grid_m: float):
|
||||
cols = max(2, int(np.ceil((x_max - x_min) / target_grid_m)) + 1)
|
||||
rows = max(2, int(np.ceil((y_max - y_min) / target_grid_m)) + 1)
|
||||
x_coords = np.linspace(x_min, x_max, cols, dtype=np.float32)
|
||||
y_coords = np.linspace(y_min, y_max, rows, dtype=np.float32)
|
||||
return x_coords, y_coords
|
||||
|
||||
|
||||
# 후보 셀 배열이 한 번에 커지지 않도록 삼각형을 나눠 처리하는 단위.
|
||||
_RASTER_CHUNK = 200_000
|
||||
# 격자점이 변 위에 놓였을 때 양쪽 삼각형 모두에서 탈락하지 않도록 두는 여유.
|
||||
_BARYCENTRIC_EPS = 1e-9
|
||||
|
||||
|
||||
def rasterize_triangle_mesh(
|
||||
vertices: np.ndarray,
|
||||
triangles: np.ndarray,
|
||||
x_coords: np.ndarray,
|
||||
y_coords: np.ndarray,
|
||||
) -> np.ndarray:
|
||||
"""삼각망을 규칙격자에 직접 래스터화해 표고 격자를 만든다.
|
||||
|
||||
삼각형마다 자기가 덮는 격자 셀만 무게중심 선형보간으로 채우므로, 질의점별
|
||||
위치탐색(scipy `find_simplex`)이 사라진다. 삼각망 밖 셀은 NaN으로 남아
|
||||
기존 `griddata` 결과와 같은 유효 판정을 유지한다.
|
||||
"""
|
||||
rows, cols = len(y_coords), len(x_coords)
|
||||
z_grid = np.full((rows, cols), np.nan, dtype=np.float64)
|
||||
vertices = np.asarray(vertices, dtype=np.float64)
|
||||
triangles = np.asarray(triangles, dtype=np.int64)
|
||||
if not len(triangles) or vertices.ndim != 2 or vertices.shape[1] < 3:
|
||||
return z_grid
|
||||
|
||||
axis_x = np.asarray(x_coords, dtype=np.float64)
|
||||
axis_y = np.asarray(y_coords, dtype=np.float64)
|
||||
|
||||
def _index_range(axis: np.ndarray, low: np.ndarray, high: np.ndarray, size: int):
|
||||
"""축 배열을 직접 탐색해 [low, high]를 덮는 인덱스 구간을 낸다.
|
||||
|
||||
`(좌표 - 원점) / 간격` 식은 쓰지 않는다. `_grid_axes`가 float32 축을 만드는데
|
||||
UTM 좌표(18만대)에서 float32 해상도가 0.015625m라 격자 간격이 0.984~1.0으로
|
||||
흔들리고, 등간격으로 환산하면 최대 0.81셀까지 어긋난다. 삼각형이 평균 0.3m라
|
||||
그만큼 어긋나면 격자점을 통째로 놓친다 (2026-08-17 실측).
|
||||
"""
|
||||
ascending = size < 2 or axis[-1] >= axis[0]
|
||||
sorted_axis = axis if ascending else axis[::-1]
|
||||
lo = np.searchsorted(sorted_axis, low, side="left")
|
||||
hi = np.searchsorted(sorted_axis, high, side="right") - 1
|
||||
if ascending:
|
||||
return lo, hi
|
||||
return size - 1 - hi, size - 1 - lo
|
||||
|
||||
for begin in range(0, len(triangles), _RASTER_CHUNK):
|
||||
chunk = triangles[begin : begin + _RASTER_CHUNK]
|
||||
corners = vertices[chunk]
|
||||
ax, ay, az = corners[:, 0, 0], corners[:, 0, 1], corners[:, 0, 2]
|
||||
bx, by, bz = corners[:, 1, 0], corners[:, 1, 1], corners[:, 1, 2]
|
||||
cx, cy, cz = corners[:, 2, 0], corners[:, 2, 1], corners[:, 2, 2]
|
||||
|
||||
denom = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy)
|
||||
col_lo, col_hi = _index_range(
|
||||
axis_x, np.minimum(np.minimum(ax, bx), cx), np.maximum(np.maximum(ax, bx), cx), cols
|
||||
)
|
||||
row_lo, row_hi = _index_range(
|
||||
axis_y, np.minimum(np.minimum(ay, by), cy), np.maximum(np.maximum(ay, by), cy), rows
|
||||
)
|
||||
|
||||
# 클립 전에 격자 밖 삼각형을 걸러야 경계에 눌러붙지 않는다.
|
||||
selected = (
|
||||
np.isfinite(denom)
|
||||
& (np.abs(denom) > 1e-12)
|
||||
& (col_hi >= col_lo)
|
||||
& (row_hi >= row_lo)
|
||||
& (col_hi >= 0)
|
||||
& (row_hi >= 0)
|
||||
& (col_lo <= cols - 1)
|
||||
& (row_lo <= rows - 1)
|
||||
)
|
||||
if not selected.any():
|
||||
continue
|
||||
|
||||
col_lo = np.clip(col_lo[selected], 0, cols - 1).astype(np.int64)
|
||||
col_hi = np.clip(col_hi[selected], 0, cols - 1).astype(np.int64)
|
||||
row_lo = np.clip(row_lo[selected], 0, rows - 1).astype(np.int64)
|
||||
row_hi = np.clip(row_hi[selected], 0, rows - 1).astype(np.int64)
|
||||
width = col_hi - col_lo + 1
|
||||
counts = width * (row_hi - row_lo + 1)
|
||||
total = int(counts.sum())
|
||||
if total <= 0:
|
||||
continue
|
||||
|
||||
# 삼각형별 후보 셀 수가 제각각이라 반복 인덱스를 펼쳐서 한 번에 계산한다.
|
||||
starts = np.concatenate(([0], np.cumsum(counts)[:-1]))
|
||||
local = np.arange(total, dtype=np.int64) - np.repeat(starts, counts)
|
||||
width_rep = np.repeat(width, counts)
|
||||
offset_row = local // width_rep
|
||||
cell_row = np.repeat(row_lo, counts) + offset_row
|
||||
cell_col = np.repeat(col_lo, counts) + (local - offset_row * width_rep)
|
||||
|
||||
point_x = axis_x[cell_col]
|
||||
point_y = axis_y[cell_row]
|
||||
ax_r, ay_r, az_r = (
|
||||
np.repeat(ax[selected], counts),
|
||||
np.repeat(ay[selected], counts),
|
||||
np.repeat(az[selected], counts),
|
||||
)
|
||||
bx_r, by_r, bz_r = (
|
||||
np.repeat(bx[selected], counts),
|
||||
np.repeat(by[selected], counts),
|
||||
np.repeat(bz[selected], counts),
|
||||
)
|
||||
cx_r, cy_r, cz_r = (
|
||||
np.repeat(cx[selected], counts),
|
||||
np.repeat(cy[selected], counts),
|
||||
np.repeat(cz[selected], counts),
|
||||
)
|
||||
denom_r = np.repeat(denom[selected], counts)
|
||||
|
||||
weight_a = ((by_r - cy_r) * (point_x - cx_r) + (cx_r - bx_r) * (point_y - cy_r)) / denom_r
|
||||
weight_b = ((cy_r - ay_r) * (point_x - cx_r) + (ax_r - cx_r) * (point_y - cy_r)) / denom_r
|
||||
weight_c = 1.0 - weight_a - weight_b
|
||||
hit = (
|
||||
(weight_a >= -_BARYCENTRIC_EPS)
|
||||
& (weight_b >= -_BARYCENTRIC_EPS)
|
||||
& (weight_c >= -_BARYCENTRIC_EPS)
|
||||
)
|
||||
if not hit.any():
|
||||
continue
|
||||
z_grid[cell_row[hit], cell_col[hit]] = (
|
||||
weight_a[hit] * az_r[hit] + weight_b[hit] * bz_r[hit] + weight_c[hit] * cz_r[hit]
|
||||
)
|
||||
|
||||
return z_grid
|
||||
|
||||
|
||||
def extract_contours(
|
||||
model_npz_path: Path,
|
||||
representation: str,
|
||||
@@ -415,102 +185,19 @@ def _extract_loaded(
|
||||
x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center
|
||||
)
|
||||
|
||||
if representation == "triangular_mesh":
|
||||
vertices, faces = data["vertices"], data["faces"]
|
||||
x_min, x_max = float(np.min(vertices[:, 0])), float(np.max(vertices[:, 0]))
|
||||
y_min, y_max = float(np.min(vertices[:, 1])), float(np.max(vertices[:, 1]))
|
||||
x_coords, y_coords = _grid_axes(x_min, x_max, y_min, y_max, target_grid_m)
|
||||
xx, yy = np.meshgrid(x_coords, y_coords)
|
||||
# 저장된 faces를 그대로 쓴다 — griddata는 정점을 다시 삼각분할하느라 긴 변
|
||||
# 제거·외곽 클리핑이 반영되지 않은 면까지 되살렸다 (PLAN 2026-08-17).
|
||||
z_grid = rasterize_triangle_mesh(vertices, faces, x_coords, y_coords)
|
||||
face_mask = _tin_face_coverage_mask(vertices, faces, xx, yy)
|
||||
valid_mask = np.isfinite(z_grid) & face_mask
|
||||
valid_mask = _apply_footprint(model_npz_path, x_coords, y_coords, valid_mask)
|
||||
return extract_contours_from_grid(
|
||||
x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center
|
||||
)
|
||||
|
||||
if representation == "bspline_surface":
|
||||
# 모델 빌더와 같은 곡면을 다시 만든다 — 평활 계수·발산 방어를 공유한다.
|
||||
from B04_PreProcess.B04_PreProcess_Engine_ModelContext import (
|
||||
evaluate_nurbs_spline,
|
||||
fit_nurbs_spline,
|
||||
)
|
||||
|
||||
control_x, control_y, control_z = data["control_x"], data["control_y"], data["control_z"]
|
||||
degree = int(data["degree"][0])
|
||||
spline, z_range = fit_nurbs_spline(control_x, control_y, control_z, degree)
|
||||
x_coords, y_coords = _grid_axes(
|
||||
float(control_x[0]),
|
||||
float(control_x[-1]),
|
||||
float(control_y[0]),
|
||||
float(control_y[-1]),
|
||||
target_grid_m,
|
||||
)
|
||||
z_grid = evaluate_nurbs_spline(
|
||||
spline, y_coords, x_coords, z_range, Path(model_npz_path).stem
|
||||
).astype(np.float32)
|
||||
valid_mask = _apply_footprint(
|
||||
model_npz_path, x_coords, y_coords, np.ones_like(z_grid, dtype=bool)
|
||||
)
|
||||
return extract_contours_from_grid(
|
||||
x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center
|
||||
)
|
||||
|
||||
if representation == "local_rbf_height_field":
|
||||
# 굳힌 격자(641-1)가 있으면 그 면 그대로 — 등고선 = 서버 표본 · 종횡단과 같은 면(643)
|
||||
# 굳힌 격자(641-1) 그대로 — 등고선 = 서버 표본 · 종횡단과 같은 면(643) · dtm 늘 먼저(754-1)
|
||||
from common_util.common_util_surface_sampler import implicit_grid_npz
|
||||
|
||||
filter_key = model_npz_path.stem.removeprefix("implicit_")
|
||||
if (model_npz_path.parent / f"dtm_{filter_key}.npz").is_file():
|
||||
from common_util.common_util_surface_sampler import implicit_grid_npz
|
||||
|
||||
with np.load(implicit_grid_npz(model_npz_path.parent, filter_key)) as grid:
|
||||
return extract_contours_from_grid(
|
||||
grid["x"],
|
||||
grid["y"],
|
||||
grid["z"],
|
||||
grid["valid_mask"],
|
||||
interval,
|
||||
scene_center=scene_center,
|
||||
)
|
||||
centers_xy, center_z = data["centers_xy"], data["center_z"]
|
||||
smoothing = float(data["smoothing"][0])
|
||||
interpolator = RBFInterpolator(
|
||||
centers_xy.astype(np.float64),
|
||||
center_z.astype(np.float64),
|
||||
neighbors=min(64, len(centers_xy)),
|
||||
smoothing=smoothing,
|
||||
kernel="thin_plate_spline",
|
||||
)
|
||||
x_min, x_max = float(np.min(centers_xy[:, 0])), float(np.max(centers_xy[:, 0]))
|
||||
y_min, y_max = float(np.min(centers_xy[:, 1])), float(np.max(centers_xy[:, 1]))
|
||||
x_coords, y_coords = _grid_axes(x_min, x_max, y_min, y_max, target_grid_m)
|
||||
xx, yy = np.meshgrid(x_coords, y_coords)
|
||||
z_values = interpolator(np.column_stack([xx.ravel(), yy.ravel()])).astype(np.float32)
|
||||
z_grid = z_values.reshape(len(y_coords), len(x_coords))
|
||||
valid_mask = _apply_footprint(
|
||||
model_npz_path, x_coords, y_coords, np.ones_like(z_grid, dtype=bool)
|
||||
)
|
||||
return extract_contours_from_grid(
|
||||
x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center
|
||||
)
|
||||
|
||||
if representation == "meshfree_surfels":
|
||||
from scipy.spatial import Delaunay
|
||||
|
||||
points = data["points"]
|
||||
x_min, x_max = float(np.min(points[:, 0])), float(np.max(points[:, 0]))
|
||||
y_min, y_max = float(np.min(points[:, 1])), float(np.max(points[:, 1]))
|
||||
x_coords, y_coords = _grid_axes(x_min, x_max, y_min, y_max, target_grid_m)
|
||||
# Delaunay 1회로 삼각분할과 hull 판정을 함께 해결한다. 기존에는 griddata가
|
||||
# 내부에서 한 번, hull 판정용으로 또 한 번 만들었다 (PLAN 2026-08-17).
|
||||
triangulation = Delaunay(np.asarray(points[:, :2], dtype=np.float64))
|
||||
z_grid = rasterize_triangle_mesh(points, triangulation.simplices, x_coords, y_coords)
|
||||
# hull 밖은 어느 삼각형에도 안 닿아 NaN으로 남는다 = 기존 hull_inside와 같다.
|
||||
valid_mask = np.isfinite(z_grid)
|
||||
valid_mask = _apply_footprint(model_npz_path, x_coords, y_coords, valid_mask)
|
||||
return extract_contours_from_grid(
|
||||
x_coords, y_coords, z_grid, valid_mask, interval, scene_center=scene_center
|
||||
)
|
||||
with np.load(implicit_grid_npz(model_npz_path.parent, filter_key)) as grid:
|
||||
return extract_contours_from_grid(
|
||||
grid["x"],
|
||||
grid["y"],
|
||||
grid["z"],
|
||||
grid["valid_mask"],
|
||||
interval,
|
||||
scene_center=scene_center,
|
||||
)
|
||||
|
||||
raise ValueError(f"지원하지 않는 표현 방식입니다: {representation}")
|
||||
|
||||
Reference in New Issue
Block a user