use crate::features::GrayscaleImage;
use crate::stereo::triangulate_stereo_pixel;
use nalgebra::Point3;
use visloc_core::types::Camera;
#[derive(Debug, Clone, PartialEq)]
pub struct DenseStereoConfig {
pub min_disparity: usize,
pub max_disparity: usize,
pub block_radius: usize,
pub max_block_diff: f32,
pub uniqueness_ratio: f32,
pub lr_consistency_px: Option<f32>,
}
impl Default for DenseStereoConfig {
fn default() -> Self {
Self {
min_disparity: 1,
max_disparity: 96,
block_radius: 3,
max_block_diff: 0.08,
uniqueness_ratio: 0.9,
lr_consistency_px: Some(1.5),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DenseStereoPoint {
pub pixel: (usize, usize),
pub point_cam: Point3<f64>,
pub disparity: f32,
pub intensity: f32,
}
#[inline]
fn at(img: &GrayscaleImage, x: usize, y: usize) -> f32 {
img.pixels()[y * img.width() + x]
}
#[inline]
fn block_cost(
left: &GrayscaleImage,
right: &GrayscaleImage,
lx: usize,
rx: usize,
ly: usize,
r: usize,
) -> f32 {
let mut sum = 0.0f32;
let n = (2 * r + 1) * (2 * r + 1);
for dy in 0..=(2 * r) {
let y = ly + dy - r;
for dx in 0..=(2 * r) {
sum += (at(left, lx + dx - r, y) - at(right, rx + dx - r, y)).abs();
}
}
sum / n as f32
}
fn best_disparity_at(
left: &GrayscaleImage,
right: &GrayscaleImage,
x: usize,
y: usize,
cfg: &DenseStereoConfig,
) -> Option<(usize, f32, f32)> {
let r = cfg.block_radius;
let mut best_d = 0usize;
let mut best = f32::INFINITY;
let mut second = f32::INFINITY;
let d_lo = cfg.min_disparity.max(1);
for d in d_lo..=cfg.max_disparity {
if x < d + r {
break;
}
let rx = x - d;
let cost = block_cost(left, right, x, rx, y, r);
if cost < best {
second = best;
best = cost;
best_d = d;
} else if cost < second {
second = cost;
}
}
if best.is_finite() {
Some((best_d, best, second))
} else {
None
}
}
pub fn dense_disparity_map(
left: &GrayscaleImage,
right: &GrayscaleImage,
cfg: &DenseStereoConfig,
) -> Vec<f32> {
let w = left.width();
let h = left.height();
let mut out = vec![f32::NAN; w * h];
if right.width() != w || right.height() != h {
return out;
}
let r = cfg.block_radius;
if w <= 2 * r + cfg.max_disparity || h <= 2 * r {
return out;
}
for y in r..(h - r) {
for x in (r + cfg.min_disparity.max(1))..(w - r) {
let Some((d, best, second)) = best_disparity_at(left, right, x, y, cfg) else {
continue;
};
if best > cfg.max_block_diff {
continue;
}
if cfg.uniqueness_ratio < 1.0
&& second.is_finite()
&& best > cfg.uniqueness_ratio * second
{
continue;
}
if let Some(tol) = cfg.lr_consistency_px {
let rx = x - d;
if let Some((d_back, _, _)) = best_disparity_right(left, right, rx, y, cfg) {
if ((d as f32) - (d_back as f32)).abs() > tol {
continue;
}
} else {
continue;
}
}
out[y * w + x] = d as f32;
}
}
out
}
fn best_disparity_right(
left: &GrayscaleImage,
right: &GrayscaleImage,
rx: usize,
y: usize,
cfg: &DenseStereoConfig,
) -> Option<(usize, f32, f32)> {
let r = cfg.block_radius;
let w = left.width();
let mut best_d = 0usize;
let mut best = f32::INFINITY;
let mut second = f32::INFINITY;
let d_lo = cfg.min_disparity.max(1);
for d in d_lo..=cfg.max_disparity {
let lx = rx + d;
if lx + r >= w {
break;
}
let cost = block_cost(left, right, lx, rx, y, r);
if cost < best {
second = best;
best = cost;
best_d = d;
} else if cost < second {
second = cost;
}
}
if best.is_finite() {
Some((best_d, best, second))
} else {
None
}
}
pub fn dense_stereo_points(
left: &GrayscaleImage,
right: &GrayscaleImage,
camera: &Camera,
baseline: f64,
cfg: &DenseStereoConfig,
) -> Vec<DenseStereoPoint> {
let disparities = dense_disparity_map(left, right, cfg);
let w = left.width();
let h = left.height();
let mut points = Vec::new();
for y in 0..h {
for x in 0..w {
let d = disparities[y * w + x];
if !d.is_finite() {
continue;
}
let Some(point_cam) = triangulate_stereo_pixel(
camera,
baseline,
(x as f64, y as f64),
((x as f64) - d as f64, y as f64),
0.0,
) else {
continue;
};
points.push(DenseStereoPoint {
pixel: (x, y),
point_cam,
disparity: d,
intensity: at(left, x, y),
});
}
}
points
}
#[cfg(test)]
mod tests {
use super::*;
fn textured(w: usize, h: usize) -> Vec<f32> {
let mut px = vec![0.0f32; w * h];
for y in 0..h {
for x in 0..w {
let v = ((x.wrapping_mul(73856093) ^ y.wrapping_mul(19349663)) % 251) as f32;
px[y * w + x] = v / 251.0;
}
}
px
}
fn shift_right(left_px: &[f32], w: usize, h: usize, d: usize) -> Vec<f32> {
let mut r = vec![0.0f32; w * h];
for y in 0..h {
for x in 0..w {
let src = x + d;
r[y * w + x] = if src < w { left_px[y * w + src] } else { 0.0 };
}
}
r
}
#[test]
fn recovers_constant_disparity() {
let (w, h, d) = (96, 64, 12);
let lpx = textured(w, h);
let rpx = shift_right(&lpx, w, h, d);
let left = GrayscaleImage::new(w, h, lpx).unwrap();
let right = GrayscaleImage::new(w, h, rpx).unwrap();
let cfg = DenseStereoConfig {
min_disparity: 1,
max_disparity: 32,
block_radius: 3,
max_block_diff: 0.02,
uniqueness_ratio: 1.0, lr_consistency_px: Some(1.5),
};
let disp = dense_disparity_map(&left, &right, &cfg);
let mut matched = 0usize;
let mut correct = 0usize;
for y in 6..(h - 6) {
for x in 16..(w - d - 6) {
let v = disp[y * w + x];
if v.is_finite() {
matched += 1;
if (v - d as f32).abs() < 1e-3 {
correct += 1;
}
}
}
}
assert!(matched > 100, "expected many matched pixels, got {matched}");
let frac = correct as f32 / matched as f32;
assert!(
frac > 0.95,
"recovered disparity wrong: {correct}/{matched} = {frac:.3} at d={d}"
);
}
#[test]
fn back_projects_to_metric_points() {
let (w, h, d) = (96, 64, 12);
let lpx = textured(w, h);
let rpx = shift_right(&lpx, w, h, d);
let left = GrayscaleImage::new(w, h, lpx).unwrap();
let right = GrayscaleImage::new(w, h, rpx).unwrap();
let camera = Camera::pinhole(0, w as u32, h as u32, 200.0, 200.0, 48.0, 32.0);
let baseline = 0.1;
let cfg = DenseStereoConfig {
max_disparity: 32,
max_block_diff: 0.02,
uniqueness_ratio: 1.0,
..DenseStereoConfig::default()
};
let pts = dense_stereo_points(&left, &right, &camera, baseline, &cfg);
assert!(!pts.is_empty());
let z_expected = 200.0 * baseline / d as f64;
for p in &pts {
assert!(p.point_cam.z > 0.0);
assert!(
(p.point_cam.z - z_expected).abs() < 1e-6,
"depth {} != {}",
p.point_cam.z,
z_expected
);
}
}
}