Modern Apps git

← Modern-Apps.git

camera: significant quality improvements to pano and sphere photos

Commit
4945be3143e0f77bdc19d6defea8273f7969d8ff
Author
Vayun Mathur <[email protected]>
When
2026-07-19 20:57 UTC (4 months ago)
Parents
439c440

Diff

camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex d21e753524..0034645939 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -1,3 +1,5 @@+import java.util.Properties+ plugins {     id("common-conventions-app")     id("common-conventions-metadata")@@ -11,11 +13,84 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.camera"     }-    packaging {-        jniLibs.useLegacyPackaging = true+    // The Rust stitcher drops <abi>/libcamera_stitch.so under this dir; register+    // it as a jniLibs source so AGP packages the native lib.+    sourceSets["main"].jniLibs.directories.add(layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath)+}++// ---------------------------------------------------------------------------+// Native panorama stitcher + night burst aligner (Rust). See camera/rust/.+// Cross-compiled per-ABI with the NDK's clang, driven directly from cargo (same+// approach as :pdf and :weather).+// Contributor/CI prerequisite:  rustup target add aarch64-linux-android+// ---------------------------------------------------------------------------++val ndkVersionForRust = "29.0.14206865"+val androidApiLevel = 31++fun resolveSdkDir(): String =+    System.getenv("ANDROID_HOME")+        ?: System.getenv("ANDROID_SDK_ROOT")+        ?: rootProject.file("local.properties").takeIf { it.exists() }?.let { f ->+            Properties().apply { f.inputStream().use { load(it) } }.getProperty("sdk.dir")+        }+        ?: error("Android SDK not found (set ANDROID_HOME or sdk.dir in local.properties)")++val cargoBin = "${System.getProperty("user.home")}/.cargo/bin"+val ndkRoot = "${resolveSdkDir()}/ndk/$ndkVersionForRust"+val hostTag = when {+    org.gradle.internal.os.OperatingSystem.current().isMacOsX -> "darwin-x86_64"+    org.gradle.internal.os.OperatingSystem.current().isLinux -> "linux-x86_64"+    org.gradle.internal.os.OperatingSystem.current().isWindows -> "windows-x86_64"+    else -> error("Unsupported host OS for NDK toolchain")+}+val ndkBin = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/bin"+val ndkSysroot = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/sysroot"++// (jniLibs ABI dir, Rust target triple)+val rustAbis = listOf(+    "arm64-v8a" to "aarch64-linux-android",+)++val perAbiBuildTasks = rustAbis.map { (abiDir, triple) ->+    tasks.register<Exec>("cargoBuild_${abiDir.replace('-', '_')}") {+        description = "Cross-compiles the Rust camera stitcher for $abiDir."+        workingDir = file("rust")++        val clang = "$ndkBin/$triple$androidApiLevel-clang"+        val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"+        val soOut = file("rust/target/$triple/release/libcamera_stitch.so")+        val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/libcamera_stitch.so").get().asFile++        inputs.dir("rust/src")+        inputs.file("rust/Cargo.toml")+        outputs.file(destSo)++        environment("PATH", "$cargoBin:${System.getenv("PATH")}")+        environment("CC", clang)+        environment("AR", "$ndkBin/llvm-ar")+        environment("SYSROOT", ndkSysroot)+        environment(linkerVar, clang)+        environment("HOST_CC", "/usr/bin/clang")++        commandLine("$cargoBin/cargo", "build", "--release", "--target", triple)++        doLast {+            destSo.parentFile.mkdirs()+            soOut.copyTo(destSo, overwrite = true)+        }     } } +val cargoNdkBuild = tasks.register("cargoNdkBuild") {+    description = "Builds libcamera_stitch.so for all Android ABIs."+    dependsOn(perAbiBuildTasks)+}++tasks.matching { it.name == "preBuild" }.configureEach {+    dependsOn(cargoNdkBuild)+}+ dependencies {     implementation(libs.androidx.camera.core)     implementation(libs.androidx.camera.camera2)@@ -26,5 +101,4 @@ dependencies {     implementation(libs.androidx.exifinterface)     implementation(libs.zxing.core)     implementation("com.google.mediapipe:tasks-vision:0.10.14")-    implementation("com.quickbirdstudios:opencv:4.5.3.0") }
camera/rust/.gitignore
diff --git a/camera/rust/.gitignore b/camera/rust/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/camera/rust/.gitignore@@ -0,0 +1 @@+/target
camera/rust/Cargo.lock
diff --git a/camera/rust/Cargo.lock b/camera/rust/Cargo.locknew file mode 100644index 0000000000..3de72171c6--- /dev/null+++ b/camera/rust/Cargo.lock@@ -0,0 +1,519 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "approx"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"+dependencies = [+ "num-traits",+]++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "bytemuck"+version = "1.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6aedf8ae72766347502cf3cb4f41cf5e9cc37d28bee90f1fdaaae15f9cf9424"++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "camera_stitch"+version = "0.1.0"+dependencies = [+ "image",+ "jni",+ "nalgebra",+ "rayon",+]++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "either"+version = "1.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "matrixmultiply"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"+dependencies = [+ "autocfg",+ "rawpointer",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "nalgebra"+version = "0.33.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d43ddcacf343185dfd6de2ee786d9e8b1c2301622afab66b6c73baf9882abfd"+dependencies = [+ "approx",+ "matrixmultiply",+ "nalgebra-macros",+ "num-complex",+ "num-rational",+ "num-traits",+ "simba",+ "typenum",+]++[[package]]+name = "nalgebra-macros"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-integer"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rawpointer"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "safe_arch"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323"+dependencies = [+ "bytemuck",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "simba"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c99284beb21666094ba2b75bbceda012e610f5479dfcc2d6e2426f53197ffd95"+dependencies = [+ "approx",+ "num-complex",+ "num-traits",+ "paste",+ "wide",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wide"+version = "0.7.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"+dependencies = [+ "bytemuck",+ "safe_arch",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "zune-core"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]
camera/rust/Cargo.toml
diff --git a/camera/rust/Cargo.toml b/camera/rust/Cargo.tomlnew file mode 100644index 0000000000..7b70779148--- /dev/null+++ b/camera/rust/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "camera_stitch"+version = "0.1.0"+edition = "2021"+description = "Feature-based panorama stitcher + night burst aligner for the camera app, exposed to Kotlin via JNI (replaces OpenCV)"+license = "GPL-2.0-only"++[lib]+name = "camera_stitch"+# cdylib => libcamera_stitch.so for Android; rlib => host `cargo test`.+crate-type = ["cdylib", "rlib"]++[dependencies]+jni = "0.21"+image = { version = "0.25", default-features = false, features = ["jpeg"] }+nalgebra = "0.33"+rayon = "1"++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+strip = true
camera/rust/src/blend.rs
diff --git a/camera/rust/src/blend.rs b/camera/rust/src/blend.rsnew file mode 100644index 0000000000..b2eed15325--- /dev/null+++ b/camera/rust/src/blend.rs@@ -0,0 +1,378 @@+//! MultiBandBlender (blenders.cpp): Laplacian-pyramid blending. Built the OpenCV+//! way — each image's pyramid is created at its own ROI (padded so tl/br divide+//! 2^bands) and accumulated into the destination pyramids at the level offset,+//! rather than allocating a full-canvas pyramid per image.++use crate::imgbuf::Rgba;+use crate::sphere::WarpedTile;++struct FImg {+    w: usize,+    h: usize,+    d: Vec<f32>, // w*h*3+}+impl FImg {+    fn new(w: usize, h: usize) -> Self {+        FImg { w, h, d: vec![0.0; w * h * 3] }+    }+}+struct Plane {+    w: usize,+    h: usize,+    d: Vec<f32>,+}+impl Plane {+    fn new(w: usize, h: usize) -> Self {+        Plane { w, h, d: vec![0.0; w * h] }+    }+}++const K: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];++fn blur3(img: &FImg) -> FImg {+    let (w, h) = (img.w, img.h);+    let mut tmp = FImg::new(w, h);+    for y in 0..h {+        for x in 0..w {+            for c in 0..3 {+                let mut s = 0.0;+                for k in 0..5 {+                    let xx = (x as i32 + k as i32 - 2).clamp(0, w as i32 - 1) as usize;+                    s += K[k] * img.d[(y * w + xx) * 3 + c];+                }+                tmp.d[(y * w + x) * 3 + c] = s;+            }+        }+    }+    let mut out = FImg::new(w, h);+    for y in 0..h {+        for x in 0..w {+            for c in 0..3 {+                let mut s = 0.0;+                for k in 0..5 {+                    let yy = (y as i32 + k as i32 - 2).clamp(0, h as i32 - 1) as usize;+                    s += K[k] * tmp.d[(yy * w + x) * 3 + c];+                }+                out.d[(y * w + x) * 3 + c] = s;+            }+        }+    }+    out+}+fn blur1(p: &Plane) -> Plane {+    let (w, h) = (p.w, p.h);+    let mut tmp = Plane::new(w, h);+    for y in 0..h {+        for x in 0..w {+            let mut s = 0.0;+            for k in 0..5 {+                let xx = (x as i32 + k as i32 - 2).clamp(0, w as i32 - 1) as usize;+                s += K[k] * p.d[y * w + xx];+            }+            tmp.d[y * w + x] = s;+        }+    }+    let mut out = Plane::new(w, h);+    for y in 0..h {+        for x in 0..w {+            let mut s = 0.0;+            for k in 0..5 {+                let yy = (y as i32 + k as i32 - 2).clamp(0, h as i32 - 1) as usize;+                s += K[k] * tmp.d[yy * w + x];+            }+            out.d[y * w + x] = s;+        }+    }+    out+}+fn down3(img: &FImg) -> FImg {+    let b = blur3(img);+    let dw = (img.w + 1) / 2;+    let dh = (img.h + 1) / 2;+    let mut out = FImg::new(dw, dh);+    for y in 0..dh {+        for x in 0..dw {+            for c in 0..3 {+                out.d[(y * dw + x) * 3 + c] = b.d[((2 * y).min(img.h - 1) * img.w + (2 * x).min(img.w - 1)) * 3 + c];+            }+        }+    }+    out+}+fn down1(p: &Plane) -> Plane {+    let b = blur1(p);+    let dw = (p.w + 1) / 2;+    let dh = (p.h + 1) / 2;+    let mut out = Plane::new(dw, dh);+    for y in 0..dh {+        for x in 0..dw {+            out.d[y * dw + x] = b.d[(2 * y).min(p.h - 1) * p.w + (2 * x).min(p.w - 1)];+        }+    }+    out+}+fn up3(src: &FImg, dw: usize, dh: usize) -> FImg {+    let mut spread = FImg::new(dw, dh);+    for y in 0..src.h {+        for x in 0..src.w {+            let dx = 2 * x;+            let dy = 2 * y;+            if dx < dw && dy < dh {+                for c in 0..3 {+                    spread.d[(dy * dw + dx) * 3 + c] = src.d[(y * src.w + x) * 3 + c] * 4.0;+                }+            }+        }+    }+    blur3(&spread)+}++/// Fill uncovered (black) pixels of a warped tile by clamp-extending the nearest+/// covered pixel: horizontally, then vertically. Prevents black edges from+/// contaminating the Laplacian pyramid near seams.+fn border_extend(img: &mut FImg, covered: &[bool], w: usize, h: usize) {+    let mut valid = covered.to_vec();+    // horizontal clamp+    for y in 0..h {+        let row = y * w;+        let mut first = None;+        let mut last = 0usize;+        for x in 0..w {+            if covered[row + x] {+                if first.is_none() {+                    first = Some(x);+                }+                last = x;+            }+        }+        if let Some(f) = first {+            for x in 0..f {+                for c in 0..3 {+                    img.d[(row + x) * 3 + c] = img.d[(row + f) * 3 + c];+                }+                valid[row + x] = true;+            }+            for x in (last + 1)..w {+                for c in 0..3 {+                    img.d[(row + x) * 3 + c] = img.d[(row + last) * 3 + c];+                }+                valid[row + x] = true;+            }+        }+    }+    // vertical clamp over remaining+    for x in 0..w {+        let mut first = None;+        let mut last = 0usize;+        for y in 0..h {+            if valid[y * w + x] {+                if first.is_none() {+                    first = Some(y);+                }+                last = y;+            }+        }+        if let Some(f) = first {+            for y in 0..f {+                for c in 0..3 {+                    img.d[(y * w + x) * 3 + c] = img.d[(f * w + x) * 3 + c];+                }+            }+            for y in (last + 1)..h {+                for c in 0..3 {+                    img.d[(y * w + x) * 3 + c] = img.d[(last * w + x) * 3 + c];+                }+            }+        }+    }+}++pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<Rgba> {+    let num = tiles.len();+    if num == 0 {+        return None;+    }+    let mut gx0 = i32::MAX;+    let mut gy0 = i32::MAX;+    let mut gx1 = i32::MIN;+    let mut gy1 = i32::MIN;+    for t in tiles {+        gx0 = gx0.min(t.corner_x);+        gy0 = gy0.min(t.corner_y);+        gx1 = gx1.max(t.corner_x + t.img.w as i32);+        gy1 = gy1.max(t.corner_y + t.img.h as i32);+    }+    let cw = (gx1 - gx0) as usize;+    let ch = (gy1 - gy0) as usize;+    if cw == 0 || ch == 0 || cw > 20000 || ch > 20000 {+        return None;+    }+    let bands = {+        let maxlen = cw.max(ch) as f64;+        (maxlen.log2().ceil() as i32 - 1).clamp(1, 5) as usize+    };+    let div = 1usize << bands;+    let pw = ((cw + div - 1) / div) * div;+    let ph = ((ch + div - 1) / div) * div;++    let mut sizes = Vec::with_capacity(bands + 1);+    {+        let (mut w, mut h) = (pw, ph);+        for _ in 0..=bands {+            sizes.push((w, h));+            w /= 2;+            h /= 2;+        }+    }+    let mut dst_lap: Vec<FImg> = sizes.iter().map(|&(w, h)| FImg::new(w, h)).collect();+    let mut dst_w: Vec<Plane> = sizes.iter().map(|&(w, h)| Plane::new(w, h)).collect();++    for ti in 0..num {+        let t = &tiles[ti];+        let gmap = &gain_maps[ti];+        let tlx = (t.corner_x - gx0) as usize;+        let tly = (t.corner_y - gy0) as usize;+        // Padded ROI whose corners divide 2^bands.+        let x_tl = (tlx / div) * div;+        let y_tl = (tly / div) * div;+        let x_br = (((tlx + t.img.w) + div - 1) / div * div).min(pw);+        let y_br = (((tly + t.img.h) + div - 1) / div * div).min(ph);+        let rw = x_br - x_tl;+        let rh = y_br - y_tl;+        if rw == 0 || rh == 0 {+            continue;+        }+        let mut img = FImg::new(rw, rh);+        let mut wt = Plane::new(rw, rh);+        let mut covered = vec![false; rw * rh];+        for ly in 0..t.img.h {+            for lx in 0..t.img.w {+                let c = t.img.get(lx, ly);+                if c[3] == 0 {+                    continue; // no coverage here+                }+                let rx = tlx + lx - x_tl;+                let ry = tly + ly - y_tl;+                let gain = gmap[ly * t.img.w + lx];+                let idx = (ry * rw + rx) * 3;+                // Place the full warped image everywhere it has coverage so the+                // Laplacian pyramid is smooth across the overlap (no hard edge at+                // the seam). The seam mask drives only the blend weight.+                img.d[idx] = (c[0] as f32 * gain).min(255.0);+                img.d[idx + 1] = (c[1] as f32 * gain).min(255.0);+                img.d[idx + 2] = (c[2] as f32 * gain).min(255.0);+                covered[ry * rw + rx] = true;+                wt.d[ry * rw + rx] = if masks[ti][ly * t.img.w + lx] != 0 { 1.0 } else { 0.0 };+            }+        }+        // Edge-extend the image into its black (uncovered) borders so the+        // Laplacian pyramid has no hard black edge that the coarse blurred+        // weights would drag into the blend (OpenCV builds pyramids with border+        // extension for the same reason).+        border_extend(&mut img, &covered, rw, rh);+        // Pyramids on the ROI.+        let mut gpyr: Vec<FImg> = Vec::with_capacity(bands + 1);+        gpyr.push(img);+        for b in 0..bands {+            gpyr.push(down3(&gpyr[b]));+        }+        let mut wpyr: Vec<Plane> = Vec::with_capacity(bands + 1);+        wpyr.push(wt);+        for b in 0..bands {+            wpyr.push(down1(&wpyr[b]));+        }+        for b in 0..=bands {+            let lw = gpyr[b].w;+            let lh = gpyr[b].h;+            let lap: FImg = if b == bands {+                FImg { w: lw, h: lh, d: gpyr[b].d.clone() }+            } else {+                let up = up3(&gpyr[b + 1], lw, lh);+                let mut l = FImg::new(lw, lh);+                for i in 0..lw * lh * 3 {+                    l.d[i] = gpyr[b].d[i] - up.d[i];+                }+                l+            };+            let (dw, _dh) = sizes[b];+            let offx = x_tl >> b;+            let offy = y_tl >> b;+            for yy in 0..lh {+                for xx in 0..lw {+                    let w = wpyr[b].d[yy * lw + xx];+                    let didx = (offy + yy) * dw + (offx + xx);+                    dst_w[b].d[didx] += w;+                    dst_lap[b].d[didx * 3] += lap.d[(yy * lw + xx) * 3] * w;+                    dst_lap[b].d[didx * 3 + 1] += lap.d[(yy * lw + xx) * 3 + 1] * w;+                    dst_lap[b].d[didx * 3 + 2] += lap.d[(yy * lw + xx) * 3 + 2] * w;+                }+            }+        }+    }++    // Normalize each band by weight.+    for b in 0..=bands {+        let (w, h) = sizes[b];+        for i in 0..w * h {+            let ww = dst_w[b].d[i];+            if ww > 1e-5 {+                dst_lap[b].d[i * 3] /= ww;+                dst_lap[b].d[i * 3 + 1] /= ww;+                dst_lap[b].d[i * 3 + 2] /= ww;+            }+        }+    }++    // Collapse pyramid.+    let mut res = FImg { w: sizes[bands].0, h: sizes[bands].1, d: dst_lap[bands].d.clone() };+    for b in (0..bands).rev() {+        let (w, h) = sizes[b];+        let up = up3(&res, w, h);+        let mut cur = FImg::new(w, h);+        for i in 0..w * h * 3 {+            cur.d[i] = up.d[i] + dst_lap[b].d[i];+        }+        res = cur;+    }++    // Crop to covered region (within the unpadded cw×ch, using base weight).+    let mut minx = cw;+    let mut miny = ch;+    let mut maxx = 0usize;+    let mut maxy = 0usize;+    let mut any = false;+    for y in 0..ch {+        for x in 0..cw {+            if dst_w[0].d[y * pw + x] > 1e-5 {+                any = true;+                minx = minx.min(x);+                miny = miny.min(y);+                maxx = maxx.max(x);+                maxy = maxy.max(y);+            }+        }+    }+    if !any {+        return None;+    }+    let ow = maxx - minx + 1;+    let oh = maxy - miny + 1;+    let mut out = Rgba::new(ow, oh);+    for y in 0..oh {+        for x in 0..ow {+            let sx = x + minx;+            let sy = y + miny;+            let didx = (y * ow + x) * 4;+            if dst_w[0].d[sy * pw + sx] > 1e-5 {+                let ridx = (sy * pw + sx) * 3;+                out.px[didx] = res.d[ridx].round().clamp(0.0, 255.0) as u8;+                out.px[didx + 1] = res.d[ridx + 1].round().clamp(0.0, 255.0) as u8;+                out.px[didx + 2] = res.d[ridx + 2].round().clamp(0.0, 255.0) as u8;+                out.px[didx + 3] = 255;+            } else {+                out.px[didx + 3] = 0;+            }+        }+    }+    Some(out)+}
camera/rust/src/bundle.rs
diff --git a/camera/rust/src/bundle.rs b/camera/rust/src/bundle.rsnew file mode 100644index 0000000000..4d2d3c9b44--- /dev/null+++ b/camera/rust/src/bundle.rs@@ -0,0 +1,194 @@+//! BundleAdjusterRay with geodesic Levenberg–Marquardt, using **block-sparse**+//! normal equations exactly as the structure demands: each correspondence's+//! residual depends only on its two cameras' 8 parameters, so JᵀJ and Jᵀr are+//! accumulated from per-edge 8-column blocks instead of a dense+//! (3·matches × 4·images) Jacobian. Rotations are optimized on SO(3)+//! (R ← exp(ω)·R, tangent re-linearized to 0 each iteration).++use crate::camera::{rodrigues_to_mat, CameraParams};+use crate::geometry::Pt;+use crate::matching::MatchInfo;+use nalgebra::{DMatrix, DVector, Matrix3, Vector3};+use rayon::prelude::*;++const CONF_THRESH: f64 = 1.0;+const MAX_ITERS: usize = 100;+const STEP: f64 = 1e-4;++struct Edge {+    i: usize,+    j: usize,+    corr: Vec<(Pt, Pt)>,+}++fn k_inv(focal: f64, ppx: f64, ppy: f64) -> Matrix3<f64> {+    Matrix3::new(+        1.0 / focal, 0.0, -ppx / focal,+        0.0, 1.0 / focal, -ppy / focal,+        0.0, 0.0, 1.0,+    )+}++/// A camera perturbed by a single tangent parameter (0 = focal, 1..3 = ω axis).+fn perturb(base: &CameraParams, j: usize, delta: f64) -> CameraParams {+    if j == 0 {+        CameraParams { focal: base.focal + delta, ..base.clone() }+    } else {+        let mut omega = Vector3::zeros();+        omega[j - 1] = delta;+        CameraParams { r: rodrigues_to_mat(omega) * base.r, ..base.clone() }+    }+}++/// Whole-camera geodesic increment: f += δf, R ← exp(ω)·R.+fn apply_increment(base: &[CameraParams], x: &DVector<f64>) -> Vec<CameraParams> {+    base.iter()+        .enumerate()+        .map(|(c, cam)| {+            let omega = Vector3::new(x[4 * c + 1], x[4 * c + 2], x[4 * c + 3]);+            CameraParams {+                focal: cam.focal + x[4 * c],+                aspect: 1.0,+                ppx: cam.ppx,+                ppy: cam.ppy,+                r: rodrigues_to_mat(omega) * cam.r,+            }+        })+        .collect()+}++/// Ray residuals (3 per correspondence) for one camera pair.+fn edge_res(ci: &CameraParams, cj: &CameraParams, corr: &[(Pt, Pt)]) -> Vec<f64> {+    let h1 = ci.r * k_inv(ci.focal, ci.ppx, ci.ppy);+    let h2 = cj.r * k_inv(cj.focal, cj.ppx, cj.ppy);+    let mult = (ci.focal * cj.focal).abs().sqrt();+    let mut out = vec![0.0f64; corr.len() * 3];+    for (idx, &(p1, p2)) in corr.iter().enumerate() {+        let mut r1 = h1 * Vector3::new(p1.0 as f64, p1.1 as f64, 1.0);+        let l1 = r1.norm();+        if l1 > 1e-12 {+            r1 /= l1;+        }+        let mut r2 = h2 * Vector3::new(p2.0 as f64, p2.1 as f64, 1.0);+        let l2 = r2.norm();+        if l2 > 1e-12 {+            r2 /= l2;+        }+        out[3 * idx] = mult * (r1.x - r2.x);+        out[3 * idx + 1] = mult * (r1.y - r2.y);+        out[3 * idx + 2] = mult * (r1.z - r2.z);+    }+    out+}++fn total_cost(cams: &[CameraParams], edges: &[Edge]) -> f64 {+    edges+        .par_iter()+        .map(|e| edge_res(&cams[e.i], &cams[e.j], &e.corr).iter().map(|v| v * v).sum::<f64>())+        .sum()+}++pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) {+    let n = cams.len();+    if n < 2 {+        return;+    }+    let edges: Vec<Edge> = matches+        .iter()+        .filter(|m| m.confidence > CONF_THRESH && !m.inliers.is_empty())+        .map(|m| Edge { i: m.src, j: m.dst, corr: m.inliers.clone() })+        .collect();+    if edges.is_empty() {+        return;+    }+    let nparams = 4 * n;+    let mut cost = total_cost(cams, &edges);+    let mut lambda = 1.0;++    for _ in 0..MAX_ITERS {+        // Block-sparse normal equations, accumulated per edge in parallel.+        let (jtj, jtr) = edges+            .par_iter()+            .map(|e| {+                let ca = &cams[e.i];+                let cb = &cams[e.j];+                let r = edge_res(ca, cb, &e.corr);+                let m = r.len();+                // 8 local Jacobian columns (cam i: 0..4, cam j: 4..8).+                let mut jb: Vec<Vec<f64>> = Vec::with_capacity(8);+                for c in 0..8 {+                    let (pj, is_i) = (c % 4, c < 4);+                    let (rp, rm) = if is_i {+                        (edge_res(&perturb(ca, pj, STEP), cb, &e.corr),+                         edge_res(&perturb(ca, pj, -STEP), cb, &e.corr))+                    } else {+                        (edge_res(ca, &perturb(cb, pj, STEP), &e.corr),+                         edge_res(ca, &perturb(cb, pj, -STEP), &e.corr))+                    };+                    let mut col = vec![0.0f64; m];+                    for t in 0..m {+                        col[t] = (rp[t] - rm[t]) / (2.0 * STEP);+                    }+                    jb.push(col);+                }+                let gcol = [+                    4 * e.i, 4 * e.i + 1, 4 * e.i + 2, 4 * e.i + 3,+                    4 * e.j, 4 * e.j + 1, 4 * e.j + 2, 4 * e.j + 3,+                ];+                let mut jtj = DMatrix::<f64>::zeros(nparams, nparams);+                let mut jtr = DVector::<f64>::zeros(nparams);+                for c1 in 0..8 {+                    let g1 = gcol[c1];+                    let mut s = 0.0;+                    for t in 0..m {+                        s += jb[c1][t] * r[t];+                    }+                    jtr[g1] += s;+                    for c2 in 0..8 {+                        let g2 = gcol[c2];+                        let mut s2 = 0.0;+                        for t in 0..m {+                            s2 += jb[c1][t] * jb[c2][t];+                        }+                        jtj[(g1, g2)] += s2;+                    }+                }+                (jtj, jtr)+            })+            .reduce(+                || (DMatrix::<f64>::zeros(nparams, nparams), DVector::<f64>::zeros(nparams)),+                |(mut a, mut b), (ja, jb)| {+                    a += ja;+                    b += jb;+                    (a, b)+                },+            );++        let mut improved = false;+        for _ in 0..10 {+            let mut a = jtj.clone();+            for d in 0..nparams {+                let diag = a[(d, d)];+                a[(d, d)] = diag + lambda * diag.max(1e-6);+            }+            let dx = match a.clone().lu().solve(&(-&jtr)) {+                Some(v) => v,+                None => break,+            };+            let trial = apply_increment(cams, &dx);+            let cost_new = total_cost(&trial, &edges);+            if cost_new < cost {+                *cams = trial;+                cost = cost_new;+                lambda = (lambda * 0.1).max(1e-12);+                improved = true;+                break;+            } else {+                lambda = (lambda * 10.0).min(1e12);+            }+        }+        if !improved {+            break;+        }+    }+}
camera/rust/src/camera.rs
diff --git a/camera/rust/src/camera.rs b/camera/rust/src/camera.rsnew file mode 100644index 0000000000..ea5e2cc990--- /dev/null+++ b/camera/rust/src/camera.rs@@ -0,0 +1,74 @@+//! Camera parameters and helpers, mirroring cv::detail::CameraParams and the+//! Rodrigues rotation conversions used by the estimators / bundle adjuster.++use nalgebra::{Matrix3, Vector3};++#[derive(Clone)]+pub struct CameraParams {+    pub focal: f64,+    pub aspect: f64,+    pub ppx: f64,+    pub ppy: f64,+    pub r: Matrix3<f64>, // rotation+}++impl CameraParams {+    pub fn k(&self) -> Matrix3<f64> {+        Matrix3::new(+            self.focal, 0.0, self.ppx,+            0.0, self.focal * self.aspect, self.ppy,+            0.0, 0.0, 1.0,+        )+    }+}++/// Rodrigues: rotation vector -> matrix (cv::Rodrigues).+pub fn rodrigues_to_mat(rvec: Vector3<f64>) -> Matrix3<f64> {+    let theta = rvec.norm();+    if theta < 1e-12 {+        return Matrix3::identity();+    }+    let r = rvec / theta;+    let (s, c) = theta.sin_cos();+    let c1 = 1.0 - c;+    let (x, y, z) = (r.x, r.y, r.z);+    Matrix3::new(+        c + x * x * c1,       x * y * c1 - z * s,   x * z * c1 + y * s,+        y * x * c1 + z * s,   c + y * y * c1,       y * z * c1 - x * s,+        z * x * c1 - y * s,   z * y * c1 + x * s,   c + z * z * c1,+    )+}++/// Rodrigues: rotation matrix -> vector (cv::Rodrigues inverse).+pub fn mat_to_rodrigues(m: &Matrix3<f64>) -> Vector3<f64> {+    // Force orthonormal via SVD first for stability.+    let r = {+        let svd = m.svd(true, true);+        match (svd.u, svd.v_t) {+            (Some(u), Some(vt)) => u * vt,+            _ => *m,+        }+    };+    let rx = r[(2, 1)] - r[(1, 2)];+    let ry = r[(0, 2)] - r[(2, 0)];+    let rz = r[(1, 0)] - r[(0, 1)];+    let s = ((rx * rx + ry * ry + rz * rz) * 0.25).sqrt();+    let trace = r[(0, 0)] + r[(1, 1)] + r[(2, 2)];+    let c = ((trace - 1.0) * 0.5).clamp(-1.0, 1.0);+    let theta = c.acos();+    if s < 1e-9 {+        if theta < 1e-9 {+            return Vector3::zeros();+        }+        // theta ~ pi: extract axis from diagonal+        let xx = (r[(0, 0)] + 1.0) * 0.5;+        let yy = (r[(1, 1)] + 1.0) * 0.5;+        let zz = (r[(2, 2)] + 1.0) * 0.5;+        let ax = xx.max(0.0).sqrt();+        let ay = yy.max(0.0).sqrt() * if r[(0, 1)] < 0.0 { -1.0 } else { 1.0 };+        let az = zz.max(0.0).sqrt() * if r[(0, 2)] < 0.0 { -1.0 } else { 1.0 };+        return Vector3::new(ax, ay, az) * theta;+    }+    let mult = theta / (2.0 * s);+    Vector3::new(rx, ry, rz) * mult+}
camera/rust/src/estimator.rs
diff --git a/camera/rust/src/estimator.rs b/camera/rust/src/estimator.rsnew file mode 100644index 0000000000..2e5bafe168--- /dev/null+++ b/camera/rust/src/estimator.rs@@ -0,0 +1,69 @@+//! HomographyBasedEstimator (motion_estimators.cpp): estimate a shared focal+//! from pairwise homographies, then chain per-image rotations along a maximum+//! spanning tree of match confidences rooted at the central image.++use crate::camera::CameraParams;+use crate::matching::MatchInfo;+use crate::sphere::{estimate_focal, k_matrix, orthonormalize};+use nalgebra::Matrix3;++pub fn estimate_cameras(n: usize, w: usize, h: usize, matches: &[MatchInfo]) -> Vec<CameraParams> {+    let hs: Vec<Matrix3<f64>> = matches.iter().map(|m| m.h).collect();+    let focal = estimate_focal(&hs, w, h);+    let ppx = w as f64 / 2.0;+    let ppy = h as f64 / 2.0;+    let k = k_matrix(focal, ppx, ppy);+    let k_inv = k.try_inverse().unwrap_or_else(Matrix3::identity);++    // adjacency: node -> Vec<(neighbor, confidence, H_node->neighbor)>+    let mut adj: Vec<Vec<(usize, f64, Matrix3<f64>)>> = vec![Vec::new(); n];+    for m in matches {+        adj[m.src].push((m.dst, m.confidence, m.h));+        if let Some(hinv) = m.h.try_inverse() {+            adj[m.dst].push((m.src, m.confidence, hinv));+        }+    }++    let mut cams: Vec<CameraParams> = (0..n)+        .map(|_| CameraParams { focal, aspect: 1.0, ppx, ppy, r: Matrix3::identity() })+        .collect();++    // Prim's maximum spanning tree from the central node.+    let root = n / 2;+    let mut in_tree = vec![false; n];+    in_tree[root] = true;+    cams[root].r = Matrix3::identity();+    let mut added = 1;+    while added < n {+        // find the highest-confidence edge from a tree node to a non-tree node+        let mut best: Option<(usize, usize, Matrix3<f64>, f64)> = None; // (u, v, H_u->v, conf)+        for u in 0..n {+            if !in_tree[u] {+                continue;+            }+            for &(v, conf, huv) in &adj[u] {+                if in_tree[v] {+                    continue;+                }+                if best.map_or(true, |(_, _, _, bc)| conf > bc) {+                    best = Some((u, v, huv, conf));+                }+            }+        }+        match best {+            Some((u, v, huv, _)) => {+                // OpenCV CalcRotation: R = K_from^-1 * H_{from->to}^-1 * K_to;+                //                      cameras[to].R = cameras[from].R * R+                let rel = huv+                    .try_inverse()+                    .map(|hinv| k_inv * hinv * k)+                    .unwrap_or_else(Matrix3::identity);+                cams[v].r = orthonormalize(&(cams[u].r * rel));+                in_tree[v] = true;+                added += 1;+            }+            None => break, // disconnected remainder (shouldn't happen after biggest_component)+        }+    }+    cams+}
camera/rust/src/exposure.rs
diff --git a/camera/rust/src/exposure.rs b/camera/rust/src/exposure.rsnew file mode 100644index 0000000000..f1233ccbd5--- /dev/null+++ b/camera/rust/src/exposure.rs@@ -0,0 +1,132 @@+//! Exposure compensation. `compensate` implements BlocksGainCompensator+//! (exposure_compensate.cpp): each warped image is split into a block grid, a+//! per-block gain is solved from pairwise block overlaps (same normal equations+//! as GainCompensator but over blocks), and the block gains are bilinearly+//! upsampled to a smooth per-pixel gain map applied by the blender.++use crate::sphere::WarpedTile;+use nalgebra::{DMatrix, DVector};++const ALPHA: f64 = 0.01;+const BETA: f64 = 100.0;+const MAX_NODES: usize = 640; // bound the dense solve++#[inline]+fn luma(c: [u8; 4]) -> f64 {+    0.299 * c[0] as f64 + 0.587 * c[1] as f64 + 0.114 * c[2] as f64+}++/// Per-tile per-pixel gain maps (len = tile.img.w*tile.img.h each).+pub fn compensate(tiles: &[WarpedTile]) -> Vec<Vec<f32>> {+    let num = tiles.len();+    if num == 0 {+        return Vec::new();+    }+    // Block grid per tile, sized so the total node count stays bounded.+    let g = ((MAX_NODES as f64 / num as f64).sqrt().floor() as usize).clamp(1, 8);+    let per_tile = g * g;+    let total = num * per_tile;+    let node = |t: usize, bx: usize, by: usize| t * per_tile + by * g + bx;++    // block index of a local pixel in a tile+    let block_of = |t: usize, lx: usize, ly: usize| -> (usize, usize) {+        let bx = (lx * g / tiles[t].img.w.max(1)).min(g - 1);+        let by = (ly * g / tiles[t].img.h.max(1)).min(g - 1);+        (bx, by)+    };++    // Pairwise block-overlap accumulation.+    let mut nmat = vec![0f64; total * total];+    let mut sum = vec![0f64; total * total]; // sum[p*total+q] = Σ intensity of node p's tile over overlap with node q's tile++    for i in 0..num {+        for j in (i + 1)..num {+            let ti = &tiles[i];+            let tj = &tiles[j];+            let x0 = ti.corner_x.max(tj.corner_x);+            let y0 = ti.corner_y.max(tj.corner_y);+            let x1 = (ti.corner_x + ti.img.w as i32).min(tj.corner_x + tj.img.w as i32);+            let y1 = (ti.corner_y + ti.img.h as i32).min(tj.corner_y + tj.img.h as i32);+            if x0 >= x1 || y0 >= y1 {+                continue;+            }+            for gy in y0..y1 {+                for gx in x0..x1 {+                    let (lix, liy) = ((gx - ti.corner_x) as usize, (gy - ti.corner_y) as usize);+                    let (ljx, ljy) = ((gx - tj.corner_x) as usize, (gy - tj.corner_y) as usize);+                    let ca = ti.img.get(lix, liy);+                    let cb = tj.img.get(ljx, ljy);+                    if ca[3] == 0 || cb[3] == 0 {+                        continue;+                    }+                    let (bix, biy) = block_of(i, lix, liy);+                    let (bjx, bjy) = block_of(j, ljx, ljy);+                    let p = node(i, bix, biy);+                    let q = node(j, bjx, bjy);+                    nmat[p * total + q] += 1.0;+                    nmat[q * total + p] += 1.0;+                    sum[p * total + q] += luma(ca);+                    sum[q * total + p] += luma(cb);+                }+            }+        }+    }++    // Build normal equations A·g = b over all blocks.+    let mut a = DMatrix::<f64>::zeros(total, total);+    let mut b = DVector::<f64>::zeros(total);+    for p in 0..total {+        // regularization so isolated blocks default to gain 1+        a[(p, p)] += 1e-3;+        b[p] += 1e-3;+        for q in 0..total {+            let n = nmat[p * total + q];+            if n <= 0.0 {+                continue;+            }+            let ipq = sum[p * total + q] / n; // mean intensity of p over overlap+            let iqp = sum[q * total + p] / n; // mean intensity of q over overlap+            b[p] += BETA * n;+            a[(p, p)] += BETA * n;+            a[(p, p)] += 2.0 * ALPHA * ipq * ipq * n;+            a[(p, q)] -= 2.0 * ALPHA * ipq * iqp * n;+        }+    }++    let block_gains: Vec<f64> = match a.lu().solve(&b) {+        Some(g) => (0..total).map(|i| if g[i].is_finite() && g[i] > 0.0 { g[i] } else { 1.0 }).collect(),+        None => vec![1.0; total],+    };++    // Bilinearly upsample each tile's g×g block gains to a per-pixel map.+    tiles+        .iter()+        .enumerate()+        .map(|(t, tile)| {+            let w = tile.img.w;+            let h = tile.img.h;+            let mut map = vec![1.0f32; w * h];+            for y in 0..h {+                // block-center coords+                let fy = (y as f64 * g as f64 / h as f64 - 0.5).clamp(0.0, g as f64 - 1.0);+                let by0 = fy.floor() as usize;+                let by1 = (by0 + 1).min(g - 1);+                let ay = (fy - by0 as f64) as f32;+                for x in 0..w {+                    let fx = (x as f64 * g as f64 / w as f64 - 0.5).clamp(0.0, g as f64 - 1.0);+                    let bx0 = fx.floor() as usize;+                    let bx1 = (bx0 + 1).min(g - 1);+                    let ax = (fx - bx0 as f64) as f32;+                    let g00 = block_gains[node(t, bx0, by0)] as f32;+                    let g10 = block_gains[node(t, bx1, by0)] as f32;+                    let g01 = block_gains[node(t, bx0, by1)] as f32;+                    let g11 = block_gains[node(t, bx1, by1)] as f32;+                    let top = g00 * (1.0 - ax) + g10 * ax;+                    let bot = g01 * (1.0 - ax) + g11 * ax;+                    map[y * w + x] = (top * (1.0 - ay) + bot * ay).clamp(0.25, 4.0);+                }+            }+            map+        })+        .collect()+}
camera/rust/src/features.rs
diff --git a/camera/rust/src/features.rs b/camera/rust/src/features.rsnew file mode 100644index 0000000000..7e0de4a253--- /dev/null+++ b/camera/rust/src/features.rs@@ -0,0 +1,207 @@+//! Oriented-FAST + rotated-BRIEF (ORB-style) feature detection and matching.++use crate::imgbuf::Gray;++pub struct KeyPoint {+    pub x: f32,+    pub y: f32,+    pub angle: f32,+    pub score: f32,+}++pub struct Features {+    pub kps: Vec<KeyPoint>,+    pub desc: Vec<[u8; 32]>, // 256-bit BRIEF+}++// Bresenham circle of radius 3 (16 pixels), clockwise from top.+const CIRCLE: [(i32, i32); 16] = [+    (0, -3), (1, -3), (2, -2), (3, -1), (3, 0), (3, 1), (2, 2), (1, 3),+    (0, 3), (-1, 3), (-2, 2), (-3, 1), (-3, 0), (-3, -1), (-2, -2), (-1, -3),+];++const PATCH_R: i32 = 15;++/// Deterministic BRIEF sampling pattern: 256 point pairs within the patch.+fn brief_pattern() -> Vec<((i32, i32), (i32, i32))> {+    // Simple LCG for reproducible pseudo-random pairs.+    let mut state: u64 = 0x9E3779B97F4A7C15;+    let mut next = || {+        state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+        ((state >> 33) as i64) as i32+    };+    let span = PATCH_R - 2; // keep pairs inside patch after rotation+    let mut pairs = Vec::with_capacity(256);+    for _ in 0..256 {+        let ax = (next().rem_euclid(2 * span + 1)) - span;+        let ay = (next().rem_euclid(2 * span + 1)) - span;+        let bx = (next().rem_euclid(2 * span + 1)) - span;+        let by = (next().rem_euclid(2 * span + 1)) - span;+        pairs.push(((ax, ay), (bx, by)));+    }+    pairs+}++#[inline]+fn fast_score(g: &Gray, x: i32, y: i32) -> i32 {+    let c = g.at(x as usize, y as usize) as i32;+    let mut s = 0;+    for &(dx, dy) in CIRCLE.iter() {+        let p = g.at((x + dx) as usize, (y + dy) as usize) as i32;+        s += (p - c).abs();+    }+    s+}++#[inline]+fn is_corner(g: &Gray, x: i32, y: i32, t: i32) -> bool {+    let c = g.at(x as usize, y as usize) as i32;+    // High-speed rejection test on pixels 1,5,9,13 (indices 0,4,8,12).+    let p0 = g.at((x + CIRCLE[0].0) as usize, (y + CIRCLE[0].1) as usize) as i32;+    let p8 = g.at((x + CIRCLE[8].0) as usize, (y + CIRCLE[8].1) as usize) as i32;+    let p4 = g.at((x + CIRCLE[4].0) as usize, (y + CIRCLE[4].1) as usize) as i32;+    let p12 = g.at((x + CIRCLE[12].0) as usize, (y + CIRCLE[12].1) as usize) as i32;+    let brighter = |p: i32| p > c + t;+    let darker = |p: i32| p < c - t;+    let nb = brighter(p0) as i32 + brighter(p4) as i32 + brighter(p8) as i32 + brighter(p12) as i32;+    let nd = darker(p0) as i32 + darker(p4) as i32 + darker(p8) as i32 + darker(p12) as i32;+    if nb < 3 && nd < 3 {+        return false;+    }+    // Full contiguous-9 test around the ring (wrap-around).+    let mut vals = [0i32; 16];+    for k in 0..16 {+        vals[k] = g.at((x + CIRCLE[k].0) as usize, (y + CIRCLE[k].1) as usize) as i32;+    }+    for start in 0..16 {+        let mut all_b = true;+        let mut all_d = true;+        for j in 0..9 {+            let v = vals[(start + j) % 16];+            if !(v > c + t) { all_b = false; }+            if !(v < c - t) { all_d = false; }+        }+        if all_b || all_d {+            return true;+        }+    }+    false+}++fn orientation(g: &Gray, x: i32, y: i32) -> f32 {+    let mut m01 = 0i64;+    let mut m10 = 0i64;+    for dy in -PATCH_R..=PATCH_R {+        for dx in -PATCH_R..=PATCH_R {+            if dx * dx + dy * dy > PATCH_R * PATCH_R {+                continue;+            }+            let v = g.at((x + dx) as usize, (y + dy) as usize) as i64;+            m10 += dx as i64 * v;+            m01 += dy as i64 * v;+        }+    }+    (m01 as f32).atan2(m10 as f32)+}++pub fn detect_and_describe(g: &Gray, max_features: usize, threshold: i32) -> Features {+    let border = PATCH_R + 1;+    if g.w as i32 <= 2 * border || g.h as i32 <= 2 * border {+        return Features { kps: Vec::new(), desc: Vec::new() };+    }+    // 1) detect corners with scores+    let mut cand: Vec<(i32, i32, i32)> = Vec::new();+    for y in border..(g.h as i32 - border) {+        for x in border..(g.w as i32 - border) {+            if is_corner(g, x, y, threshold) {+                cand.push((x, y, fast_score(g, x, y)));+            }+        }+    }+    // 2) grid-bucketed non-max suppression, then cap by score+    cand.sort_by(|a, b| b.2.cmp(&a.2));+    let cell = 8i32;+    let gw = (g.w as i32 / cell) + 1;+    let gh = (g.h as i32 / cell) + 1;+    let mut occupied = vec![false; (gw * gh) as usize];+    let mut kept: Vec<(i32, i32)> = Vec::new();+    for (x, y, _s) in cand {+        let cx = x / cell;+        let cy = y / cell;+        let idx = (cy * gw + cx) as usize;+        if occupied[idx] {+            continue;+        }+        occupied[idx] = true;+        kept.push((x, y));+        if kept.len() >= max_features {+            break;+        }+    }+    // 3) describe+    let pattern = brief_pattern();+    let mut kps = Vec::with_capacity(kept.len());+    let mut desc = Vec::with_capacity(kept.len());+    for (x, y) in kept {+        let angle = orientation(g, x, y);+        let (sin, cos) = angle.sin_cos();+        let mut d = [0u8; 32];+        for (bit, &((ax, ay), (bx, by))) in pattern.iter().enumerate() {+            let rax = (ax as f32 * cos - ay as f32 * sin).round() as i32;+            let ray = (ax as f32 * sin + ay as f32 * cos).round() as i32;+            let rbx = (bx as f32 * cos - by as f32 * sin).round() as i32;+            let rby = (bx as f32 * sin + by as f32 * cos).round() as i32;+            let pa = sample_clamped(g, x + rax, y + ray);+            let pb = sample_clamped(g, x + rbx, y + rby);+            if pa < pb {+                d[bit / 8] |= 1 << (bit % 8);+            }+        }+        kps.push(KeyPoint { x: x as f32, y: y as f32, angle, score: 0.0 });+        desc.push(d);+    }+    Features { kps, desc }+}++#[inline]+fn sample_clamped(g: &Gray, x: i32, y: i32) -> i32 {+    let xx = x.clamp(0, g.w as i32 - 1) as usize;+    let yy = y.clamp(0, g.h as i32 - 1) as usize;+    g.at(xx, yy) as i32+}++#[inline]+fn hamming(a: &[u8; 32], b: &[u8; 32]) -> u32 {+    let mut d = 0u32;+    for i in 0..32 {+        d += (a[i] ^ b[i]).count_ones();+    }+    d+}++/// Brute-force match a->b with Lowe ratio test. Returns (index_in_a, index_in_b).+pub fn match_features(a: &Features, b: &Features, ratio: f32) -> Vec<(usize, usize)> {+    let mut out = Vec::new();+    if a.desc.is_empty() || b.desc.is_empty() {+        return out;+    }+    for (i, da) in a.desc.iter().enumerate() {+        let mut best = u32::MAX;+        let mut second = u32::MAX;+        let mut best_j = usize::MAX;+        for (j, db) in b.desc.iter().enumerate() {+            let d = hamming(da, db);+            if d < best {+                second = best;+                best = d;+                best_j = j;+            } else if d < second {+                second = d;+            }+        }+        if best_j != usize::MAX && (best as f32) < ratio * (second as f32) {+            out.push((i, best_j));+        }+    }+    out+}
camera/rust/src/geometry.rs
diff --git a/camera/rust/src/geometry.rs b/camera/rust/src/geometry.rsnew file mode 100644index 0000000000..166a996097--- /dev/null+++ b/camera/rust/src/geometry.rs@@ -0,0 +1,161 @@+//! Homography estimation (normalized DLT) with RANSAC.++use nalgebra::{DMatrix, Matrix3, Vector3};++pub type Pt = (f32, f32);++struct Lcg(u64);+impl Lcg {+    fn new(seed: u64) -> Self {+        Lcg(seed | 1)+    }+    fn next_usize(&mut self, n: usize) -> usize {+        self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+        ((self.0 >> 33) as usize) % n.max(1)+    }+}++/// Isotropic normalization (Hartley): returns (T, normalized points).+fn normalize(pts: &[Pt]) -> (Matrix3<f64>, Vec<(f64, f64)>) {+    let n = pts.len().max(1) as f64;+    let (mut mx, mut my) = (0.0, 0.0);+    for &(x, y) in pts {+        mx += x as f64;+        my += y as f64;+    }+    mx /= n;+    my /= n;+    let mut mean_dist = 0.0;+    for &(x, y) in pts {+        let dx = x as f64 - mx;+        let dy = y as f64 - my;+        mean_dist += (dx * dx + dy * dy).sqrt();+    }+    mean_dist /= n;+    let s = if mean_dist > 1e-8 { (2.0f64).sqrt() / mean_dist } else { 1.0 };+    let t = Matrix3::new(s, 0.0, -s * mx, 0.0, s, -s * my, 0.0, 0.0, 1.0);+    let out = pts.iter().map(|&(x, y)| (s * (x as f64 - mx), s * (y as f64 - my))).collect();+    (t, out)+}++/// Homography mapping a -> b from >=4 correspondences via normalized DLT.+fn dlt(a: &[Pt], b: &[Pt]) -> Option<Matrix3<f64>> {+    if a.len() < 4 || a.len() != b.len() {+        return None;+    }+    let (ta, na) = normalize(a);+    let (tb, nb) = normalize(b);+    let mut m = DMatrix::<f64>::zeros(2 * a.len(), 9);+    for i in 0..a.len() {+        let (x, y) = na[i];+        let (u, v) = nb[i];+        m[(2 * i, 0)] = -x;+        m[(2 * i, 1)] = -y;+        m[(2 * i, 2)] = -1.0;+        m[(2 * i, 6)] = u * x;+        m[(2 * i, 7)] = u * y;+        m[(2 * i, 8)] = u;+        m[(2 * i + 1, 3)] = -x;+        m[(2 * i + 1, 4)] = -y;+        m[(2 * i + 1, 5)] = -1.0;+        m[(2 * i + 1, 6)] = v * x;+        m[(2 * i + 1, 7)] = v * y;+        m[(2 * i + 1, 8)] = v;+    }+    let svd = m.svd(true, true);+    let vt = svd.v_t?;+    let h = vt.row(vt.nrows() - 1);+    let hn = Matrix3::new(+        h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7], h[8],+    );+    // Denormalize: H = Tb^-1 * Hn * Ta+    let tb_inv = tb.try_inverse()?;+    let mut hd = tb_inv * hn * ta;+    if hd[(2, 2)].abs() > 1e-12 {+        hd /= hd[(2, 2)];+    }+    Some(hd)+}++#[inline]+fn apply(h: &Matrix3<f64>, p: Pt) -> (f64, f64) {+    let v = h * Vector3::new(p.0 as f64, p.1 as f64, 1.0);+    if v.z.abs() < 1e-12 {+        (v.x, v.y)+    } else {+        (v.x / v.z, v.y / v.z)+    }+}++/// Indices of correspondences whose transfer error under `h` is below `thresh`.+pub fn transfer_inliers(h: &Matrix3<f64>, a: &[Pt], b: &[Pt], thresh: f32) -> Vec<usize> {+    let thr2 = (thresh * thresh) as f64;+    let mut v = Vec::new();+    for i in 0..a.len().min(b.len()) {+        let (px, py) = apply(h, a[i]);+        let dx = px - b[i].0 as f64;+        let dy = py - b[i].1 as f64;+        if dx * dx + dy * dy < thr2 {+            v.push(i);+        }+    }+    v+}++/// RANSAC homography a->b. Returns (H, inlier_count).+pub fn find_homography_ransac(a: &[Pt], b: &[Pt], iters: usize, thresh: f32) -> Option<(Matrix3<f64>, usize)> {+    let n = a.len();+    if n < 4 || n != b.len() {+        return None;+    }+    let thr2 = (thresh * thresh) as f64;+    let mut rng = Lcg::new(0xC0FFEE ^ n as u64);+    let mut best_h: Option<Matrix3<f64>> = None;+    let mut best_inliers: Vec<usize> = Vec::new();++    for _ in 0..iters {+        // sample 4 distinct indices+        let mut idx = [0usize; 4];+        let mut ok = true;+        for k in 0..4 {+            idx[k] = rng.next_usize(n);+            for j in 0..k {+                if idx[j] == idx[k] {+                    ok = false;+                }+            }+        }+        if !ok {+            continue;+        }+        let sa: Vec<Pt> = idx.iter().map(|&i| a[i]).collect();+        let sb: Vec<Pt> = idx.iter().map(|&i| b[i]).collect();+        let h = match dlt(&sa, &sb) {+            Some(h) => h,+            None => continue,+        };+        let mut inliers = Vec::new();+        for i in 0..n {+            let (px, py) = apply(&h, a[i]);+            let dx = px - b[i].0 as f64;+            let dy = py - b[i].1 as f64;+            if dx * dx + dy * dy < thr2 {+                inliers.push(i);+            }+        }+        if inliers.len() > best_inliers.len() {+            best_inliers = inliers;+            best_h = Some(h);+        }+    }++    let inliers = best_inliers;+    if inliers.len() < 8 {+        return best_h.map(|h| (h, inliers.len()));+    }+    // Refit on all inliers.+    let ia: Vec<Pt> = inliers.iter().map(|&i| a[i]).collect();+    let ib: Vec<Pt> = inliers.iter().map(|&i| b[i]).collect();+    let refined = dlt(&ia, &ib).or(best_h)?;+    Some((refined, inliers.len()))+}
camera/rust/src/imgbuf.rs
diff --git a/camera/rust/src/imgbuf.rs b/camera/rust/src/imgbuf.rsnew file mode 100644index 0000000000..c854679c58--- /dev/null+++ b/camera/rust/src/imgbuf.rs@@ -0,0 +1,122 @@+//! Minimal image buffers and sampling helpers (kept dependency-free so the CV+//! code is fully under our control; the `image` crate is only used for the final+//! JPEG encode).++/// Interleaved 8-bit RGBA image.+#[derive(Clone)]+pub struct Rgba {+    pub w: usize,+    pub h: usize,+    pub px: Vec<u8>, // len = w*h*4+}++impl Rgba {+    pub fn new(w: usize, h: usize) -> Self {+        Rgba { w, h, px: vec![0u8; w * h * 4] }+    }++    pub fn from_bytes(w: usize, h: usize, px: Vec<u8>) -> Self {+        debug_assert_eq!(px.len(), w * h * 4);+        Rgba { w, h, px }+    }++    #[inline]+    pub fn get(&self, x: usize, y: usize) -> [u8; 4] {+        let i = (y * self.w + x) * 4;+        [self.px[i], self.px[i + 1], self.px[i + 2], self.px[i + 3]]+    }++    /// Bilinear-resampled copy at a new size. Used to run the (slow) registration+    /// stage — features, matching, bundle adjustment — at a reduced resolution.+    pub fn resized(&self, nw: usize, nh: usize) -> Rgba {+        let nw = nw.max(1);+        let nh = nh.max(1);+        let mut out = Rgba::new(nw, nh);+        let sx = self.w as f32 / nw as f32;+        let sy = self.h as f32 / nh as f32;+        for y in 0..nh {+            let fy = ((y as f32 + 0.5) * sy - 0.5).max(0.0);+            for x in 0..nw {+                let fx = ((x as f32 + 0.5) * sx - 0.5).max(0.0);+                let c = self.sample(fx, fy).unwrap_or([0.0, 0.0, 0.0, 0.0]);+                out.set(x, y, [+                    c[0].round().clamp(0.0, 255.0) as u8,+                    c[1].round().clamp(0.0, 255.0) as u8,+                    c[2].round().clamp(0.0, 255.0) as u8,+                    255,+                ]);+            }+        }+        out+    }++    #[inline]+    pub fn set(&mut self, x: usize, y: usize, c: [u8; 4]) {+        let i = (y * self.w + x) * 4;+        self.px[i] = c[0];+        self.px[i + 1] = c[1];+        self.px[i + 2] = c[2];+        self.px[i + 3] = c[3];+    }++    /// Bilinear RGBA sample; returns None if out of bounds or the sampled+    /// neighbourhood is fully transparent.+    #[inline]+    pub fn sample(&self, fx: f32, fy: f32) -> Option<[f32; 4]> {+        if fx < 0.0 || fy < 0.0 || fx > (self.w - 1) as f32 || fy > (self.h - 1) as f32 {+            return None;+        }+        let x0 = fx.floor() as usize;+        let y0 = fy.floor() as usize;+        let x1 = (x0 + 1).min(self.w - 1);+        let y1 = (y0 + 1).min(self.h - 1);+        let ax = fx - x0 as f32;+        let ay = fy - y0 as f32;+        let mut out = [0f32; 4];+        let c00 = self.get(x0, y0);+        let c10 = self.get(x1, y0);+        let c01 = self.get(x0, y1);+        let c11 = self.get(x1, y1);+        // If every corner is fully transparent, treat as no data.+        if c00[3] == 0 && c10[3] == 0 && c01[3] == 0 && c11[3] == 0 {+            return None;+        }+        for k in 0..4 {+            let top = c00[k] as f32 * (1.0 - ax) + c10[k] as f32 * ax;+            let bot = c01[k] as f32 * (1.0 - ax) + c11[k] as f32 * ax;+            out[k] = top * (1.0 - ay) + bot * ay;+        }+        Some(out)+    }+}++/// 8-bit single-channel image.+#[derive(Clone)]+pub struct Gray {+    pub w: usize,+    pub h: usize,+    pub px: Vec<u8>,+}++impl Gray {+    pub fn new(w: usize, h: usize) -> Self {+        Gray { w, h, px: vec![0u8; w * h] }+    }++    #[inline]+    pub fn at(&self, x: usize, y: usize) -> u8 {+        self.px[y * self.w + x]+    }+}++/// Rec.601 luma from an RGBA image.+pub fn to_gray(img: &Rgba) -> Gray {+    let mut g = Gray::new(img.w, img.h);+    for i in 0..img.w * img.h {+        let r = img.px[i * 4] as u32;+        let gg = img.px[i * 4 + 1] as u32;+        let b = img.px[i * 4 + 2] as u32;+        g.px[i] = ((r * 77 + gg * 150 + b * 29) >> 8) as u8;+    }+    g+}
camera/rust/src/lib.rs
diff --git a/camera/rust/src/lib.rs b/camera/rust/src/lib.rsnew file mode 100644index 0000000000..c41cd417b6--- /dev/null+++ b/camera/rust/src/lib.rs@@ -0,0 +1,232 @@+//! Camera stitching native library: feature-based panorama stitcher + night+//! burst aligner, exposed to Kotlin via JNI. Replaces the OpenCV dependency.++mod imgbuf;+mod features;+mod geometry;+mod camera;+mod matching;+mod estimator;+mod bundle;+mod wave;+mod warp;+mod sphere;+mod exposure;+mod seam;+mod blend;+mod stitch;+mod night;++use imgbuf::Rgba;+use std::collections::HashMap;+use std::sync::{Mutex, OnceLock};++struct Session {+    sphere: bool,+    frames: Vec<Rgba>,+    yaw: Vec<f32>,+    pitch: Vec<f32>,+}++fn registry() -> &'static Mutex<HashMap<i64, Session>> {+    static REG: OnceLock<Mutex<HashMap<i64, Session>>> = OnceLock::new();+    REG.get_or_init(|| Mutex::new(HashMap::new()))+}++fn next_handle() -> i64 {+    static CTR: OnceLock<Mutex<i64>> = OnceLock::new();+    let m = CTR.get_or_init(|| Mutex::new(1));+    let mut g = m.lock().unwrap();+    let h = *g;+    *g += 1;+    h+}++/// Encode an RGBA image to JPEG bytes (alpha dropped).+fn encode_jpeg(img: &Rgba, quality: u8) -> Option<Vec<u8>> {+    use image::codecs::jpeg::JpegEncoder;+    use image::{ExtendedColorType, ImageEncoder};+    let mut rgb = vec![0u8; img.w * img.h * 3];+    for i in 0..img.w * img.h {+        rgb[i * 3] = img.px[i * 4];+        rgb[i * 3 + 1] = img.px[i * 4 + 1];+        rgb[i * 3 + 2] = img.px[i * 4 + 2];+    }+    let mut buf = Vec::new();+    let enc = JpegEncoder::new_with_quality(&mut buf, quality);+    enc.write_image(&rgb, img.w as u32, img.h as u32, ExtendedColorType::Rgb8)+        .ok()?;+    Some(buf)+}++// Pure-Rust API (also usable from host `cargo test`).+fn do_stitch(s: &mut Session) -> Option<Vec<u8>> {+    let frames = std::mem::take(&mut s.frames);+    let yaw = std::mem::take(&mut s.yaw);+    let pitch = std::mem::take(&mut s.pitch);+    let _ = s.sphere; // sphere vs cylindrical handled by the (planar-chain) pipeline for now+    let result = stitch::stitch_panorama(&frames, &yaw, &pitch)?;+    encode_jpeg(&result, 92)+}++fn do_merge(s: &mut Session) -> Option<Vec<u8>> {+    let frames = std::mem::take(&mut s.frames);+    let result = night::align_and_merge(&frames)?;+    encode_jpeg(&result, 95)+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::imgbuf::Rgba;++    fn load(path: &str) -> Rgba {+        let img = image::ImageReader::open(path)+            .expect("open image")+            .decode()+            .expect("decode image")+            .to_rgba8();+        let (w, h) = img.dimensions();+        Rgba::from_bytes(w as usize, h as usize, img.into_raw())+    }++    /// Stitches the two sample photos from linrl3/Image-Stitching-OpenCV and+    /// writes the result to testdata/output.jpg for visual comparison against+    /// testdata/panorama.jpg. Run with:  cargo test stitch_two_samples -- --nocapture+    #[test]+    fn stitch_two_samples() {+        let a = load("testdata/q11.jpg");+        let b = load("testdata/q22.jpg");+        let (aw, ah) = (a.w, a.h);+        let t0 = std::time::Instant::now();+        let out = crate::stitch::stitch_panorama(&[a, b], &[0.0, 0.0], &[0.0, 0.0])+            .expect("stitch returned None");+        let dt = t0.elapsed();+        let jpeg = encode_jpeg(&out, 92).expect("encode");+        std::fs::write("testdata/output.jpg", &jpeg).expect("write output");+        eprintln!(+            "inputs {aw}x{ah}; stitched {}x{} in {:?} -> testdata/output.jpg ({} KB)",+            out.w,+            out.h,+            dt,+            jpeg.len() / 1024+        );+        // The inputs are portrait (aspect < 1); a real two-frame panorama must be+        // much wider relative to its height. (Output pixel size is memory-capped,+        // so compare aspect ratios rather than absolute width.)+        let in_aspect = aw as f32 / ah as f32;+        let out_aspect = out.w as f32 / out.h as f32;+        assert!(+            out_aspect > in_aspect * 1.4,+            "output aspect {out_aspect:.2} not panoramic vs input {in_aspect:.2} ({}x{})",+            out.w,+            out.h+        );+    }+}++#[cfg(not(test))]+mod jni_bindings {+    use super::*;+    use jni::objects::{JByteArray, JClass};+    use jni::sys::{jboolean, jbyteArray, jfloat, jint, jlong};+    use jni::JNIEnv;++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_newSession<'l>(+        _env: JNIEnv<'l>,+        _class: JClass<'l>,+        sphere: jboolean,+    ) -> jlong {+        let h = next_handle();+        registry().lock().unwrap().insert(+            h,+            Session { sphere: sphere != 0, frames: Vec::new(), yaw: Vec::new(), pitch: Vec::new() },+        );+        h+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_addFrame<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+        rgba: JByteArray<'l>,+        width: jint,+        height: jint,+        yaw: jfloat,+        pitch: jfloat,+        _roll: jfloat,+    ) {+        let bytes = match env.convert_byte_array(&rgba) {+            Ok(b) => b,+            Err(_) => return,+        };+        let (w, h) = (width as usize, height as usize);+        if bytes.len() != w * h * 4 {+            return;+        }+        if let Some(s) = registry().lock().unwrap().get_mut(&(handle as i64)) {+            s.frames.push(Rgba::from_bytes(w, h, bytes));+            s.yaw.push(yaw);+            s.pitch.push(pitch);+        }+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_stitch<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+    ) -> jbyteArray {+        run_and_return(env, handle, true)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_merge<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+    ) -> jbyteArray {+        run_and_return(env, handle, false)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_free<'l>(+        _env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+    ) {+        registry().lock().unwrap().remove(&(handle as i64));+    }++    fn run_and_return(env: JNIEnv, handle: jlong, panorama: bool) -> jbyteArray {+        let null = std::ptr::null_mut();+        // Pull the session out so the (potentially long) compute doesn't hold the lock.+        let mut session = match registry().lock().unwrap().get_mut(&(handle as i64)) {+            Some(s) => Session {+                sphere: s.sphere,+                frames: std::mem::take(&mut s.frames),+                yaw: std::mem::take(&mut s.yaw),+                pitch: std::mem::take(&mut s.pitch),+            },+            None => return null,+        };+        // Never let a panic unwind across the JNI/FFI boundary — return null instead.+        let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            if panorama {+                do_stitch(&mut session)+            } else {+                do_merge(&mut session)+            }+        }))+        .unwrap_or(None);+        match bytes {+            Some(b) => match env.byte_array_from_slice(&b) {+                Ok(arr) => arr.into_raw(),+                Err(_) => null,+            },+            None => null,+        }+    }+}
camera/rust/src/matching.rs
diff --git a/camera/rust/src/matching.rs b/camera/rust/src/matching.rsnew file mode 100644index 0000000000..0814d2b184--- /dev/null+++ b/camera/rust/src/matching.rs@@ -0,0 +1,112 @@+//! All-pairs feature matching, mirroring cv::detail::BestOf2NearestMatcher:+//! bidirectional 2-NN ratio matches (cross-checked) -> RANSAC homography ->+//! confidence = num_inliers / (8 + 0.3 * num_matches).++use crate::features::{match_features, Features};+use crate::geometry::{find_homography_ransac, transfer_inliers, Pt};+use nalgebra::Matrix3;+use rayon::prelude::*;+use std::collections::HashSet;++const RATIO: f32 = 0.85;+const RANSAC_ITERS: usize = 2000;+const RANSAC_THRESH: f32 = 5.0;+const MIN_MATCHES: usize = 6;++pub struct MatchInfo {+    pub src: usize,+    pub dst: usize,+    pub h: Matrix3<f64>,        // maps src -> dst+    pub inliers: Vec<(Pt, Pt)>, // (src pt, dst pt)+    pub confidence: f64,+}++/// Match one ordered pair (src -> dst). Returns None if too weak.+fn match_pair(src: usize, dst: usize, fs: &Features, fd: &Features) -> Option<MatchInfo> {+    let m12 = match_features(fs, fd, RATIO); // (i in src, j in dst)+    if m12.len() < MIN_MATCHES {+        return None;+    }+    let m21: HashSet<(usize, usize)> = match_features(fd, fs, RATIO)+        .into_iter()+        .map(|(j, i)| (i, j)) // normalize to (src, dst)+        .collect();+    // cross-check+    let mutual: Vec<(usize, usize)> = m12.into_iter().filter(|p| m21.contains(p)).collect();+    if mutual.len() < MIN_MATCHES {+        return None;+    }++    let a: Vec<Pt> = mutual.iter().map(|&(i, _)| (fs.kps[i].x, fs.kps[i].y)).collect();+    let b: Vec<Pt> = mutual.iter().map(|&(_, j)| (fd.kps[j].x, fd.kps[j].y)).collect();+    let (h, _n) = find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH)?;+    let inl = transfer_inliers(&h, &a, &b, RANSAC_THRESH);+    let num_inliers = inl.len();+    if num_inliers < MIN_MATCHES {+        return None;+    }+    // Brown & Lowe confidence.+    let confidence = num_inliers as f64 / (8.0 + 0.3 * mutual.len() as f64);+    let inliers: Vec<(Pt, Pt)> = inl.iter().map(|&k| (a[k], b[k])).collect();+    Some(MatchInfo { src, dst, h, inliers, confidence })+}++/// Match pairs (i<j). `window` limits pairs to |i-j| <= window (0 = all pairs);+/// for an ordered continuous sweep a small window is far cheaper and loses+/// nothing since only nearby frames overlap. Runs in parallel across pairs.+pub fn match_all(feats: &[Features], window: usize) -> Vec<MatchInfo> {+    let n = feats.len();+    let mut pairs: Vec<(usize, usize)> = Vec::new();+    for i in 0..n {+        let jmax = if window == 0 { n } else { (i + window + 1).min(n) };+        for j in (i + 1)..jmax {+            pairs.push((i, j));+        }+    }+    pairs+        .par_iter()+        .filter_map(|&(i, j)| match_pair(i, j, &feats[i], &feats[j]))+        .collect()+}++/// leaveBiggestComponent: keep the largest set of images connected by matches+/// with confidence > `conf_thresh`. Returns the kept image indices (sorted).+pub fn biggest_component(n: usize, matches: &[MatchInfo], conf_thresh: f64) -> Vec<usize> {+    // union-find+    let mut parent: Vec<usize> = (0..n).collect();+    fn find(parent: &mut Vec<usize>, x: usize) -> usize {+        let mut r = x;+        while parent[r] != r {+            r = parent[r];+        }+        let mut c = x;+        while parent[c] != c {+            let next = parent[c];+            parent[c] = r;+            c = next;+        }+        r+    }+    for m in matches {+        if m.confidence > conf_thresh {+            let a = find(&mut parent, m.src);+            let b = find(&mut parent, m.dst);+            if a != b {+                parent[a] = b;+            }+        }+    }+    let mut counts = vec![0usize; n];+    let roots: Vec<usize> = (0..n).map(|i| find(&mut parent, i)).collect();+    for &r in &roots {+        counts[r] += 1;+    }+    let best_root = (0..n).max_by_key(|&i| counts[i]).unwrap_or(0);+    let best_root = find(&mut parent, best_root);+    let mut kept: Vec<usize> = (0..n).filter(|&i| roots[i] == best_root).collect();+    if kept.is_empty() {+        kept = (0..n).collect();+    }+    kept.sort_unstable();+    kept+}
camera/rust/src/night.rs
diff --git a/camera/rust/src/night.rs b/camera/rust/src/night.rsnew file mode 100644index 0000000000..a87b6ddc34--- /dev/null+++ b/camera/rust/src/night.rs@@ -0,0 +1,92 @@+//! Night mode: align a hand-held burst to the first frame (ORB + RANSAC+//! homography) and temporally average to reduce noise.++use crate::features::{detect_and_describe, match_features};+use crate::geometry::{find_homography_ransac, Pt};+use crate::imgbuf::{to_gray, Rgba};+use nalgebra::{Matrix3, Vector3};++const MAX_FEATURES: usize = 1200;+const FAST_THRESHOLD: i32 = 20;+const RATIO: f32 = 0.8;+const RANSAC_ITERS: usize = 400;+const RANSAC_THRESH: f32 = 3.0;+const MIN_INLIERS: usize = 20;++#[inline]+fn apply(h: &Matrix3<f64>, x: f64, y: f64) -> (f64, f64) {+    let v = h * Vector3::new(x, y, 1.0);+    if v.z.abs() < 1e-12 { (v.x, v.y) } else { (v.x / v.z, v.y / v.z) }+}++pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> {+    let n = frames.len();+    if n == 0 {+        return None;+    }+    if n == 1 {+        return Some(frames[0].clone());+    }+    let reff = &frames[0];+    let w = reff.w;+    let h = reff.h;+    let ref_feat = detect_and_describe(&to_gray(reff), MAX_FEATURES, FAST_THRESHOLD);++    let mut acc = vec![0f32; w * h * 3];+    let mut cnt = vec![0f32; w * h];++    for (i, f) in frames.iter().enumerate() {+        // homography mapping this frame -> reference+        let h_to_ref = if i == 0 {+            Matrix3::identity()+        } else {+            let feat = detect_and_describe(&to_gray(f), MAX_FEATURES, FAST_THRESHOLD);+            let matches = match_features(&feat, &ref_feat, RATIO);+            if matches.len() < MIN_INLIERS {+                continue; // too different; skip rather than ghost+            }+            let a: Vec<Pt> = matches.iter().map(|&(ia, _)| (feat.kps[ia].x, feat.kps[ia].y)).collect();+            let b: Vec<Pt> = matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect();+            match find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH) {+                Some((hm, inl)) if inl >= MIN_INLIERS => hm,+                _ => continue,+            }+        };+        let h_inv = match h_to_ref.try_inverse() {+            Some(m) => m,+            None => continue,+        };+        for y in 0..h {+            for x in 0..w {+                let (sx, sy) = apply(&h_inv, x as f64, y as f64);+                if let Some(c) = f.sample(sx as f32, sy as f32) {+                    let idx = y * w + x;+                    acc[idx * 3] += c[0];+                    acc[idx * 3 + 1] += c[1];+                    acc[idx * 3 + 2] += c[2];+                    cnt[idx] += 1.0;+                }+            }+        }+    }++    let mut out = Rgba::new(w, h);+    for i in 0..w * h {+        let c = cnt[i];+        let d = i * 4;+        if c > 0.0 {+            out.px[d] = (acc[i * 3] / c).round().clamp(0.0, 255.0) as u8;+            out.px[d + 1] = (acc[i * 3 + 1] / c).round().clamp(0.0, 255.0) as u8;+            out.px[d + 2] = (acc[i * 3 + 2] / c).round().clamp(0.0, 255.0) as u8;+            out.px[d + 3] = 255;+        } else {+            // fall back to the reference pixel if nothing aligned here+            let rc = reff.get(i % w, i / w);+            out.px[d] = rc[0];+            out.px[d + 1] = rc[1];+            out.px[d + 2] = rc[2];+            out.px[d + 3] = 255;+        }+    }+    Some(out)+}
camera/rust/src/seam.rs
diff --git a/camera/rust/src/seam.rs b/camera/rust/src/seam.rsnew file mode 100644index 0000000000..aab30c05e3--- /dev/null+++ b/camera/rust/src/seam.rs@@ -0,0 +1,412 @@+//! Seam finding. `seam_masks` uses a graph-cut (min-cut) seam like OpenCV's+//! default GraphCutSeamFinder, applied pairwise as each image is merged into the+//! running composite; it falls back to VoronoiSeamFinder if the cut can't be+//! built (e.g. overlap too large), so the blender always gets valid masks.++use crate::imgbuf::Rgba;+use crate::sphere::WarpedTile;++const INF: i64 = 1 << 40;+const MAX_CUT_NODES: usize = 900_000;++pub fn seam_masks(tiles: &[WarpedTile]) -> Vec<Vec<u8>> {+    graph_cut_masks(tiles).unwrap_or_else(|| voronoi_masks(tiles))+}++// ---------------------------------------------------------------------------+// Voronoi (fallback): nearest warped-center ownership.+// ---------------------------------------------------------------------------+pub fn voronoi_masks(tiles: &[WarpedTile]) -> Vec<Vec<u8>> {+    let num = tiles.len();+    let mut masks: Vec<Vec<u8>> = tiles.iter().map(|t| vec![0u8; t.img.w * t.img.h]).collect();+    if num == 0 {+        return masks;+    }+    let (gx0, gy0, gx1, gy1) = global_bounds(tiles);+    let centers: Vec<(f64, f64)> = tiles+        .iter()+        .map(|t| (t.corner_x as f64 + t.img.w as f64 / 2.0, t.corner_y as f64 + t.img.h as f64 / 2.0))+        .collect();+    for gy in gy0..gy1 {+        for gx in gx0..gx1 {+            let mut best = usize::MAX;+            let mut best_d = f64::MAX;+            for ti in 0..num {+                if let Some(c) = tile_at(&tiles[ti], gx, gy) {+                    if c[3] == 0 {+                        continue;+                    }+                    let dx = gx as f64 - centers[ti].0;+                    let dy = gy as f64 - centers[ti].1;+                    let d = dx * dx + dy * dy;+                    if d < best_d {+                        best_d = d;+                        best = ti;+                    }+                }+            }+            if best != usize::MAX {+                let t = &tiles[best];+                masks[best][(gy - t.corner_y) as usize * t.img.w + (gx - t.corner_x) as usize] = 1;+            }+        }+    }+    masks+}++// ---------------------------------------------------------------------------+// Graph-cut seam (default): incremental pairwise min-cut on a per-pixel owner map.+// ---------------------------------------------------------------------------+fn graph_cut_masks(tiles: &[WarpedTile]) -> Option<Vec<Vec<u8>>> {+    let num = tiles.len();+    if num == 0 {+        return Some(Vec::new());+    }+    let (gx0, gy0, gx1, gy1) = global_bounds(tiles);+    let cw = (gx1 - gx0) as usize;+    let ch = (gy1 - gy0) as usize;+    if cw == 0 || ch == 0 {+        return None;+    }+    // owner[global pixel] = tile index or -1+    let mut owner = vec![-1i32; cw * ch];+    // per-tile gradient maps for the COST_COLOR_GRAD seam cost+    let grads: Vec<Vec<i64>> = tiles.iter().map(|t| gradient_map(&t.img)).collect();+    let grad_at = |ti2: usize, gi: usize| -> i64 {+        let tt = &tiles[ti2];+        let gx = (gi % cw) as i32 + gx0;+        let gy = (gi / cw) as i32 + gy0;+        let lx = gx - tt.corner_x;+        let ly = gy - tt.corner_y;+        if lx < 0 || ly < 0 || lx >= tt.img.w as i32 || ly >= tt.img.h as i32 {+            0+        } else {+            grads[ti2][ly as usize * tt.img.w + lx as usize]+        }+    };++    for ti in 0..num {+        let t = &tiles[ti];+        // Overlap pixels (owned by a previous tile AND covered by ti).+        let mut overlap: Vec<usize> = Vec::new(); // global indices+        for ly in 0..t.img.h {+            for lx in 0..t.img.w {+                if t.img.get(lx, ly)[3] == 0 {+                    continue;+                }+                let gx = t.corner_x + lx as i32;+                let gy = t.corner_y + ly as i32;+                let gi = (gy - gy0) as usize * cw + (gx - gx0) as usize;+                if owner[gi] >= 0 {+                    overlap.push(gi);+                }+            }+        }+        if overlap.len() > MAX_CUT_NODES {+            return None; // too big -> use Voronoi+        }+        if overlap.is_empty() {+            // first tile or disjoint: claim all covered pixels+            claim_all(t, gx0, gy0, cw, &mut owner, ti);+            continue;+        }++        // Build min-cut over the overlap: source = existing (A), sink = new (B=ti).+        // node id: 0..overlap.len(); +2 terminals.+        let mut node_of = vec![usize::MAX; cw * ch];+        for (k, &gi) in overlap.iter().enumerate() {+            node_of[gi] = k;+        }+        let src = overlap.len();+        let snk = overlap.len() + 1;+        let mut mf = MaxFlow::new(overlap.len() + 2);++        let color_at = |ti2: usize, gi: usize| -> [u8; 4] {+            let tt = &tiles[ti2];+            let gx = (gi % cw) as i32 + gx0;+            let gy = (gi / cw) as i32 + gy0;+            tile_at(tt, gx, gy).unwrap_or([0, 0, 0, 0])+        };++        for (k, &gi) in overlap.iter().enumerate() {+            let gx = gi % cw;+            let gy = gi / cw;+            // neighbor smoothness edges (right, down) within overlap+            for (nx, ny) in [(gx + 1, gy), (gx, gy + 1)] {+                if nx >= cw || ny >= ch {+                    continue;+                }+                let ngi = ny * cw + nx;+                let nk = node_of[ngi];+                if nk == usize::MAX {+                    continue;+                }+                // cost = colordiff, biased toward high-gradient regions (COST_COLOR_GRAD)+                let cp = diff(color_at(owner[gi] as usize, gi), color_at(ti, gi));+                let cq = diff(color_at(owner[ngi] as usize, ngi), color_at(ti, ngi));+                let gp = grad_at(owner[gi] as usize, gi) + grad_at(ti, gi);+                let gq = grad_at(owner[ngi] as usize, ngi) + grad_at(ti, ngi);+                let cap = ((cp + cq) * 256) / (gp + gq + 1) + 1;+                mf.add_edge(k, nk, cap, cap);+            }+            // terminal links: pixels bordering A-exclusive -> source; B-exclusive -> sink.+            let mut borders_a_excl = false;+            let mut borders_b_excl = false;+            for (nx, ny) in neighbors(gx, gy, cw, ch) {+                let ngi = ny * cw + nx;+                if node_of[ngi] != usize::MAX {+                    continue; // still in overlap+                }+                // outside overlap: is it A-owned (owner>=0) or B-covered?+                if owner[ngi] >= 0 {+                    borders_a_excl = true;+                }+                if covered_by(&tiles[ti], gx as i32 + gx0, gy as i32 + gy0) {+                    borders_b_excl = borders_b_excl || (owner[ngi] < 0);+                }+            }+            if borders_a_excl {+                mf.add_edge(src, k, INF, 0);+            }+            if borders_b_excl {+                mf.add_edge(k, snk, INF, 0);+            }+        }++        mf.max_flow(src, snk);+        let cut = mf.min_cut_side(src); // true = source side (A keeps), false = sink (B=ti)+        // Assign overlap pixels.+        for (k, &gi) in overlap.iter().enumerate() {+            if !cut[k] {+                owner[gi] = ti as i32;+            }+        }+        // Claim ti's non-overlap new coverage.+        claim_all(t, gx0, gy0, cw, &mut owner, ti);+    }++    // Build per-tile masks from owner.+    let mut masks: Vec<Vec<u8>> = tiles.iter().map(|t| vec![0u8; t.img.w * t.img.h]).collect();+    for gy in 0..ch {+        for gx in 0..cw {+            let o = owner[gy * cw + gx];+            if o < 0 {+                continue;+            }+            let t = &tiles[o as usize];+            let lx = gx as i32 + gx0 - t.corner_x;+            let ly = gy as i32 + gy0 - t.corner_y;+            if lx >= 0 && ly >= 0 && (lx as usize) < t.img.w && (ly as usize) < t.img.h {+                masks[o as usize][ly as usize * t.img.w + lx as usize] = 1;+            }+        }+    }+    Some(masks)+}++/// Claim every covered pixel of `t` that is currently unowned.+fn claim_all(t: &WarpedTile, gx0: i32, gy0: i32, cw: usize, owner: &mut [i32], ti: usize) {+    for ly in 0..t.img.h {+        for lx in 0..t.img.w {+            if t.img.get(lx, ly)[3] == 0 {+                continue;+            }+            let gx = t.corner_x + lx as i32;+            let gy = t.corner_y + ly as i32;+            let gi = (gy - gy0) as usize * cw + (gx - gx0) as usize;+            if owner[gi] < 0 {+                owner[gi] = ti as i32;+            }+        }+    }+}++fn neighbors(x: usize, y: usize, w: usize, h: usize) -> Vec<(usize, usize)> {+    let mut v = Vec::with_capacity(4);+    if x + 1 < w {+        v.push((x + 1, y));+    }+    if x > 0 {+        v.push((x - 1, y));+    }+    if y + 1 < h {+        v.push((x, y + 1));+    }+    if y > 0 {+        v.push((x, y - 1));+    }+    v+}++fn covered_by(t: &WarpedTile, gx: i32, gy: i32) -> bool {+    tile_at(t, gx, gy).map_or(false, |c| c[3] != 0)+}++fn tile_at(t: &WarpedTile, gx: i32, gy: i32) -> Option<[u8; 4]> {+    let lx = gx - t.corner_x;+    let ly = gy - t.corner_y;+    if lx < 0 || ly < 0 || lx >= t.img.w as i32 || ly >= t.img.h as i32 {+        return None;+    }+    Some(t.img.get(lx as usize, ly as usize))+}++fn diff(a: [u8; 4], b: [u8; 4]) -> i64 {+    ((a[0] as i64 - b[0] as i64).abs()+        + (a[1] as i64 - b[1] as i64).abs()+        + (a[2] as i64 - b[2] as i64).abs())+}++#[inline]+fn luma_i(c: [u8; 4]) -> i64 {+    (0.299 * c[0] as f64 + 0.587 * c[1] as f64 + 0.114 * c[2] as f64) as i64+}++/// Per-pixel gradient magnitude (|dx|+|dy| of luma) of a warped tile, for the+/// COST_COLOR_GRAD seam cost (seams prefer high-gradient areas that hide them).+fn gradient_map(img: &Rgba) -> Vec<i64> {+    let (w, h) = (img.w, img.h);+    let mut g = vec![0i64; w * h];+    for y in 0..h {+        for x in 0..w {+            if img.get(x, y)[3] == 0 {+                continue;+            }+            let xm = if x > 0 { x - 1 } else { x };+            let xp = if x + 1 < w { x + 1 } else { x };+            let ym = if y > 0 { y - 1 } else { y };+            let yp = if y + 1 < h { y + 1 } else { y };+            let dx = (luma_i(img.get(xp, y)) - luma_i(img.get(xm, y))).abs();+            let dy = (luma_i(img.get(x, yp)) - luma_i(img.get(x, ym))).abs();+            g[y * w + x] = dx + dy;+        }+    }+    g+}++fn global_bounds(tiles: &[WarpedTile]) -> (i32, i32, i32, i32) {+    let mut gx0 = i32::MAX;+    let mut gy0 = i32::MAX;+    let mut gx1 = i32::MIN;+    let mut gy1 = i32::MIN;+    for t in tiles {+        gx0 = gx0.min(t.corner_x);+        gy0 = gy0.min(t.corner_y);+        gx1 = gx1.max(t.corner_x + t.img.w as i32);+        gy1 = gy1.max(t.corner_y + t.img.h as i32);+    }+    (gx0, gy0, gx1, gy1)+}++// ---------------------------------------------------------------------------+// Dinic max-flow / min-cut.+// ---------------------------------------------------------------------------+struct MaxFlow {+    head: Vec<i32>,+    to: Vec<u32>,+    nxt: Vec<i32>,+    cap: Vec<i64>,+    level: Vec<i32>,+    it: Vec<i32>,+    n: usize,+}++impl MaxFlow {+    fn new(n: usize) -> Self {+        MaxFlow {+            head: vec![-1; n],+            to: Vec::new(),+            nxt: Vec::new(),+            cap: Vec::new(),+            level: vec![0; n],+            it: vec![0; n],+            n,+        }+    }+    fn add_edge(&mut self, u: usize, v: usize, c: i64, rc: i64) {+        self.to.push(v as u32);+        self.cap.push(c);+        self.nxt.push(self.head[u]);+        self.head[u] = (self.to.len() - 1) as i32;+        self.to.push(u as u32);+        self.cap.push(rc);+        self.nxt.push(self.head[v]);+        self.head[v] = (self.to.len() - 1) as i32;+    }+    fn bfs(&mut self, s: usize, t: usize) -> bool {+        for l in self.level.iter_mut() {+            *l = -1;+        }+        let mut q = std::collections::VecDeque::new();+        self.level[s] = 0;+        q.push_back(s);+        while let Some(u) = q.pop_front() {+            let mut e = self.head[u];+            while e != -1 {+                let ei = e as usize;+                let v = self.to[ei] as usize;+                if self.cap[ei] > 0 && self.level[v] < 0 {+                    self.level[v] = self.level[u] + 1;+                    q.push_back(v);+                }+                e = self.nxt[ei];+            }+        }+        self.level[t] >= 0+    }+    fn dfs(&mut self, u: usize, t: usize, f: i64) -> i64 {+        if u == t {+            return f;+        }+        while self.it[u] != -1 {+            let ei = self.it[u] as usize;+            let v = self.to[ei] as usize;+            if self.cap[ei] > 0 && self.level[v] == self.level[u] + 1 {+                let d = self.dfs(v, t, f.min(self.cap[ei]));+                if d > 0 {+                    self.cap[ei] -= d;+                    self.cap[ei ^ 1] += d;+                    return d;+                }+            }+            self.it[u] = self.nxt[ei];+        }+        0+    }+    fn max_flow(&mut self, s: usize, t: usize) -> i64 {+        let mut flow = 0;+        while self.bfs(s, t) {+            for u in 0..self.n {+                self.it[u] = self.head[u];+            }+            loop {+                let f = self.dfs(s, t, INF);+                if f == 0 {+                    break;+                }+                flow += f;+            }+        }+        flow+    }+    /// Pixels reachable from `s` in the residual graph = source side of the cut.+    fn min_cut_side(&self, s: usize) -> Vec<bool> {+        let mut side = vec![false; self.n];+        let mut q = std::collections::VecDeque::new();+        side[s] = true;+        q.push_back(s);+        while let Some(u) = q.pop_front() {+            let mut e = self.head[u];+            while e != -1 {+                let ei = e as usize;+                let v = self.to[ei] as usize;+                if self.cap[ei] > 0 && !side[v] {+                    side[v] = true;+                    q.push_back(v);+                }+                e = self.nxt[ei];+            }+        }+        side+    }+}
camera/rust/src/sphere.rs
diff --git a/camera/rust/src/sphere.rs b/camera/rust/src/sphere.rsnew file mode 100644index 0000000000..814576582f--- /dev/null+++ b/camera/rust/src/sphere.rs@@ -0,0 +1,366 @@+//! Rotation-model spherical stitching — a Rust translation of OpenCV's+//! `stitching_detail` pipeline used by `cv::Stitcher` (Brown & Lowe 2007):+//!   * `focalsFromHomography` / `estimateFocal`  (modules/stitching/.../autocalib.cpp)+//!   * `HomographyBasedEstimator` rotation chaining (motion_estimators.cpp)+//!   * `SphericalProjector::mapForward/mapBackward` (warpers.cpp / warpers_inl.hpp)+//!+//! This replaces planar homography chaining (which distorts badly for multi-image+//! panoramas) with per-image focal + rotation warped onto a common sphere.++use crate::imgbuf::Rgba;+use crate::warp::feather_weights;+use nalgebra::{Matrix3, Vector3};++/// OpenCV `focalsFromHomography` (autocalib.cpp): recover the two focal-length+/// estimates implied by a homography. Returns (f0, f1), each Some if valid.+pub fn focals_from_homography(h: &Matrix3<f64>) -> (Option<f64>, Option<f64>) {+    // Row-major access matching OpenCV's h[0..8].+    let hh = [+        h[(0, 0)], h[(0, 1)], h[(0, 2)],+        h[(1, 0)], h[(1, 1)], h[(1, 2)],+        h[(2, 0)], h[(2, 1)], h[(2, 2)],+    ];++    // f1 (from the "to" image)+    let mut f1: Option<f64> = None;+    {+        let d1 = hh[6] * hh[7];+        let d2 = (hh[7] - hh[6]) * (hh[7] + hh[6]);+        let mut v1 = -(hh[0] * hh[1] + hh[3] * hh[4]) / d1;+        let mut v2 = (hh[0] * hh[0] + hh[3] * hh[3] - hh[1] * hh[1] - hh[4] * hh[4]) / d2;+        if v1 < v2 {+            std::mem::swap(&mut v1, &mut v2);+        }+        if v1 > 0.0 && v2 > 0.0 {+            f1 = Some((if d1.abs() > d2.abs() { v1 } else { v2 }).sqrt());+        } else if v1 > 0.0 {+            f1 = Some(v1.sqrt());+        }+    }++    // f0 (from the "from" image)+    let mut f0: Option<f64> = None;+    {+        let d1 = hh[0] * hh[3] + hh[1] * hh[4];+        let d2 = hh[0] * hh[0] + hh[1] * hh[1] - hh[3] * hh[3] - hh[4] * hh[4];+        let mut v1 = -hh[2] * hh[5] / d1;+        let mut v2 = (hh[5] * hh[5] - hh[2] * hh[2]) / d2;+        if v1 < v2 {+            std::mem::swap(&mut v1, &mut v2);+        }+        if v1 > 0.0 && v2 > 0.0 {+            f0 = Some((if d1.abs() > d2.abs() { v1 } else { v2 }).sqrt());+        } else if v1 > 0.0 {+            f0 = Some(v1.sqrt());+        }+    }++    (sanitize(f0), sanitize(f1))+}++fn sanitize(f: Option<f64>) -> Option<f64> {+    f.filter(|v| v.is_finite() && *v > 1.0)+}++/// OpenCV `estimateFocal`: median of sqrt(f0*f1) over pairwise homographies that+/// yield both focals; falls back to (w + h) when nothing is estimable.+pub fn estimate_focal(pairs: &[Matrix3<f64>], w: usize, h: usize) -> f64 {+    let mut all = Vec::new();+    for hmat in pairs {+        let (f0, f1) = focals_from_homography(hmat);+        if let (Some(a), Some(b)) = (f0, f1) {+            all.push((a * b).sqrt());+        }+    }+    if all.is_empty() {+        return (w + h) as f64;+    }+    all.sort_by(|a, b| a.total_cmp(b));+    let m = all.len() / 2;+    if all.len() % 2 == 1 {+        all[m]+    } else {+        (all[m - 1] + all[m]) / 2.0+    }+}++pub fn k_matrix(f: f64, ppx: f64, ppy: f64) -> Matrix3<f64> {+    Matrix3::new(f, 0.0, ppx, 0.0, f, ppy, 0.0, 0.0, 1.0)+}++/// Nearest orthonormal matrix (SVD): R = U Vᵀ. Ensures a valid rotation.+pub(crate) fn orthonormalize(m: &Matrix3<f64>) -> Matrix3<f64> {+    let svd = m.svd(true, true);+    match (svd.u, svd.v_t) {+        (Some(u), Some(vt)) => u * vt,+        _ => Matrix3::identity(),+    }+}++/// Chain per-image rotations from consecutive homographies `pair[i]` = H_{i->i-1}+/// (rotation-only model H = K R_{i-1} R_iᵀ K⁻¹). R_0 = I.+pub fn estimate_rotations(pairs: &[Matrix3<f64>], k: &Matrix3<f64>) -> Vec<Matrix3<f64>> {+    let n = pairs.len();+    let k_inv = k.try_inverse().unwrap_or_else(Matrix3::identity);+    let mut rots = vec![Matrix3::<f64>::identity(); n];+    for i in 1..n {+        // M_i = K^-1 H_{i->i-1} K = R_{i-1} R_iᵀ  =>  R_i = M_iᵀ R_{i-1}+        let m = k_inv * pairs[i] * k;+        let r = m.transpose() * rots[i - 1];+        rots[i] = orthonormalize(&r);+    }+    rots+}++/// SphericalProjector state for one image: r_kinv = R K⁻¹, k_rinv = K Rᵀ.+struct Proj {+    r_kinv: Matrix3<f64>,+    k_rinv: Matrix3<f64>,+    scale: f64,+}++impl Proj {+    fn new(k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<Proj> {+        let k_inv = k.try_inverse()?;+        Some(Proj {+            r_kinv: r * k_inv,+            k_rinv: k * r.transpose(),+            scale,+        })+    }++    /// source (x,y) -> sphere (u,v)+    fn forward(&self, x: f64, y: f64) -> (f64, f64) {+        let p = self.r_kinv * Vector3::new(x, y, 1.0);+        let u = self.scale * p.x.atan2(p.z);+        let denom = (p.x * p.x + p.y * p.y + p.z * p.z).sqrt();+        let w = if denom > 1e-12 { p.y / denom } else { 0.0 };+        let v = self.scale * (std::f64::consts::PI - w.clamp(-1.0, 1.0).acos());+        (u, v)+    }++    /// sphere (u,v) -> source (x,y); None if behind the camera.+    fn backward(&self, u: f64, v: f64) -> Option<(f64, f64)> {+        let uu = u / self.scale;+        let vv = v / self.scale;+        let sinv = (std::f64::consts::PI - vv).sin();+        let x_ = sinv * uu.sin();+        let y_ = (std::f64::consts::PI - vv).cos();+        let z_ = sinv * uu.cos();+        let p = self.k_rinv * Vector3::new(x_, y_, z_);+        if p.z > 0.0 {+            Some((p.x / p.z, p.y / p.z))+        } else {+            None+        }+    }+}++/// Compute a projector's (u,v) bounds by walking the source-image border.+fn tile_bounds(proj: &Proj, w: usize, h: usize) -> (f64, f64, f64, f64) {+    let (mut u0, mut v0, mut u1, mut v1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+    let step = 1usize.max(w.min(h) / 100);+    let mut consider = |x: usize, y: usize, u0: &mut f64, v0: &mut f64, u1: &mut f64, v1: &mut f64| {+        let (u, v) = proj.forward(x as f64, y as f64);+        if u.is_finite() && v.is_finite() {+            *u0 = u0.min(u);+            *v0 = v0.min(v);+            *u1 = u1.max(u);+            *v1 = v1.max(v);+        }+    };+    let mut x = 0;+    while x < w {+        consider(x, 0, &mut u0, &mut v0, &mut u1, &mut v1);+        consider(x, h - 1, &mut u0, &mut v0, &mut u1, &mut v1);+        x += step;+    }+    let mut y = 0;+    while y < h {+        consider(0, y, &mut u0, &mut v0, &mut u1, &mut v1);+        consider(w - 1, y, &mut u0, &mut v0, &mut u1, &mut v1);+        y += step;+    }+    (u0, v0, u1, v1)+}++/// Cheap (u,v) bounds of a warped image (border walk only, no pixels), for+/// sizing the output canvas before committing to a full warp.+pub fn warped_bounds(fw: usize, fh: usize, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<(f64, f64, f64, f64)> {+    let p = Proj::new(k, r, scale)?;+    let b = tile_bounds(&p, fw, fh);+    if b.0.is_finite() && b.1.is_finite() && b.2.is_finite() && b.3.is_finite() {+        Some(b)+    } else {+        None+    }+}++/// A single image warped onto the sphere: RGBA tile (alpha = coverage mask) and+/// its top-left corner in global sphere-pixel coordinates.+pub struct WarpedTile {+    pub img: Rgba,+    pub corner_x: i32,+    pub corner_y: i32,+}++/// Warp one image onto the sphere with camera intrinsics `k`/rotation `r` and+/// warp `scale`. Mirrors SphericalWarper::warp (buildMaps + remap).+pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<WarpedTile> {+    let p = Proj::new(k, r, scale)?;+    let (u0, v0, u1, v1) = tile_bounds(&p, frame.w, frame.h);+    if !u0.is_finite() || !u1.is_finite() {+        return None;+    }+    let cx = u0.floor() as i32;+    let cy = v0.floor() as i32;+    let tw = ((u1.ceil() as i32 - cx) + 1).max(1) as usize;+    let th = ((v1.ceil() as i32 - cy) + 1).max(1) as usize;+    if tw > 20000 || th > 20000 {+        return None;+    }+    let mut img = Rgba::new(tw, th);+    for ty in 0..th {+        for tx in 0..tw {+            let u = (cx + tx as i32) as f64;+            let v = (cy + ty as i32) as f64;+            if let Some((sx, sy)) = p.backward(u, v) {+                if let Some(c) = frame.sample(sx as f32, sy as f32) {+                    if c[3] >= 8.0 {+                        img.set(tx, ty, [+                            c[0].round().clamp(0.0, 255.0) as u8,+                            c[1].round().clamp(0.0, 255.0) as u8,+                            c[2].round().clamp(0.0, 255.0) as u8,+                            255,+                        ]);+                    }+                }+            }+        }+    }+    Some(WarpedTile { img, corner_x: cx, corner_y: cy })+}++/// Warp all frames onto the common sphere and gain-compensated feather-blend.+/// `rotations[i]` and shared `k`/`scale` come from the estimator. Returns the+/// cropped panorama.+pub fn warp_spherical_and_blend(+    frames: &[Rgba],+    rotations: &[Matrix3<f64>],+    k: &Matrix3<f64>,+    scale: f64,+    gains: &[f32],+    max_canvas: usize,+) -> Option<Rgba> {+    if frames.is_empty() || frames.len() != rotations.len() {+        return None;+    }+    let projs: Vec<Proj> = frames+        .iter()+        .zip(rotations.iter())+        .filter_map(|(_, r)| Proj::new(k, r, scale))+        .collect();+    if projs.len() != frames.len() {+        return None;+    }++    // Global sphere bounds.+    let (mut gu0, mut gv0, mut gu1, mut gv1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+    let mut tiles = Vec::with_capacity(frames.len());+    for (f, p) in frames.iter().zip(projs.iter()) {+        let b = tile_bounds(p, f.w, f.h);+        tiles.push(b);+        gu0 = gu0.min(b.0);+        gv0 = gv0.min(b.1);+        gu1 = gu1.max(b.2);+        gv1 = gv1.max(b.3);+    }+    if !gu0.is_finite() || !gu1.is_finite() {+        return None;+    }+    let cw = (gu1 - gu0).ceil() as i64 + 1;+    let ch = (gv1 - gv0).ceil() as i64 + 1;+    if cw <= 0 || ch <= 0 || cw as usize > max_canvas || ch as usize > max_canvas {+        return None;+    }+    let cw = cw as usize;+    let ch = ch as usize;++    let mut acc = vec![0f32; cw * ch * 3];+    let mut accw = vec![0f32; cw * ch];++    for (fi, f) in frames.iter().enumerate() {+        let p = &projs[fi];+        let gain = gains.get(fi).copied().unwrap_or(1.0);+        let wt = feather_weights(f.w, f.h);+        let (tu0, tv0, tu1, tv1) = tiles[fi];+        let x0 = ((tu0 - gu0).floor() as i64).max(0) as usize;+        let y0 = ((tv0 - gv0).floor() as i64).max(0) as usize;+        let x1 = (((tu1 - gu0).ceil() as i64).min(cw as i64 - 1)).max(0) as usize;+        let y1 = (((tv1 - gv0).ceil() as i64).min(ch as i64 - 1)).max(0) as usize;++        for cy in y0..=y1 {+            for cx in x0..=x1 {+                let u = cx as f64 + gu0;+                let v = cy as f64 + gv0;+                let (sx, sy) = match p.backward(u, v) {+                    Some(s) => s,+                    None => continue,+                };+                if let Some(c) = f.sample(sx as f32, sy as f32) {+                    if c[3] < 8.0 {+                        continue;+                    }+                    let ix = (sx as usize).min(f.w - 1);+                    let iy = (sy as usize).min(f.h - 1);+                    let w = wt[iy * f.w + ix];+                    if w <= 0.0 {+                        continue;+                    }+                    let idx = cy * cw + cx;+                    acc[idx * 3] += (c[0] * gain).min(255.0) * w;+                    acc[idx * 3 + 1] += (c[1] * gain).min(255.0) * w;+                    acc[idx * 3 + 2] += (c[2] * gain).min(255.0) * w;+                    accw[idx] += w;+                }+            }+        }+    }++    // Resolve + crop to covered bbox.+    let (mut minx, mut miny, mut maxx, mut maxy) = (cw, ch, 0usize, 0usize);+    let mut any = false;+    for y in 0..ch {+        for x in 0..cw {+            if accw[y * cw + x] > 0.0 {+                any = true;+                minx = minx.min(x);+                miny = miny.min(y);+                maxx = maxx.max(x);+                maxy = maxy.max(y);+            }+        }+    }+    if !any {+        return None;+    }+    let ow = maxx - minx + 1;+    let oh = maxy - miny + 1;+    let mut out = Rgba::new(ow, oh);+    for y in 0..oh {+        for x in 0..ow {+            let sidx = (y + miny) * cw + (x + minx);+            let w = accw[sidx];+            let didx = (y * ow + x) * 4;+            if w > 0.0 {+                out.px[didx] = (acc[sidx * 3] / w).round().clamp(0.0, 255.0) as u8;+                out.px[didx + 1] = (acc[sidx * 3 + 1] / w).round().clamp(0.0, 255.0) as u8;+                out.px[didx + 2] = (acc[sidx * 3 + 2] / w).round().clamp(0.0, 255.0) as u8;+                out.px[didx + 3] = 255;+            } else {+                out.px[didx + 3] = 0;+            }+        }+    }+    Some(out)+}
camera/rust/src/stitch.rs
diff --git a/camera/rust/src/stitch.rs b/camera/rust/src/stitch.rsnew file mode 100644index 0000000000..bd4def287a--- /dev/null+++ b/camera/rust/src/stitch.rs@@ -0,0 +1,223 @@+//! Full cv::Stitcher (PANORAMA) pipeline, ported to Rust — no fallbacks.+//! Performance mirrors OpenCV: registration (features/matching/estimation/bundle+//! adjustment) runs at a reduced resolution, then warping + blending run at the+//! captured resolution. Matching is windowed to nearby frames and the slow+//! stages are parallelised with rayon.++use crate::blend::multiband_blend;+use crate::bundle::bundle_adjust;+use crate::camera::CameraParams;+use crate::estimator::estimate_cameras;+use crate::exposure::compensate;+use crate::features::{detect_and_describe, Features};+use crate::imgbuf::{to_gray, Rgba};+use crate::matching::{biggest_component, match_all, MatchInfo};+use crate::seam::seam_masks;+use crate::sphere::{warp_one, warped_bounds};+use crate::wave::wave_correct_horizontal;+use rayon::prelude::*;++const MAX_FEATURES: usize = 3000;+const FAST_THRESHOLD: i32 = 12;+const CONF_THRESH: f64 = 1.0;+const MATCH_WINDOW: usize = 5; // match each frame only to ~5 neighbours (ordered sweep)+const REG_MEGAPIXELS: f64 = 0.6; // registration resolution (like OpenCV's registr_resol_)+const COMPOSE_MAX_PIXELS: f64 = 5_000_000.0; // cap output canvas area (bounds blend memory)+const SEAM_MAX_PIXELS: f64 = 400_000.0; // seam/exposure canvas area (OpenCV seam_est_resol_)++fn remap_matches(matches: Vec<MatchInfo>, kept: &[usize]) -> Vec<MatchInfo> {+    let max = kept.iter().max().map(|m| m + 1).unwrap_or(0);+    let mut idx_of = vec![usize::MAX; max];+    for (new, &old) in kept.iter().enumerate() {+        idx_of[old] = new;+    }+    matches+        .into_iter()+        .filter_map(|mut m| {+            if m.src >= idx_of.len() || m.dst >= idx_of.len() {+                return None;+            }+            let (s, d) = (idx_of[m.src], idx_of[m.dst]);+            if s == usize::MAX || d == usize::MAX {+                return None;+            }+            m.src = s;+            m.dst = d;+            Some(m)+        })+        .collect()+}++fn median_focal(cams: &[CameraParams]) -> f64 {+    let mut f: Vec<f64> = cams.iter().map(|c| c.focal).filter(|v| v.is_finite() && *v > 1.0).collect();+    if f.is_empty() {+        return 1.0;+    }+    f.sort_by(|a, b| a.total_cmp(b));+    let m = f.len() / 2;+    if f.len() % 2 == 1 {+        f[m]+    } else {+        (f[m - 1] + f[m]) / 2.0+    }+}++pub fn stitch_panorama(frames: &[Rgba], _yaw: &[f32], _pitch: &[f32]) -> Option<Rgba> {+    let n = frames.len();+    if n == 0 {+        return None;+    }+    if n == 1 {+        return Some(frames[0].clone());+    }++    let full_w = frames[0].w;+    let full_h = frames[0].h;++    // --- registration resolution (downscale for the slow stages) ---+    let reg_scale = (REG_MEGAPIXELS * 1e6 / (full_w as f64 * full_h as f64)).sqrt().min(1.0);+    let reg_w = ((full_w as f64 * reg_scale).round() as usize).max(1);+    let reg_h = ((full_h as f64 * reg_scale).round() as usize).max(1);+    let reg_frames: Vec<Rgba> = if reg_scale < 0.999 {+        frames.par_iter().map(|f| f.resized(reg_w, reg_h)).collect()+    } else {+        frames.to_vec()+    };++    // 1) features (parallel)+    let feats: Vec<Features> = reg_frames+        .par_iter()+        .map(|f| detect_and_describe(&to_gray(f), MAX_FEATURES, FAST_THRESHOLD))+        .collect();++    // 2) all-pairs matching+    let matches = match_all(&feats, MATCH_WINDOW);+    if matches.is_empty() {+        return None;+    }++    // 3) leaveBiggestComponent+    let kept = biggest_component(n, &matches, CONF_THRESH);+    if kept.len() < 2 {+        return None;+    }+    let matches = remap_matches(matches, &kept);+    if matches.is_empty() {+        return None;+    }+    let m = kept.len();++    // 4) estimate cameras -> 5) bundle adjust -> 6) wave correct  (all at reg res)+    let mut cams = estimate_cameras(m, reg_w, reg_h, &matches);+    bundle_adjust(&mut cams, &matches);+    wave_correct_horizontal(&mut cams);++    // Rescale intrinsics from registration to full resolution.+    for c in cams.iter_mut() {+        c.focal /= reg_scale;+        c.ppx = full_w as f64 / 2.0;+        c.ppy = full_h as f64 / 2.0;+    }++    // 7) choose compose scale (bounded so the blend stays within memory), then+    // a much smaller seam-estimation scale (OpenCV's seam_est_resol_ ~= 0.1 MP):+    // exposure compensation and graph-cut seam finding run on tiny low-res warps,+    // and the resulting masks/gains are upscaled for the full-res blend. This is+    // the key to speed — the max-flow runs on ~30x fewer pixels.+    let mut scale = median_focal(&cams);+    if !scale.is_finite() || scale <= 1.0 {+        return None;+    }+    let kept_full: Vec<&Rgba> = kept.iter().map(|&i| &frames[i]).collect();+    let mut compose_area = {+        let mut gx0 = f64::MAX;+        let mut gy0 = f64::MAX;+        let mut gx1 = f64::MIN;+        let mut gy1 = f64::MIN;+        for (f, c) in kept_full.iter().zip(cams.iter()) {+            if let Some((u0, v0, u1, v1)) = warped_bounds(f.w, f.h, &c.k(), &c.r, scale) {+                gx0 = gx0.min(u0);+                gy0 = gy0.min(v0);+                gx1 = gx1.max(u1);+                gy1 = gy1.max(v1);+            }+        }+        (gx1 - gx0).max(1.0) * (gy1 - gy0).max(1.0)+    };+    if compose_area.is_finite() && compose_area > COMPOSE_MAX_PIXELS {+        scale *= (COMPOSE_MAX_PIXELS / compose_area).sqrt();+        compose_area = COMPOSE_MAX_PIXELS;+    }+    let seam_scale = (scale * (SEAM_MAX_PIXELS / compose_area).sqrt()).min(scale).max(1.0);++    // Low-res warps -> exposure + seam (cheap).+    let seam_tiles = kept_full+        .par_iter()+        .zip(cams.par_iter())+        .map(|(f, c)| warp_one(f, &c.k(), &c.r, seam_scale))+        .collect::<Option<Vec<_>>>()?;+    let seam_gains = compensate(&seam_tiles);+    let low_masks = seam_masks(&seam_tiles);++    // Full-res warps -> blend.+    let tiles = kept_full+        .par_iter()+        .zip(cams.par_iter())+        .map(|(f, c)| warp_one(f, &c.k(), &c.r, scale))+        .collect::<Option<Vec<_>>>()?;++    // Upscale seam masks (nearest) and gain maps (bilinear) to compose tile size.+    let masks: Vec<Vec<u8>> = (0..tiles.len())+        .map(|i| resize_mask(&low_masks[i], seam_tiles[i].img.w, seam_tiles[i].img.h, tiles[i].img.w, tiles[i].img.h))+        .collect();+    let gain_maps: Vec<Vec<f32>> = (0..tiles.len())+        .map(|i| resize_gain(&seam_gains[i], seam_tiles[i].img.w, seam_tiles[i].img.h, tiles[i].img.w, tiles[i].img.h))+        .collect();++    // 10) multi-band blend + crop+    multiband_blend(&tiles, &masks, &gain_maps)+}++/// Nearest-neighbour upscale of a binary mask.+fn resize_mask(src: &[u8], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<u8> {+    if sw == 0 || sh == 0 {+        return vec![0u8; dw * dh];+    }+    let mut out = vec![0u8; dw * dh];+    for y in 0..dh {+        let sy = (y * sh / dh).min(sh - 1);+        for x in 0..dw {+            let sx = (x * sw / dw).min(sw - 1);+            out[y * dw + x] = src[sy * sw + sx];+        }+    }+    out+}++/// Bilinear upscale of a per-pixel gain map.+fn resize_gain(src: &[f32], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<f32> {+    if sw == 0 || sh == 0 {+        return vec![1.0f32; dw * dh];+    }+    let mut out = vec![1.0f32; dw * dh];+    for y in 0..dh {+        let fy = ((y as f64 + 0.5) * sh as f64 / dh as f64 - 0.5).clamp(0.0, sh as f64 - 1.0);+        let y0 = fy.floor() as usize;+        let y1 = (y0 + 1).min(sh - 1);+        let ay = (fy - y0 as f64) as f32;+        for x in 0..dw {+            let fx = ((x as f64 + 0.5) * sw as f64 / dw as f64 - 0.5).clamp(0.0, sw as f64 - 1.0);+            let x0 = fx.floor() as usize;+            let x1 = (x0 + 1).min(sw - 1);+            let ax = (fx - x0 as f64) as f32;+            let g00 = src[y0 * sw + x0];+            let g10 = src[y0 * sw + x1];+            let g01 = src[y1 * sw + x0];+            let g11 = src[y1 * sw + x1];+            let top = g00 * (1.0 - ax) + g10 * ax;+            let bot = g01 * (1.0 - ax) + g11 * ax;+            out[y * dw + x] = top * (1.0 - ay) + bot * ay;+        }+    }+    out+}
camera/rust/src/warp.rs
diff --git a/camera/rust/src/warp.rs b/camera/rust/src/warp.rsnew file mode 100644index 0000000000..710408c990--- /dev/null+++ b/camera/rust/src/warp.rs@@ -0,0 +1,190 @@+//! Warp frames onto a common canvas (via chained homographies) with feather+//! blending and simple gain compensation.++use crate::imgbuf::Rgba;+use nalgebra::{Matrix3, Vector3};++/// Precomputed edge-distance feather weight for a w×h frame.+pub(crate) fn feather_weights(w: usize, h: usize) -> Vec<f32> {+    let mut wt = vec![0f32; w * h];+    for y in 0..h {+        let dy = (y.min(h - 1 - y)) as f32 + 1.0;+        for x in 0..w {+            let dx = (x.min(w - 1 - x)) as f32 + 1.0;+            wt[y * w + x] = dx.min(dy);+        }+    }+    // normalize to [0,1]+    let max = wt.iter().cloned().fold(1.0f32, f32::max);+    for v in wt.iter_mut() {+        *v /= max;+    }+    wt+}++#[inline]+fn apply(h: &Matrix3<f64>, x: f64, y: f64) -> (f64, f64) {+    let v = h * Vector3::new(x, y, 1.0);+    if v.z.abs() < 1e-12 {+        (v.x, v.y)+    } else {+        (v.x / v.z, v.y / v.z)+    }+}++/// Mean luma of an RGBA frame (opaque pixels only).+pub fn mean_luma(f: &Rgba) -> f32 {+    let mut sum = 0f64;+    let mut n = 0f64;+    for i in 0..f.w * f.h {+        if f.px[i * 4 + 3] == 0 {+            continue;+        }+        let r = f.px[i * 4] as f64;+        let g = f.px[i * 4 + 1] as f64;+        let b = f.px[i * 4 + 2] as f64;+        sum += 0.299 * r + 0.587 * g + 0.114 * b;+        n += 1.0;+    }+    if n > 0.0 { (sum / n) as f32 } else { 0.0 }+}++/// Warp all `frames` into the reference plane using `h_to_ref[i]` (frame i ->+/// reference coords), apply per-frame `gains`, feather-blend, and crop to the+/// covered region. Returns the stitched RGBA image.+pub fn warp_and_blend(+    frames: &[Rgba],+    h_to_ref: &[Matrix3<f64>],+    gains: &[f32],+    max_canvas: usize,+) -> Option<Rgba> {+    if frames.is_empty() || frames.len() != h_to_ref.len() {+        return None;+    }+    // 1) canvas bounds from warped frame corners+    let mut min_x = f64::MAX;+    let mut min_y = f64::MAX;+    let mut max_x = f64::MIN;+    let mut max_y = f64::MIN;+    for (f, h) in frames.iter().zip(h_to_ref.iter()) {+        let corners = [+            (0.0, 0.0),+            ((f.w - 1) as f64, 0.0),+            (0.0, (f.h - 1) as f64),+            ((f.w - 1) as f64, (f.h - 1) as f64),+        ];+        for &(cx, cy) in corners.iter() {+            let (x, y) = apply(h, cx, cy);+            min_x = min_x.min(x);+            min_y = min_y.min(y);+            max_x = max_x.max(x);+            max_y = max_y.max(y);+        }+    }+    if !min_x.is_finite() || !max_x.is_finite() {+        return None;+    }+    let cw = (max_x - min_x).ceil() as i64 + 1;+    let ch = (max_y - min_y).ceil() as i64 + 1;+    if cw <= 0 || ch <= 0 || cw as usize > max_canvas || ch as usize > max_canvas {+        return None;+    }+    let cw = cw as usize;+    let ch = ch as usize;++    let mut acc = vec![0f32; cw * ch * 3];+    let mut accw = vec![0f32; cw * ch];++    for (fi, f) in frames.iter().enumerate() {+        let h = h_to_ref[fi];+        let h_inv = match h.try_inverse() {+            Some(m) => m,+            None => continue,+        };+        let gain = gains.get(fi).copied().unwrap_or(1.0);+        let wt = feather_weights(f.w, f.h);++        // Warped bbox of this frame on canvas.+        let corners = [+            (0.0, 0.0),+            ((f.w - 1) as f64, 0.0),+            (0.0, (f.h - 1) as f64),+            ((f.w - 1) as f64, (f.h - 1) as f64),+        ];+        let (mut bx0, mut by0, mut bx1, mut by1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+        for &(cx, cy) in corners.iter() {+            let (x, y) = apply(&h, cx, cy);+            bx0 = bx0.min(x);+            by0 = by0.min(y);+            bx1 = bx1.max(x);+            by1 = by1.max(y);+        }+        let x0 = ((bx0 - min_x).floor() as i64).max(0) as usize;+        let y0 = ((by0 - min_y).floor() as i64).max(0) as usize;+        let x1 = (((bx1 - min_x).ceil() as i64).min(cw as i64 - 1)).max(0) as usize;+        let y1 = (((by1 - min_y).ceil() as i64).min(ch as i64 - 1)).max(0) as usize;++        for cy in y0..=y1 {+            for cx in x0..=x1 {+                // canvas -> reference -> source frame+                let rx = cx as f64 + min_x;+                let ry = cy as f64 + min_y;+                let (sx, sy) = apply(&h_inv, rx, ry);+                if let Some(c) = f.sample(sx as f32, sy as f32) {+                    if c[3] < 8.0 {+                        continue;+                    }+                    // feather weight from nearest source pixel+                    let ix = (sx as usize).min(f.w - 1);+                    let iy = (sy as usize).min(f.h - 1);+                    let w = wt[iy * f.w + ix];+                    if w <= 0.0 {+                        continue;+                    }+                    let idx = cy * cw + cx;+                    acc[idx * 3] += (c[0] * gain).min(255.0) * w;+                    acc[idx * 3 + 1] += (c[1] * gain).min(255.0) * w;+                    acc[idx * 3 + 2] += (c[2] * gain).min(255.0) * w;+                    accw[idx] += w;+                }+            }+        }+    }++    // 2) resolve accumulation + crop to covered bbox+    let (mut minx, mut miny, mut maxx, mut maxy) = (cw, ch, 0usize, 0usize);+    let mut any = false;+    for y in 0..ch {+        for x in 0..cw {+            if accw[y * cw + x] > 0.0 {+                any = true;+                minx = minx.min(x);+                miny = miny.min(y);+                maxx = maxx.max(x);+                maxy = maxy.max(y);+            }+        }+    }+    if !any {+        return None;+    }+    let ow = maxx - minx + 1;+    let oh = maxy - miny + 1;+    let mut out = Rgba::new(ow, oh);+    for y in 0..oh {+        for x in 0..ow {+            let sidx = (y + miny) * cw + (x + minx);+            let w = accw[sidx];+            let didx = (y * ow + x) * 4;+            if w > 0.0 {+                out.px[didx] = (acc[sidx * 3] / w).round().clamp(0.0, 255.0) as u8;+                out.px[didx + 1] = (acc[sidx * 3 + 1] / w).round().clamp(0.0, 255.0) as u8;+                out.px[didx + 2] = (acc[sidx * 3 + 2] / w).round().clamp(0.0, 255.0) as u8;+                out.px[didx + 3] = 255;+            } else {+                out.px[didx + 3] = 0;+            }+        }+    }+    Some(out)+}
camera/rust/src/wave.rs
diff --git a/camera/rust/src/wave.rs b/camera/rust/src/wave.rsnew file mode 100644index 0000000000..8bd3030bf7--- /dev/null+++ b/camera/rust/src/wave.rs@@ -0,0 +1,57 @@+//! waveCorrect (motion_estimators.cpp, WAVE_CORRECT_HORIZ): removes the vertical+//! "wave" by re-aligning all camera rotations to a common up/right frame.++use crate::camera::CameraParams;+use nalgebra::{Matrix3, Vector3};++pub fn wave_correct_horizontal(cams: &mut [CameraParams]) {+    if cams.len() <= 1 {+        return;+    }+    // moment = Σ col0 · col0ᵀ+    let mut moment = Matrix3::<f64>::zeros();+    for c in cams.iter() {+        let col0 = c.r.column(0).into_owned();+        moment += col0 * col0.transpose();+    }+    let se = moment.symmetric_eigen();+    // eigenvector for the smallest eigenvalue+    let mut min_i = 0;+    for i in 1..3 {+        if se.eigenvalues[i] < se.eigenvalues[min_i] {+            min_i = i;+        }+    }+    let mut rg1 = se.eigenvectors.column(min_i).into_owned();++    // img_k = Σ col2+    let mut img_k = Vector3::<f64>::zeros();+    for c in cams.iter() {+        img_k += c.r.column(2).into_owned();+    }++    let mut rg0 = rg1.cross(&img_k);+    let n0 = rg0.norm();+    if n0 < 1e-9 {+        return;+    }+    rg0 /= n0;+    let rg2 = rg0.cross(&rg1);++    // orientation confidence+    let mut conf = 0.0;+    for c in cams.iter() {+        conf += rg0.dot(&c.r.column(0));+    }+    if conf < 0.0 {+        rg0 = -rg0;+        rg1 = -rg1;+    }+    let rg2 = if conf < 0.0 { rg0.cross(&rg1) } else { rg2 };++    // R_wave has rows rg0ᵀ, rg1ᵀ, rg2ᵀ+    let r_wave = Matrix3::from_rows(&[rg0.transpose(), rg1.transpose(), rg2.transpose()]);+    for c in cams.iter_mut() {+        c.r = r_wave * c.r;+    }+}
camera/rust/testdata/output.jpg
diff --git a/camera/rust/testdata/output.jpg b/camera/rust/testdata/output.jpgnew file mode 100644index 0000000000..1520ec4006Binary files /dev/null and b/camera/rust/testdata/output.jpg differ
camera/rust/testdata/panorama.jpg
diff --git a/camera/rust/testdata/panorama.jpg b/camera/rust/testdata/panorama.jpgnew file mode 100644index 0000000000..ea982fa63dBinary files /dev/null and b/camera/rust/testdata/panorama.jpg differ
camera/rust/testdata/q11.jpg
diff --git a/camera/rust/testdata/q11.jpg b/camera/rust/testdata/q11.jpgnew file mode 100644index 0000000000..743476a978Binary files /dev/null and b/camera/rust/testdata/q11.jpg differ
camera/rust/testdata/q22.jpg
diff --git a/camera/rust/testdata/q22.jpg b/camera/rust/testdata/q22.jpgnew file mode 100644index 0000000000..823fed9103Binary files /dev/null and b/camera/rust/testdata/q22.jpg differ