Skip to content

3장: 카메라 프러스텀 시각화


멀티뷰 재구성이나 캘리브레이션 코드를 디버깅할 때 가장 자주 나는 실수는 "카메라 회전행렬은 계산했는데, 그게 정말 원하는 방향을 보고 있는지" 확인하지 않는 것입니다. 프러스텀(절두체) 하나만 눈으로 봐도 이 실수는 바로 드러납니다 — 이 장에서는 `add_camera_frustum`으로 카메라의 시야각과 자세를 동시에 그리는 법을 다룹니다.

프러스텀 = 내부 파라미터 + 외부 파라미터

`add_camera_frustum`은 카메라 위치에서 시야를 나타내는 각뿔(절두체) 와이어프레임을 그립니다.

import numpy as np
import viser

server = viser.ViserServer()
server.scene.world_axes.visible = True

# 이 시리즈의 1장 핀홀 카메라 모델 책에서 쓴 내부 파라미터를 그대로 재사용
fx, fy = 800.0, 800.0
width, height = 640, 480
fov_y = 2.0 * np.arctan(height / 2.0 / fy)
aspect = width / height

fov(수직 시야각, 라디안)와 aspect(가로/세로 비율)가 프러스텀의 모양을 결정합니다. fov_y = 2·atan(height / (2·fy))`는 핀홀 카메라 모델 책 1장에서 다룬 내부 파라미터 `fy(세로 방향 초점거리)로부터 시야각을 역산하는 공식입니다 — 즉 캘리브레이션으로 얻은 K 행렬을 그대로 프러스텀 모양으로 옮길 수 있다는 뜻입니다.

look-at 회전으로 카메라를 원점으로 향하게 하기

프러스텀의 위치와 방향은 외부 파라미터입니다. 원점을 중심으로 세 대의 카메라를 배치하고, 각 카메라가 항상 원점을 바라보도록 방향을 계산해보겠습니다.

from scipy.spatial.transform import Rotation


def quat_wxyz(rotation: Rotation) -> tuple[float, float, float, float]:
    x, y, z, w = rotation.as_quat()
    return (w, x, y, z)


camera_handles = []
for i, angle_deg in enumerate([0.0, 120.0, 240.0]):
    angle = np.deg2rad(angle_deg)
    radius = 2.0
    position = np.array([radius * np.cos(angle), radius * np.sin(angle), 0.5])

    # 카메라가 항상 원점을 바라보도록 하는 방향(look-at) 계산
    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)
    # 카메라 좌표계 관례: x=right, y=down, z=forward
    R_cam_to_world = np.stack([right, -up, forward], axis=1)
    rotation = Rotation.from_matrix(R_cam_to_world)

    handle = server.scene.add_camera_frustum(
        f"/cameras/cam_{i}",
        fov=fov_y,
        aspect=aspect,
        scale=0.3,
        wxyz=quat_wxyz(rotation),
        position=tuple(position),
        color=(200, 60, 60),
    )
    camera_handles.append(handle)

`forward`는 카메라에서 원점을 향하는 방향(카메라 위치의 반대 방향), `right`는 `forward`와 세계의 "위" 방향을 외적해서 얻는 카메라의 오른쪽 방향, `up`은 다시 `right`와 `forward`를 외적해서 얻는 카메라의 실제 위쪽 방향입니다. 이 세 벡터를 열로 쌓으면 카메라 좌표축을 세계 좌표축으로 대응시키는 회전행렬이 됩니다 — 컴퓨터 그래픽스/비전에서 카메라의 y축은 보통 "아래"를 향하므로(이미지의 행 번호가 아래로 갈수록 커지듯) `up`이 아니라 `-up`을 두 번째 열로 씁니다.

씬 트리와 파라미터 검증

assert len(camera_handles) == 3
assert camera_handles[0].name == "/cameras/cam_0"
assert np.isclose(camera_handles[0].aspect, aspect)

# 회전행렬이 직교(RᵀR=I)하고 행렬식이 +1인 진짜 회전인지 검증
assert np.allclose(R_cam_to_world.T @ R_cam_to_world, np.eye(3), atol=1e-10)
assert np.isclose(np.linalg.det(R_cam_to_world), 1.0)

2장에서 다룬 강체 변환의 조건(직교 + 행렬식 +1)은 여기서도 그대로 적용됩니다 — `look-at`으로 즉석에서 만든 회전행렬이라도 이 조건을 만족하지 않으면 프러스텀이 찌그러지거나 뒤집혀 렌더링됩니다.

forward 벡터가 실제로 원점을 향하는지 확인

last_position = np.array(
    [2.0 * np.cos(np.deg2rad(240.0)), 2.0 * np.sin(np.deg2rad(240.0)), 0.5]
)
forward_check = R_cam_to_world @ np.array([0.0, 0.0, 1.0])
to_origin_direction = -last_position / np.linalg.norm(last_position)
assert np.allclose(forward_check[:2], to_origin_direction[:2], atol=1e-10)

카메라 좌표계의 `z`축(정면 방향)에 회전행렬을 곱하면 세계 좌표계에서 그 카메라가 실제로 바라보는 방향이 나와야 합니다. 이 값이 "카메라 위치에서 원점으로 향하는 방향"과 일치한다는 것을 확인했으니, 브라우저에서도 세 프러스텀이 모두 원점을 향해 모여 있는 모습을 볼 수 있을 것입니다 — 코드로 미리 확인했으니 눈으로 보는 결과는 그저 확인 도장일 뿐입니다.

실전에서: 캘리브레이션 디버깅

실무에서는 position`과 `wxyz`를 직접 계산하는 대신, 캘리브레이션 파이프라인이 추정한 `R, t(월드→카메라)를 카메라 중심 C = -Rᵀt`와 카메라→월드 회전 `Rᵀ`로 변환해 넣습니다. 프러스텀을 실제 3D 포인트클라우드(다음 장 이후에서 다룰 `add_point_cloud)와 함께 띄우면, 카메라가 재구성된 장면 밖을 보고 있거나 스케일이 이상한 것을 즉시 알아챌 수 있습니다 — 순수 숫자 검증만으로는 놓치기 쉬운 종류의 버그입니다.

전체 코드

Details
import numpy as np
import viser
from scipy.spatial.transform import Rotation

server = viser.ViserServer()
server.scene.world_axes.visible = True

# 1장 핀홀 카메라 모델 책의 내부 파라미터를 그대로 사용
fx, fy = 800.0, 800.0
width, height = 640, 480
fov_y = 2.0 * np.arctan(height / 2.0 / fy)
aspect = width / height


def quat_wxyz(rotation: Rotation) -> tuple[float, float, float, float]:
    x, y, z, w = rotation.as_quat()
    return (w, x, y, z)


# 세 대의 카메라가 원점을 중심으로 원을 그리며 서로 다른 위치/방향에서 바라본다
camera_handles = []
for i, angle_deg in enumerate([0.0, 120.0, 240.0]):
    angle = np.deg2rad(angle_deg)
    radius = 2.0
    position = np.array([radius * np.cos(angle), radius * np.sin(angle), 0.5])

    # 카메라가 항상 원점을 바라보도록 하는 방향(look-at) 계산
    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)
    # 카메라 좌표계 관례: x=right, y=down, z=forward
    R_cam_to_world = np.stack([right, -up, forward], axis=1)
    rotation = Rotation.from_matrix(R_cam_to_world)

    handle = server.scene.add_camera_frustum(
        f"/cameras/cam_{i}",
        fov=fov_y,
        aspect=aspect,
        scale=0.3,
        wxyz=quat_wxyz(rotation),
        position=tuple(position),
        color=(200, 60, 60),
    )
    camera_handles.append(handle)

assert len(camera_handles) == 3
assert camera_handles[0].name == "/cameras/cam_0"
assert np.isclose(camera_handles[0].aspect, aspect)

# 회전행렬이 직교(RᵀR=I)하고 행렬식이 +1인 진짜 회전인지 검증
assert np.allclose(R_cam_to_world.T @ R_cam_to_world, np.eye(3), atol=1e-10)
assert np.isclose(np.linalg.det(R_cam_to_world), 1.0)

# 카메라의 forward(z) 방향이 실제로 원점을 향하는지 검증
last_position = np.array(
    [2.0 * np.cos(np.deg2rad(240.0)), 2.0 * np.sin(np.deg2rad(240.0)), 0.5]
)
forward_check = R_cam_to_world @ np.array([0.0, 0.0, 1.0])
to_origin_direction = -last_position / np.linalg.norm(last_position)
assert np.allclose(forward_check[:2], to_origin_direction[:2], atol=1e-10)

server.stop()

요약

  • `add_camera_frustum(fov, aspect, wxyz, position)`은 내부 파라미터(시야각·종횡비)와 외부 파라미터(위치·방향)를 하나의 시각화로 합칩니다.

  • `fov_y = 2·atan(height / (2·fy))`로 캘리브레이션된 초점거리를 프러스텀의 시야각으로 직접 변환할 수 있습니다.

  • look-at 방식으로 forward/right/up 세 벡터를 외적으로 구성하면 카메라가 특정 지점을 바라보는 회전행렬을 얻을 수 있고, 이 행렬도 여전히 RᵀR=I, det®=1 조건을 만족해야 합니다.

다음 장에서는 점과 축을 넘어 실제 표면을 가진 메시와 조명을 다뤄, 장면에 입체감을 더하는 법을 봅니다.