10장: 종합 실전 — 재구성 결과 뷰어 앱
전체 목차 · 이전: 9장: 시간에 따른 재생과 스트리밍 · 다음: 맺음말
지금까지 배운 요소 — 포인트클라우드(1, 7장), 프레임(2장), 카메라 프러스텀(3장), GUI 컨트롤(5장), 클릭 이벤트(6장) — 를 하나로 묶어, 3D 재구성 파이프라인을 디버깅할 때 실제로 쓸 법한 작은 뷰어 앱을 만들어봅니다.
재구성 결과: 포인트클라우드와 카메라들
import numpy as np
import viser
from scipy.spatial.transform import Rotation
server = viser.ViserServer()
server.scene.world_axes.visible = True
def quat_wxyz(rotation: Rotation) -> tuple[float, float, float, float]:
x, y, z, w = rotation.as_quat()
return (w, x, y, z)
rng = np.random.default_rng(seed=3)
num_points = 20_000
theta = rng.uniform(0, np.pi, num_points)
phi = rng.uniform(0, 2 * np.pi, num_points)
radius = 2.0 + rng.normal(0, 0.03, num_points)
scene_points = np.stack(
[
radius * np.sin(theta) * np.cos(phi),
radius * np.sin(theta) * np.sin(phi),
radius * np.cos(theta),
],
axis=1,
).astype(np.float32)
z_normalized = (scene_points[:, 2] - scene_points[:, 2].min()) / (
scene_points[:, 2].max() - scene_points[:, 2].min()
)
scene_colors = np.zeros((num_points, 3), dtype=np.uint8)
scene_colors[:, 0] = (255 * z_normalized).astype(np.uint8)
scene_colors[:, 2] = (255 * (1.0 - z_normalized)).astype(np.uint8)
point_cloud = server.scene.add_point_cloud(
"/reconstruction/points",
points=scene_points,
colors=scene_colors,
point_size=0.015,
point_shape="circle",
)7장에서 만든 "가짜 라이다 스캔"과 같은 방식으로 재구성된 장면을 흉내 냈습니다. 이름을 /reconstruction/points`로 지어 이 뷰어 앱의 모든 물체가 `/reconstruction 아래 정리되도록 씬 트리를 구성했습니다 — 이렇게 이름 규칙을 정해두면, 나중에 씬이 복잡해져도 /reconstruction/* 전체를 한 번에 지우거나 숨기기 쉬워집니다.
재구성에 사용된 카메라: 클릭 가능한 프러스텀
num_cameras = 6
fov_y = 2.0 * np.arctan(480 / 2.0 / 800.0)
aspect = 640 / 480
camera_positions = np.stack(
[
3.5 * np.cos(np.linspace(0, 2 * np.pi, num_cameras, endpoint=False)),
3.5 * np.sin(np.linspace(0, 2 * np.pi, num_cameras, endpoint=False)),
np.full(num_cameras, 0.8),
],
axis=1,
)
status_text = server.gui.add_text("Selected camera", initial_value="none")
frustum_handles = []
click_handlers = []
selected_log: list[int] = []
for i in range(num_cameras):
position = camera_positions[i]
forward = -position / np.linalg.norm(position)
world_up = np.array([0.0, 0.0, 1.0])
right = np.cross(forward, world_up)
right /= np.linalg.norm(right)
up = np.cross(right, forward)
R_cam_to_world = np.stack([right, -up, forward], axis=1)
handle = server.scene.add_camera_frustum(
f"/reconstruction/cameras/cam_{i}",
fov=fov_y,
aspect=aspect,
scale=0.3,
wxyz=quat_wxyz(Rotation.from_matrix(R_cam_to_world)),
position=tuple(position),
color=(230, 160, 30),
)
def make_click_handler(index: int):
def _handler(_event) -> None:
status_text.value = f"cam_{index}"
selected_log.append(index)
return _handler
click_handler = make_click_handler(i)
handle.on_click(click_handler)
frustum_handles.append(handle)
click_handlers.append(click_handler)3장의 look-at 코드를 그대로 재사용해 6대의 카메라가 재구성된 장면을 둘러싸도록 배치했습니다. on_click`으로 등록한 `make_click_handler(i)`는 클로저로 카메라 인덱스 `i`를 기억하고 있다가, 그 프러스텀을 클릭하면 GUI 텍스트에 어떤 카메라인지 표시합니다 — for 루프 안에서 콜백을 만들 때 `i`를 직접 참조하지 않고 `make_click_handler 함수로 감싸는 이유는, 그렇게 하지 않으면 파이썬 클로저가 루프 변수 `i`의 "마지막 값"만 기억하는 흔한 함정에 빠지기 때문입니다.
GUI 컨트롤 패널로 묶기
with server.gui.add_folder("Controls"):
point_size_slider = server.gui.add_slider(
"Point size", min=0.002, max=0.05, step=0.001, initial_value=0.015
)
show_cameras_checkbox = server.gui.add_checkbox("Show cameras", initial_value=True)
@point_size_slider.on_update
def _(_event) -> None:
point_cloud.point_size = point_size_slider.value
@show_cameras_checkbox.on_update
def _(_event) -> None:
for handle in frustum_handles:
handle.visible = show_cameras_checkbox.value`server.gui.add_folder`로 만든 컨텍스트 매니저 안에서 컨트롤을 추가하면, 그 컨트롤들이 사이드바에서 접었다 펼 수 있는 폴더로 묶여 나타납니다 — 컨트롤이 많아질수록 이런 그룹화가 뷰어를 정돈된 상태로 유지해줍니다. 포인트 크기 슬라이더는 5장의 패턴대로 `point_cloud.point_size`에 직접 연결했고, 체크박스는 모든 프러스텀 핸들의 `visible`을 한 번에 토글합니다 — 재구성된 장면만 집중해서 보고 싶을 때 카메라들을 잠깐 치울 수 있습니다.
전체 배선이 올바른지 한 번에 검증하기
assert point_cloud.points.shape == (num_points, 3)
assert len(frustum_handles) == num_cameras
point_size_slider.value = 0.03
assert np.isclose(point_cloud.point_size, 0.03)
show_cameras_checkbox.value = False
assert all(not h.visible for h in frustum_handles)
show_cameras_checkbox.value = True
assert all(h.visible for h in frustum_handles)
click_handlers[2](None)
click_handlers[5](None)
assert status_text.value == "cam_5"
assert selected_log == [2, 5]포인트 크기 슬라이더를 옮기면 실제로 포인트클라우드의 `point_size`가 바뀌는지, 체크박스를 껐다 켜면 6개 프러스텀 전부의 `visible`이 한꺼번에 바뀌는지, 그리고 클릭 핸들러를 직접 호출했을 때(`click_handlers[2](None)`처럼 이벤트 객체 없이도 호출 가능하도록 함수 시그니처를 단순하게 짰습니다) 상태 텍스트와 클릭 로그가 정확한 카메라 인덱스로 갱신되는지까지, 이 작은 앱의 배선 전체를 브라우저 없이 코드만으로 검증했습니다.
전체 코드
Details
import numpy as np
import viser
from scipy.spatial.transform import Rotation
server = viser.ViserServer()
server.scene.world_axes.visible = True
def quat_wxyz(rotation: Rotation) -> tuple[float, float, float, float]:
x, y, z, w = rotation.as_quat()
return (w, x, y, z)
# --- 1. 재구성된 장면: 노이즈 섞인 구형 포인트클라우드 (7장) ---
rng = np.random.default_rng(seed=3)
num_points = 20_000
theta = rng.uniform(0, np.pi, num_points)
phi = rng.uniform(0, 2 * np.pi, num_points)
radius = 2.0 + rng.normal(0, 0.03, num_points)
scene_points = np.stack(
[
radius * np.sin(theta) * np.cos(phi),
radius * np.sin(theta) * np.sin(phi),
radius * np.cos(theta),
],
axis=1,
).astype(np.float32)
z_normalized = (scene_points[:, 2] - scene_points[:, 2].min()) / (
scene_points[:, 2].max() - scene_points[:, 2].min()
)
scene_colors = np.zeros((num_points, 3), dtype=np.uint8)
scene_colors[:, 0] = (255 * z_normalized).astype(np.uint8)
scene_colors[:, 2] = (255 * (1.0 - z_normalized)).astype(np.uint8)
point_cloud = server.scene.add_point_cloud(
"/reconstruction/points",
points=scene_points,
colors=scene_colors,
point_size=0.015,
point_shape="circle",
)
# --- 2. 재구성에 쓰인 카메라들: look-at 프러스텀 (3장) ---
num_cameras = 6
fov_y = 2.0 * np.arctan(480 / 2.0 / 800.0)
aspect = 640 / 480
camera_positions = np.stack(
[
3.5 * np.cos(np.linspace(0, 2 * np.pi, num_cameras, endpoint=False)),
3.5 * np.sin(np.linspace(0, 2 * np.pi, num_cameras, endpoint=False)),
np.full(num_cameras, 0.8),
],
axis=1,
)
status_text = server.gui.add_text("Selected camera", initial_value="none")
frustum_handles = []
click_handlers = []
selected_log: list[int] = []
for i in range(num_cameras):
position = camera_positions[i]
forward = -position / np.linalg.norm(position)
world_up = np.array([0.0, 0.0, 1.0])
right = np.cross(forward, world_up)
right /= np.linalg.norm(right)
up = np.cross(right, forward)
R_cam_to_world = np.stack([right, -up, forward], axis=1)
handle = server.scene.add_camera_frustum(
f"/reconstruction/cameras/cam_{i}",
fov=fov_y,
aspect=aspect,
scale=0.3,
wxyz=quat_wxyz(Rotation.from_matrix(R_cam_to_world)),
position=tuple(position),
color=(230, 160, 30),
)
def make_click_handler(index: int):
def _handler(_event) -> None:
status_text.value = f"cam_{index}"
selected_log.append(index)
return _handler
click_handler = make_click_handler(i)
handle.on_click(click_handler)
frustum_handles.append(handle)
click_handlers.append(click_handler)
# --- 3. GUI 컨트롤 패널 (5장) ---
with server.gui.add_folder("Controls"):
point_size_slider = server.gui.add_slider(
"Point size", min=0.002, max=0.05, step=0.001, initial_value=0.015
)
show_cameras_checkbox = server.gui.add_checkbox("Show cameras", initial_value=True)
@point_size_slider.on_update
def _(_event) -> None:
point_cloud.point_size = point_size_slider.value
@show_cameras_checkbox.on_update
def _(_event) -> None:
for handle in frustum_handles:
handle.visible = show_cameras_checkbox.value
# --- 검증: 각 부분이 올바르게 연결되었는지 확인 ---
assert point_cloud.points.shape == (num_points, 3)
assert len(frustum_handles) == num_cameras
point_size_slider.value = 0.03
assert np.isclose(point_cloud.point_size, 0.03)
show_cameras_checkbox.value = False
assert all(not h.visible for h in frustum_handles)
show_cameras_checkbox.value = True
assert all(h.visible for h in frustum_handles)
# 프러스텀 클릭 콜백을 직접 호출해 상태 텍스트와 로그가 갱신되는지 검증
click_handlers[2](None)
click_handlers[5](None)
assert status_text.value == "cam_5"
assert selected_log == [2, 5]
server.stop()요약
이름 규칙(
/reconstruction/points,/reconstruction/cameras/cam_i)으로 씬 트리를 정리해두면, 물체가 늘어나도 뷰어 앱을 관리하기 쉽습니다.add_folder컨텍스트 매니저로 관련된 GUI 컨트롤들을 묶어 사이드바를 정돈할 수 있습니다.for 루프 안에서 클릭 콜백을 등록할 때는 `make_click_handler(i)`처럼 클로저로 감싸야 루프 변수를 올바르게 캡처합니다.
앱의 모든 배선(슬라이더→물체 속성, 체크박스→가시성, 클릭→상태 텍스트)은 브라우저를 열지 않고도 핸들의 속성을 직접 바꾸거나 콜백을 직접 호출해 검증할 수 있습니다.
이 책에서 다룬 요소들 — 씬 트리, 프레임, 프러스텀, 메시, GUI, 클릭 이벤트, 배치 렌더링, 3DGS 시각화, 재생 — 을 조합하면, 각자의 SLAM/재구성/3DGS 파이프라인에 맞춘 전용 디버깅 뷰어를 직접 만들 수 있습니다.