mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
craft-develop: track clipping at bilinear taps
This commit is contained in:
@@ -11,7 +11,7 @@
|
||||
//! Every method reproduces a constant-colour mosaic exactly.
|
||||
|
||||
mod ahd;
|
||||
mod bilinear;
|
||||
pub(super) mod bilinear;
|
||||
mod ppg;
|
||||
mod xtrans;
|
||||
|
||||
@@ -26,6 +26,10 @@ pub enum Method {
|
||||
Ahd,
|
||||
}
|
||||
|
||||
pub(super) fn mosaic_method(cfa: &Cfa, w: usize, h: usize, method: Method) -> Method {
|
||||
if (w < 4 || h < 4) && cfa.is_bayer() { Method::Bilinear } else { method }
|
||||
}
|
||||
|
||||
/// Mirror-reflected access to a single-plane mosaic (reflection keeps Bayer parity: −k → k, w−1+k → w−1−k).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Mosaic<'a> {
|
||||
@@ -96,17 +100,9 @@ pub fn demosaic(n: &Normalized, method: Method) -> Rgb32f {
|
||||
(None, _) => Rgb32f { width: w, height: h, data: n.data.iter().map(|&v| [v; 3]).collect() },
|
||||
(Some(cfa), _) => {
|
||||
let m = Mosaic { w, h, data: &n.data, cfa };
|
||||
if !cfa.is_bayer() {
|
||||
return match method {
|
||||
Method::Bilinear => bilinear::bilinear(&m),
|
||||
_ => xtrans::directional(&m),
|
||||
};
|
||||
}
|
||||
if w < 4 || h < 4 {
|
||||
return bilinear::bilinear(&m);
|
||||
}
|
||||
match method {
|
||||
match mosaic_method(cfa, w, h, method) {
|
||||
Method::Bilinear => bilinear::bilinear(&m),
|
||||
_ if !cfa.is_bayer() => xtrans::directional(&m),
|
||||
Method::Ppg => ppg::ppg(&m),
|
||||
Method::Ahd => ahd::ahd(&m),
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
//! Bilinear demosaicing for any CFA pattern: each missing colour is the mean of the same-colour samples in the
|
||||
//! 3×3 neighbourhood (5×5 when the 3×3 has none, as happens in some non-Bayer layouts).
|
||||
|
||||
use super::super::Rgb32f;
|
||||
use super::Mosaic;
|
||||
use crate::raster::par_rows;
|
||||
use crate::sensor::highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS};
|
||||
use crate::sensor::{Rect, Rgb32f};
|
||||
|
||||
type PhaseTaps = [Vec<(isize, isize)>; 3];
|
||||
|
||||
/// Offsets (dx, dy) of same-colour neighbours for each pattern position and colour.
|
||||
pub(crate) fn neighbour_table(m: &Mosaic) -> Vec<[Vec<(isize, isize)>; 3]> {
|
||||
fn neighbour_table(m: &Mosaic) -> Vec<PhaseTaps> {
|
||||
let cfa = m.cfa;
|
||||
let mut table = Vec::with_capacity(cfa.width * cfa.height);
|
||||
for py in 0..cfa.height {
|
||||
@@ -33,6 +36,34 @@ pub(crate) fn neighbour_table(m: &Mosaic) -> Vec<[Vec<(isize, isize)>; 3]> {
|
||||
table
|
||||
}
|
||||
|
||||
/// Visit the samples that contribute to a missing channel, in interpolation order.
|
||||
#[inline]
|
||||
fn for_each_tap(m: &Mosaic, table: &[PhaseTaps], x: usize, y: usize, c: usize, mut visit: impl FnMut(f32)) {
|
||||
let cfa = m.cfa;
|
||||
if x >= 2 && y >= 2 && x + 2 < m.w && y + 2 < m.h {
|
||||
let entry = &table[(y % cfa.height) * cfa.width + (x % cfa.width)];
|
||||
for &(dx, dy) in &entry[c] {
|
||||
visit(m.data[(y as isize + dy) as usize * m.w + (x as isize + dx) as usize]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for r in [1isize, 2] {
|
||||
let mut found = false;
|
||||
for dy in -r..=r {
|
||||
for dx in -r..=r {
|
||||
let (nx, ny) = (x as isize + dx, y as isize + dy);
|
||||
if m.color(nx, ny) as usize == c {
|
||||
visit(m.get(nx, ny));
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f {
|
||||
let (w, h) = (m.w, m.h);
|
||||
let table = neighbour_table(m);
|
||||
@@ -41,38 +72,44 @@ pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f {
|
||||
par_rows(&mut out.data, w, |y, row| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let own = cfa.color_at(x, y) as usize;
|
||||
let interior = x >= 2 && y >= 2 && x + 2 < w && y + 2 < h;
|
||||
let entry = &table[(y % cfa.height) * cfa.width + (x % cfa.width)];
|
||||
for c in 0..3 {
|
||||
for (c, channel) in px.iter_mut().enumerate() {
|
||||
if c == own {
|
||||
px[c] = m.data[y * w + x];
|
||||
*channel = m.data[y * w + x];
|
||||
continue;
|
||||
}
|
||||
let (mut s, mut n) = (0.0f32, 0u32);
|
||||
if interior {
|
||||
for &(dx, dy) in &entry[c] {
|
||||
s += m.data[(y as isize + dy) as usize * w + (x as isize + dx) as usize];
|
||||
n += 1;
|
||||
}
|
||||
} else {
|
||||
for r in [1isize, 2] {
|
||||
for dy in -r..=r {
|
||||
for dx in -r..=r {
|
||||
let (nx, ny) = (x as isize + dx, y as isize + dy);
|
||||
if m.color(nx, ny) as usize == c {
|
||||
s += m.get(nx, ny);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
px[c] = if n > 0 { s / n as f32 } else { m.data[y * w + x] };
|
||||
for_each_tap(m, &table, x, y, c, |v| {
|
||||
s += v;
|
||||
n += 1;
|
||||
});
|
||||
*channel = if n > 0 { s / n as f32 } else { m.data[y * w + x] };
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
pub(in crate::sensor) fn clip_mask(m: &Mosaic, crop: Rect, clip: f32) -> Vec<u8> {
|
||||
let table = neighbour_table(m);
|
||||
let mut mask = vec![0; crop.width * crop.height];
|
||||
par_rows(&mut mask, crop.width, |oy, row| {
|
||||
let y = crop.y + oy;
|
||||
for (ox, bits) in row.iter_mut().enumerate() {
|
||||
let x = crop.x + ox;
|
||||
let own = m.cfa.color_at(x, y) as usize;
|
||||
if m.data[y * m.w + x] >= clip {
|
||||
*bits = CLIPPED_BITS[own];
|
||||
continue;
|
||||
}
|
||||
// Each channel uses only its own taps, so leave the measured-colour field unset.
|
||||
for (c, bit) in FROM_CLIPPED_BITS.into_iter().enumerate().filter(|&(c, _)| c != own) {
|
||||
for_each_tap(m, &table, x, y, c, |v| {
|
||||
if v >= clip {
|
||||
*bits |= bit;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
mask
|
||||
}
|
||||
|
||||
@@ -377,21 +377,24 @@ pub const CLIPPED_B: u8 = 4;
|
||||
pub const FROM_CLIPPED_R: u8 = 8;
|
||||
pub const FROM_CLIPPED_G: u8 = 16;
|
||||
pub const FROM_CLIPPED_B: u8 = 32;
|
||||
/// Bits 6 and 7 of a [`reconstruct_masked`] mask entry: the colour the pixel measured itself, plus one (0: not told,
|
||||
/// as for binned pixels, which measured none on their own).
|
||||
/// Bits 6 and 7 of a directional [`reconstruct_masked`] mask entry: the measured colour plus one.
|
||||
/// Binned and bilinear masks leave this field at zero.
|
||||
pub const MEASURED_SHIFT: u8 = 6;
|
||||
|
||||
pub(super) const CLIPPED_BITS: [u8; 3] = [CLIPPED_R, CLIPPED_G, CLIPPED_B];
|
||||
pub(super) const FROM_CLIPPED_BITS: [u8; 3] = [FROM_CLIPPED_R, FROM_CLIPPED_G, FROM_CLIPPED_B];
|
||||
|
||||
/// [`reconstruct_with`] for a binned image ([`super::RawDevelopExt::develop_binned_masked`]): its values are block
|
||||
/// means, and `mask` (one entry per pixel, bits [`CLIPPED_R`], [`CLIPPED_G`], [`CLIPPED_B`]) says which colours
|
||||
/// had a clipped sample in the block. Those channels count as clipped with their mean as the lower bound of their
|
||||
/// true value, so one clipped specular sample among many unclipped ones neither escapes reconstruction nor
|
||||
/// (as the block's maximum would) lifts the channel to the clip level, which reads as a coloured speckle (#548).
|
||||
///
|
||||
/// For a full-size demosaic ([`super::RawDevelopExt::develop_balanced_masked`]), the mask marks the measured colour
|
||||
/// and colours interpolated from nearby clipped samples. Below the clip, an interpolated channel marked this
|
||||
/// way is unknown. The other interpolated channel may depend on the same clipped samples, so reconstruction
|
||||
/// treats it as unknown below the clip too. Reconstruction uses the measured colour and limits brightness
|
||||
/// changes near strongly coloured highlights.
|
||||
/// For a full-size demosaic ([`super::RawDevelopExt::develop_balanced_masked`]), the mask marks colours
|
||||
/// interpolated from clipped samples. Below the clip, an interpolated channel marked this way is unknown.
|
||||
/// A directional mask also records the measured colour. In that case, the other interpolated channel may
|
||||
/// depend on the same clipped samples, so reconstruction treats it as unknown below the clip too.
|
||||
/// Reconstruction uses the known channels and limits brightness changes near strongly coloured highlights.
|
||||
///
|
||||
/// A mask of the wrong length is ignored (clipping is then told by the values alone).
|
||||
pub fn reconstruct_masked(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], mask: &[u8]) -> usize {
|
||||
@@ -422,8 +425,8 @@ impl Clipping {
|
||||
#[inline]
|
||||
fn masked(m: u8, p: &[f32; 3], clip: f32) -> Clipping {
|
||||
let bit = |b: u8| m & b != 0;
|
||||
let saturated = std::array::from_fn(|c| p[c] >= clip || bit([CLIPPED_R, CLIPPED_G, CLIPPED_B][c]));
|
||||
let mut unknown: [bool; 3] = std::array::from_fn(|c| bit([FROM_CLIPPED_R, FROM_CLIPPED_G, FROM_CLIPPED_B][c]) && !saturated[c]);
|
||||
let saturated = std::array::from_fn(|c| p[c] >= clip || bit(CLIPPED_BITS[c]));
|
||||
let mut unknown: [bool; 3] = std::array::from_fn(|c| bit(FROM_CLIPPED_BITS[c]) && !saturated[c]);
|
||||
if let Some(own) = ((m >> MEASURED_SHIFT) as usize).checked_sub(1).filter(|&c| !saturated[c])
|
||||
&& unknown.iter().any(|&u| u)
|
||||
{
|
||||
|
||||
@@ -149,7 +149,7 @@ impl RawDevelopExt for RawImage {
|
||||
|
||||
fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option<Vec<u8>>)> {
|
||||
let n = self.normalized()?;
|
||||
let mask = clip_mask(self, &n, clip);
|
||||
let mask = clip_mask(self, &n, method, clip);
|
||||
Ok((develop_full(self, n, method, Some(wb)), mask))
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ fn balance_gains(wb: [f32; 3]) -> Option<[f32; 3]> {
|
||||
|
||||
fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool {
|
||||
let Some(cfa) = n.cfa.as_ref().filter(|_| n.cpp == 1) else { return false };
|
||||
if method == Method::Bilinear || (cfa.is_bayer() && (n.width < 4 || n.height < 4)) {
|
||||
if demosaic::mosaic_method(cfa, n.width, n.height, method) == Method::Bilinear {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -234,12 +234,12 @@ fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn clip_mask(raw: &RawImage, n: &Normalized, clip: f32) -> Option<Vec<u8>> {
|
||||
fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option<Vec<u8>> {
|
||||
use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS};
|
||||
|
||||
// This radius covers samples read directly by the directional interpolators. Estimates
|
||||
// that build on interpolated green can depend on samples farther away.
|
||||
const REACH: usize = 2;
|
||||
const FROM: [u8; 3] = [highlight::FROM_CLIPPED_R, highlight::FROM_CLIPPED_G, highlight::FROM_CLIPPED_B];
|
||||
const CLIPPED: [u8; 3] = [highlight::CLIPPED_R, highlight::CLIPPED_G, highlight::CLIPPED_B];
|
||||
|
||||
let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?;
|
||||
let (w, h) = (n.width, n.height);
|
||||
@@ -255,12 +255,17 @@ fn clip_mask(raw: &RawImage, n: &Normalized, clip: f32) -> Option<Vec<u8>> {
|
||||
if !has_clip {
|
||||
return None;
|
||||
}
|
||||
if demosaic::mosaic_method(cfa, w, h, method) == Method::Bilinear {
|
||||
let mosaic = demosaic::Mosaic { w, h, data: &n.data, cfa };
|
||||
return Some(demosaic::bilinear::clip_mask(&mosaic, crop, clip));
|
||||
}
|
||||
|
||||
// Collect clipped colours within reach horizontally, then combine those rows for each output pixel.
|
||||
let mut rows = vec![0u8; w * h];
|
||||
par_rows(&mut rows, w, |y, row| {
|
||||
let samples = &n.data[y * w..(y + 1) * w];
|
||||
let clipped: Vec<u8> = samples.iter().enumerate().map(|(x, v)| if is_clipped(v) { FROM[cfa.color_at(x, y) as usize] } else { 0 }).collect();
|
||||
let clipped: Vec<u8> =
|
||||
samples.iter().enumerate().map(|(x, v)| if is_clipped(v) { FROM_CLIPPED_BITS[cfa.color_at(x, y) as usize] } else { 0 }).collect();
|
||||
for (x, bits) in row.iter_mut().enumerate() {
|
||||
*bits = clipped[x.saturating_sub(REACH)..=(x + REACH).min(w - 1)].iter().fold(0, |a, b| a | b);
|
||||
}
|
||||
@@ -275,10 +280,10 @@ fn clip_mask(raw: &RawImage, n: &Normalized, clip: f32) -> Option<Vec<u8>> {
|
||||
for (ox, bits) in out.iter_mut().enumerate() {
|
||||
let x = crop.x + ox;
|
||||
let colour = cfa.color_at(x, y);
|
||||
let from = *bits & !FROM[colour as usize];
|
||||
let from = *bits & !FROM_CLIPPED_BITS[colour as usize];
|
||||
*bits = if is_clipped(&n.data[y * w + x]) {
|
||||
// Keep the interpolated values around a clipped measurement. They can carry thin dark detail.
|
||||
CLIPPED[colour as usize]
|
||||
CLIPPED_BITS[colour as usize]
|
||||
} else if from != 0 {
|
||||
from | ((colour + 1) << highlight::MEASURED_SHIFT)
|
||||
} else {
|
||||
|
||||
@@ -355,6 +355,32 @@ fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() {
|
||||
assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bilinear_clip_mask_marks_only_actual_taps() {
|
||||
let cfa = Cfa::bayer("RGGB").unwrap();
|
||||
for (width, method) in [(16, Method::Bilinear), (3, Method::Ahd), (3, Method::Ppg)] {
|
||||
let raw = raw_of(width, 10, &cfa, [1.0; 3], |x, y| if (x, y) == (0, 2) { [1.0; 3] } else { [0.21, 0.15, 0.11] });
|
||||
let (mut image, mask) = raw.develop_balanced_masked(method, [1.0; 3], CLIP).unwrap();
|
||||
let mask = mask.unwrap();
|
||||
let clean = image.get(2, 3);
|
||||
let blue = image.get(1, 2)[2];
|
||||
highlight::reconstruct_masked(&mut image, [1.0; 3], CLIP, [1.0; 3], &mask);
|
||||
assert_eq!(image.get(2, 3), clean, "the clipped red sample is outside these bilinear taps");
|
||||
assert_eq!(mask[3 * width + 2], 0);
|
||||
assert_eq!(mask[2 * width + 1] & highlight::FROM_CLIPPED_R, highlight::FROM_CLIPPED_R);
|
||||
assert_eq!(image.get(1, 2)[2], blue, "blue interpolation uses its own samples");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bilinear_clip_mask_keeps_the_wider_taps_for_sparse_cfas() {
|
||||
let cfa = Cfa { width: 6, height: 1, pattern: vec![0, 1, 1, 1, 2, 1], origin_x: 0, origin_y: 0 };
|
||||
let raw = raw_of(12, 10, &cfa, [1.0; 3], |x, y| if (x, y) == (0, 2) { [1.0; 3] } else { [0.21, 0.15, 0.11] });
|
||||
let (_, mask) = raw.develop_balanced_masked(Method::Bilinear, DAYLIGHT, CLIP).unwrap();
|
||||
let mask = mask.unwrap();
|
||||
assert_ne!(mask[2 * raw.width + 2] & highlight::FROM_CLIPPED_R, 0, "the closest red taps are two columns away");
|
||||
}
|
||||
|
||||
/// Review of #1328: dark twigs and wires against a clipped sky (every channel clipped around them) keep their level.
|
||||
/// A pixel's own CFA sample is measured: a clipped neighbour of the same colour says nothing about it, and the colours
|
||||
/// interpolated from clipped samples are unknown, not lower bounds. Taken as lower bounds (with the pixel's own colour
|
||||
@@ -510,10 +536,16 @@ fn coloured_highlights_keep_their_brightness_at_the_edges() {
|
||||
}
|
||||
n += 1;
|
||||
let ratio = |p: [f32; 3]| lum(p) / lum(t).max(1e-4);
|
||||
if ratio(out.get(x, y)) < 0.6 {
|
||||
dark.push((x, y, ratio(out.get(x, y))));
|
||||
let masked_ratio = ratio(out.get(x, y));
|
||||
let value_ratio = ratio(by_value.get(x, y));
|
||||
assert!(
|
||||
masked_ratio.is_finite() && value_ratio.is_finite(),
|
||||
"{scene_name} {tint:?} x{level}, {name} at ({x}, {y}): masked ratio {masked_ratio}, by-value ratio {value_ratio}"
|
||||
);
|
||||
if masked_ratio < 0.6 {
|
||||
dark.push((x, y, masked_ratio));
|
||||
}
|
||||
if ratio(by_value.get(x, y)) < 0.6 {
|
||||
if value_ratio < 0.6 {
|
||||
dark_by_value += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user