- 필터 = 업체 분류 · 점진 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>
204 lines
7.6 KiB
Python
204 lines
7.6 KiB
Python
"""B04 등고선 추출 엔진.
|
|
|
|
표현(regular_grid · local_rbf_height_field 굳힌 격자)의 표고 격자에서 marching
|
|
squares로 지정 간격 등고선 라인을 추출한다. 격자 valid_mask가 경계 누출을 막는다.
|
|
"""
|
|
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import numpy as np
|
|
from skimage import measure
|
|
|
|
# 등고선 캐시 형식/추출 규칙이 바뀔 때 증가시킨다.
|
|
CONTOUR_EXTRACTOR_VERSION = 4
|
|
|
|
|
|
def extract_contours_from_grid(
|
|
x_coords: np.ndarray,
|
|
y_coords: np.ndarray,
|
|
z_grid: np.ndarray,
|
|
valid_mask: np.ndarray | None,
|
|
interval: float,
|
|
min_interval: float = 0.5,
|
|
scene_center: tuple[float, float, float] | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""정규 표고 격자로부터 등고선 라인을 추출한다."""
|
|
interval = max(interval, min_interval)
|
|
finite_mask = np.isfinite(z_grid)
|
|
if valid_mask is not None:
|
|
finite_mask &= valid_mask
|
|
if not finite_mask.any():
|
|
return []
|
|
|
|
z_min = float(np.min(z_grid[finite_mask]))
|
|
z_max = float(np.max(z_grid[finite_mask]))
|
|
span = z_max - z_min
|
|
if span <= 0:
|
|
return []
|
|
# 레벨 수 상한은 arange **앞에서** 건다. 뒤에 두면 표고 범위가 비정상적으로 넓을 때
|
|
# np.arange가 배열을 만들다 "Maximum allowed size exceeded"로 먼저 터진다.
|
|
if span / interval > 500:
|
|
interval = span / 100.0
|
|
start_level = np.ceil(z_min / interval) * interval
|
|
levels = np.arange(start_level, z_max, interval)
|
|
if len(levels) == 0:
|
|
return []
|
|
|
|
contours_geojson_list: list[dict[str, Any]] = []
|
|
|
|
# marching squares의 NaN 문제 예방: 무효 영역을 sentinel(z_min-1000)로 채운다.
|
|
z_grid_masked = z_grid.copy()
|
|
if valid_mask is not None:
|
|
z_grid_masked[~valid_mask] = z_min - 1000.0
|
|
invalid_mask = ~np.isfinite(z_grid_masked)
|
|
if invalid_mask.any():
|
|
z_grid_masked[invalid_mask] = z_min - 1000.0
|
|
|
|
cx, cy, cz = scene_center if scene_center is not None else (0.0, 0.0, 0.0)
|
|
|
|
for level in levels:
|
|
for contour in measure.find_contours(z_grid_masked, level):
|
|
current_segment: list[list[float]] = []
|
|
for y_idx, x_idx in contour:
|
|
x_idx_c = np.clip(x_idx, 0, len(x_coords) - 1)
|
|
y_idx_c = np.clip(y_idx, 0, len(y_coords) - 1)
|
|
x_0, x_1 = int(np.floor(x_idx_c)), int(np.ceil(x_idx_c))
|
|
y_0, y_1 = int(np.floor(y_idx_c)), int(np.ceil(y_idx_c))
|
|
|
|
is_valid = True
|
|
if valid_mask is not None and not (
|
|
valid_mask[y_0, x_0]
|
|
and valid_mask[y_0, x_1]
|
|
and valid_mask[y_1, x_0]
|
|
and valid_mask[y_1, x_1]
|
|
):
|
|
is_valid = False
|
|
|
|
if not is_valid:
|
|
if len(current_segment) >= 2:
|
|
mid_idx = len(current_segment) // 2
|
|
contours_geojson_list.append(
|
|
{
|
|
"level": float(level),
|
|
"coordinates": current_segment,
|
|
"label_position": current_segment[mid_idx],
|
|
}
|
|
)
|
|
current_segment = []
|
|
continue
|
|
|
|
tx = x_idx_c - x_0
|
|
ty = y_idx_c - y_0
|
|
x_val = (1.0 - tx) * x_coords[x_0] + tx * x_coords[x_1]
|
|
y_val = (1.0 - ty) * y_coords[y_0] + ty * y_coords[y_1]
|
|
|
|
if scene_center is not None:
|
|
current_segment.append(
|
|
[
|
|
round(float(x_val - cx), 3),
|
|
round(float(level - cz), 3),
|
|
round(float(-(y_val - cy)), 3),
|
|
]
|
|
)
|
|
else:
|
|
current_segment.append(
|
|
[round(float(x_val), 3), round(float(y_val), 3), round(float(level), 3)]
|
|
)
|
|
|
|
if len(current_segment) >= 2:
|
|
mid_idx = len(current_segment) // 2
|
|
contours_geojson_list.append(
|
|
{
|
|
"level": float(level),
|
|
"coordinates": current_segment,
|
|
"label_position": current_segment[mid_idx],
|
|
}
|
|
)
|
|
|
|
return contours_geojson_list
|
|
|
|
|
|
def contour_cache_is_stale(contour_path: Path, model_path: Path) -> bool:
|
|
"""등고선 캐시가 없거나 그 면을 낳은 파일보다 옛것이면 True(754-1).
|
|
|
|
낳은 파일 = 모델 npz · 같은 필터 `dtm_{필터}.npz`(외곽 자르기) · implicit 굳힌 격자.
|
|
"""
|
|
stem = Path(model_path).stem.removesuffix("_smooth")
|
|
folder = Path(model_path).parent
|
|
sources = [Path(model_path), folder / f"dtm_{stem.split('_', 1)[-1]}.npz"]
|
|
if stem.startswith("implicit_"):
|
|
sources.append(folder / f"{stem}_grid.npz")
|
|
try:
|
|
built = Path(contour_path).stat().st_mtime_ns
|
|
except OSError:
|
|
return True
|
|
return any(path.is_file() and path.stat().st_mtime_ns > built for path in sources)
|
|
|
|
|
|
def extract_contours(
|
|
model_npz_path: Path,
|
|
representation: str,
|
|
interval: float,
|
|
target_grid_m: float = 1.0,
|
|
scene_center: tuple[float, float, float] | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""표현별 npz 모델에서 표고 격자를 환원한 뒤 등고선 리스트를 추출한다."""
|
|
model_npz_path = Path(model_npz_path)
|
|
if not model_npz_path.exists():
|
|
raise FileNotFoundError(f"모델 파일이 존재하지 않습니다: {model_npz_path}")
|
|
# 실패해도 모델 파일을 닫음 — 열린 채 남으면 Windows 에서 다시 짓기(교체)가 막힘(754-1)
|
|
with np.load(model_npz_path) as data:
|
|
return _extract_loaded(
|
|
data, model_npz_path, representation, interval, target_grid_m, scene_center
|
|
)
|
|
|
|
|
|
def _extract_loaded(
|
|
data: Any,
|
|
model_npz_path: Path,
|
|
representation: str,
|
|
interval: float,
|
|
target_grid_m: float,
|
|
scene_center: tuple[float, float, float] | None,
|
|
) -> list[dict[str, Any]]:
|
|
|
|
if representation == "regular_grid":
|
|
x_coords, y_coords, z_grid, valid_mask = (
|
|
data["x"],
|
|
data["y"],
|
|
data["z"],
|
|
data["valid_mask"],
|
|
)
|
|
current_res = (x_coords[-1] - x_coords[0]) / (len(x_coords) - 1)
|
|
step = max(1, int(round(target_grid_m / current_res)))
|
|
if step > 1:
|
|
return extract_contours_from_grid(
|
|
x_coords[::step],
|
|
y_coords[::step],
|
|
z_grid[::step, ::step],
|
|
valid_mask[::step, ::step],
|
|
interval,
|
|
scene_center=scene_center,
|
|
)
|
|
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) · dtm 늘 먼저(754-1)
|
|
from common_util.common_util_surface_sampler import implicit_grid_npz
|
|
|
|
filter_key = model_npz_path.stem.removeprefix("implicit_")
|
|
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}")
|