CHAPTER 7

3D Vision and Depth Estimation

Understanding three-dimensional structure from images

Introduction to 3D Vision

3D vision enables computers to understand the three-dimensional structure of the world from 2D images. This is crucial for robotics, autonomous vehicles, AR/VR, and scene understanding.

Key Concepts

Stereo Vision

Stereo vision uses two cameras to triangulate depth, similar to human binocular vision.

Stereo Calibration

import cv2
import numpy as np

# Prepare object points (e.g., chessboard corners)
objp = np.zeros((6*9, 3), np.float32)
objp[:,:2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)

# Arrays to store points
objpoints = []  # 3D points in real world
imgpoints_left = []  # 2D points in left image
imgpoints_right = []  # 2D points in right image

# Find corners in calibration images
for left_img, right_img in calibration_images:
    gray_left = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY)
    gray_right = cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY)

    ret_left, corners_left = cv2.findChessboardCorners(gray_left, (9,6))
    ret_right, corners_right = cv2.findChessboardCorners(gray_right, (9,6))

    if ret_left and ret_right:
        objpoints.append(objp)
        imgpoints_left.append(corners_left)
        imgpoints_right.append(corners_right)

# Stereo calibration
retval, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, R, T, E, F = \
    cv2.stereoCalibrate(objpoints, imgpoints_left, imgpoints_right,
                        None, None, None, None, gray_left.shape[::-1])

# Stereo rectification
R1, R2, P1, P2, Q, roi1, roi2 = cv2.stereoRectify(
    cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2,
    gray_left.shape[::-1], R, T
)

Disparity Map Computation

# Create StereoBM (Block Matching) or StereoSGBM
stereo = cv2.StereoSGBM_create(
    minDisparity=0,
    numDisparities=16*10,  # Max disparity (must be divisible by 16)
    blockSize=5,
    P1=8 * 3 * 5**2,
    P2=32 * 3 * 5**2,
    disp12MaxDiff=1,
    uniquenessRatio=10,
    speckleWindowSize=100,
    speckleRange=32
)

# Compute disparity
disparity = stereo.compute(left_gray, right_gray).astype(np.float32) / 16.0

# Compute depth from disparity
# depth = (focal_length * baseline) / disparity
focal_length = cameraMatrix1[0, 0]
baseline = np.linalg.norm(T)
depth_map = (focal_length * baseline) / (disparity + 1e-6)

Monocular Depth Estimation

Estimate depth from a single image using deep learning.

MiDaS (Towards Robust Monocular Depth Estimation)

import torch
import cv2
from torchvision.transforms import Compose

# Load MiDaS model
model_type = "DPT_Large"  # or "DPT_Hybrid", "MiDaS_small"
midas = torch.hub.load("intel-isl/MiDaS", model_type)

device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
midas.to(device)
midas.eval()

# Load transforms
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
transform = midas_transforms.dpt_transform

# Load image
img = cv2.imread("image.jpg")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Prepare input
input_batch = transform(img_rgb).to(device)

# Predict depth
with torch.no_grad():
    prediction = midas(input_batch)
    prediction = torch.nn.functional.interpolate(
        prediction.unsqueeze(1),
        size=img_rgb.shape[:2],
        mode="bicubic",
        align_corners=False,
    ).squeeze()

depth_map = prediction.cpu().numpy()

# Normalize for visualization
depth_min = depth_map.min()
depth_max = depth_map.max()
depth_normalized = (depth_map - depth_min) / (depth_max - depth_min)
depth_colored = cv2.applyColorMap((depth_normalized * 255).astype(np.uint8),
                                  cv2.COLORMAP_MAGMA)

ZoeDepth

Zero-shot transfer for metric depth estimation.

Depth Anything

Foundation model for monocular depth estimation with strong generalization.

Structure from Motion (SfM)

Reconstruct 3D structure from multiple images taken from different viewpoints.

COLMAP

# COLMAP pipeline for 3D reconstruction
# 1. Feature extraction
colmap feature_extractor \
    --database_path database.db \
    --image_path images/

# 2. Feature matching
colmap exhaustive_matcher \
    --database_path database.db

# 3. Sparse reconstruction
colmap mapper \
    --database_path database.db \
    --image_path images/ \
    --output_path sparse/

# 4. Dense reconstruction
colmap image_undistorter \
    --image_path images/ \
    --input_path sparse/0 \
    --output_path dense/

colmap patch_match_stereo \
    --workspace_path dense/

colmap stereo_fusion \
    --workspace_path dense/ \
    --output_path dense/fused.ply

Point Cloud Processing

Loading and Visualizing Point Clouds

import open3d as o3d

# Load point cloud
pcd = o3d.io.read_point_cloud("pointcloud.ply")

# Visualize
o3d.visualization.draw_geometries([pcd])

# Get point cloud statistics
print(f"Number of points: {len(pcd.points)}")
print(f"Point cloud center: {pcd.get_center()}")
print(f"Bounding box: {pcd.get_axis_aligned_bounding_box()}")

# Downsample point cloud
pcd_down = pcd.voxel_down_sample(voxel_size=0.05)

# Estimate normals
pcd.estimate_normals(
    search_param=o3d.geometry.KDTreeSearchParamHybrid(
        radius=0.1, max_nn=30
    )
)

# Remove outliers
cl, ind = pcd.remove_statistical_outlier(nb_neighbors=20, std_ratio=2.0)
pcd_clean = pcd.select_by_index(ind)

Point Cloud Registration

# ICP (Iterative Closest Point) registration
def register_point_clouds(source, target):
    threshold = 0.02
    trans_init = np.identity(4)

    # Coarse registration with RANSAC
    ransac_result = o3d.pipelines.registration.registration_ransac_based_on_feature_matching(
        source, target,
        source_features, target_features,
        True, threshold,
        o3d.pipelines.registration.TransformationEstimationPointToPoint(False),
        3,
        [o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9),
         o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(threshold)],
        o3d.pipelines.registration.RANSACConvergenceCriteria(100000, 0.999)
    )

    # Fine registration with ICP
    icp_result = o3d.pipelines.registration.registration_icp(
        source, target, threshold, ransac_result.transformation,
        o3d.pipelines.registration.TransformationEstimationPointToPoint()
    )

    return icp_result.transformation

3D Object Detection

PointNet

Deep learning on point clouds for classification and segmentation.

import torch
import torch.nn as nn

class PointNet(nn.Module):
    def __init__(self, num_classes):
        super(PointNet, self).__init__()

        # Shared MLP
        self.conv1 = nn.Conv1d(3, 64, 1)
        self.conv2 = nn.Conv1d(64, 128, 1)
        self.conv3 = nn.Conv1d(128, 1024, 1)

        # Classification head
        self.fc1 = nn.Linear(1024, 512)
        self.fc2 = nn.Linear(512, 256)
        self.fc3 = nn.Linear(256, num_classes)

        self.bn1 = nn.BatchNorm1d(64)
        self.bn2 = nn.BatchNorm1d(128)
        self.bn3 = nn.BatchNorm1d(1024)
        self.bn4 = nn.BatchNorm1d(512)
        self.bn5 = nn.BatchNorm1d(256)

        self.dropout = nn.Dropout(0.3)

    def forward(self, x):
        # x: (batch, 3, num_points)
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.relu(self.bn3(self.conv3(x)))

        # Max pooling for global feature
        x = torch.max(x, 2, keepdim=True)[0]
        x = x.view(-1, 1024)

        # Classification
        x = F.relu(self.bn4(self.fc1(x)))
        x = F.relu(self.bn5(self.dropout(self.fc2(x))))
        x = self.fc3(x)

        return x

VoxelNet and SECOND

Voxel-based 3D detection for autonomous driving.

Neural Radiance Fields (NeRF)

Novel view synthesis by representing scenes as continuous 5D functions.

# NeRF concept (simplified)
class NeRF(nn.Module):
    def __init__(self, D=8, W=256):
        super(NeRF, self).__init__()

        # Position encoding
        self.pos_encoder = PositionalEncoder()

        # MLP layers
        self.layers = nn.ModuleList()
        for i in range(D):
            if i == 0:
                self.layers.append(nn.Linear(63, W))  # 3*10*2 + 3
            elif i == D//2:
                self.layers.append(nn.Linear(W + 63, W))
            else:
                self.layers.append(nn.Linear(W, W))

        self.rgb_layer = nn.Linear(W, 3)
        self.density_layer = nn.Linear(W, 1)

    def forward(self, x, d):
        # x: position (batch, 3)
        # d: viewing direction (batch, 3)

        x = self.pos_encoder(x)
        h = x

        for i, layer in enumerate(self.layers):
            h = layer(h)
            h = F.relu(h)
            if i == len(self.layers) // 2:
                h = torch.cat([h, x], -1)

        density = F.relu(self.density_layer(h))
        rgb = torch.sigmoid(self.rgb_layer(h))

        return rgb, density

3D Reconstruction from Images

Multi-View Stereo (MVS)

Dense reconstruction from calibrated images.

Photogrammetry

Create 3D models from photographs.

Depth Sensors

RGB-D Cameras

import pyrealsense2 as rs
import numpy as np

# Configure RealSense pipeline
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

# Start streaming
pipeline.start(config)

try:
    while True:
        # Wait for frames
        frames = pipeline.wait_for_frames()
        depth_frame = frames.get_depth_frame()
        color_frame = frames.get_color_frame()

        if not depth_frame or not color_frame:
            continue

        # Convert to numpy arrays
        depth_image = np.asanyarray(depth_frame.get_data())
        color_image = np.asanyarray(color_frame.get_data())

        # Process depth (in millimeters)
        depth_colormap = cv2.applyColorMap(
            cv2.convertScaleAbs(depth_image, alpha=0.03),
            cv2.COLORMAP_JET
        )

        # Stack images side by side
        images = np.hstack((color_image, depth_colormap))
        cv2.imshow('RealSense', images)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
finally:
    pipeline.stop()

Applications

Autonomous Vehicles

Augmented Reality

Robotics

Summary

  • Stereo vision uses triangulation to compute depth from two cameras
  • Monocular depth estimation uses deep learning to predict depth from single images
  • Structure from Motion reconstructs 3D scenes from multiple viewpoints
  • Point clouds represent 3D data and can be processed with PointNet and similar architectures
  • NeRF enables novel view synthesis by learning continuous scene representations
  • RGB-D sensors provide direct depth measurements for real-time applications
  • 3D vision is critical for autonomous vehicles, AR/VR, and robotics

Review Questions

  1. Explain how stereo vision computes depth from disparity.
  2. What are the advantages of monocular depth estimation over stereo?
  3. How does PointNet process unordered point clouds?
  4. What is the key innovation in NeRF for novel view synthesis?
  5. Compare active vs passive depth sensing methods.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.