Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Debayering

A one-shot color camera has a single sensor with a grid of color filters over it, one filter per pixel. Each pixel records only red, green or blue, so the raw frame is a mosaic: one number per pixel, arranged in a repeating 2 x 2 tile called a Bayer pattern. Debayering, or demosaicing, estimates the two missing colors at every pixel from its neighbors and turns the mosaic into an RGB image.

Most capture programs save the raw mosaic and leave debayering to the processing software, because calibration with darks and flats has to happen on the mosaic first. The crate debayers mosaics of every sample type, integer or float, with bilinear interpolation.

Debayer an image

Image::debayer takes the pattern and replaces the mono mosaic with an interleaved RGB image of the same width and height. The pattern has to match the sensor, and the example shows what a wrong one does to a mosaic of an evenly lit target:

use celestial_images::debayer::BayerPattern;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;

// A 4 x 4 RGGB mosaic of an evenly lit target:
// red sites read 600, green sites 1000, blue sites 400.
fn mosaic() -> Image {
    let mut raw = Vec::new();
    for y in 0..4 {
        for x in 0..4 {
            raw.push(match (x % 2, y % 2) {
                (0, 0) => 600u16,
                (1, 1) => 400,
                _ => 1000,
            });
        }
    }
    Image::new(PixelData::U16(raw), [4, 4])
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    for pattern in [BayerPattern::Rggb, BayerPattern::Bggr, BayerPattern::Grbg] {
        let mut img = mosaic();
        img.debayer(pattern)?;
        // RGB samples are interleaved: R, G, B of pixel 0, then pixel 1, ...
        let rgb = img.pixels.as_u16().ok_or("not u16")?;
        let pixel = |x: usize, y: usize| &rgb[(y * 4 + x) * 3..][..3];
        println!(
            "{pattern:?}: {:?} {:?} {:?}",
            img.dimensions,
            pixel(1, 1),
            pixel(2, 1)
        );
    }
    Ok(())
}
Rggb: [4, 4, 3] [600, 1000, 400] [600, 1000, 400]
Bggr: [4, 4, 3] [400, 1000, 600] [400, 1000, 600]
Grbg: [4, 4, 3] [1000, 400, 1000] [1000, 500, 1000]

With the right pattern, every pixel comes out as the color the target actually has. Bggr swaps red and blue, so the image is the right brightness with the wrong hue. Grbg reads the green samples as red and blue, so the whole image turns magenta, and the green channel changes from one pixel to the next in a fine grid. If your first debayered image has either look, try another pattern.

The pattern names the colors of the top-left 2 x 2 tile, read left to right and then top to bottom. Rggb means red at (0, 0), green at (1, 0) and (0, 1), and blue at (1, 1).

Get the pattern from the header

Capture programs record the pattern in a BAYERPAT keyword. The crate doesn’t read it for you, so map it to a BayerPattern yourself:

use celestial_images::debayer::BayerPattern;
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;

fn bayer_pattern(img: &Image) -> Option<BayerPattern> {
    match img.get("BAYERPAT").as_str()? {
        "RGGB" => Some(BayerPattern::Rggb),
        "GRBG" => Some(BayerPattern::Grbg),
        "GBRG" => Some(BayerPattern::Gbrg),
        "BGGR" => Some(BayerPattern::Bggr),
        _ => None,
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A raw frame from a one-shot color camera, as a capture program saves it
    let mut raw = Image::new(PixelData::U16(vec![1000; 3008 * 3008]), [3008, 3008]);
    raw.set_keyword(Keyword::string("BAYERPAT", "RGGB"));
    raw.save("osc_light.fits")?;

    let mut img = Image::open("osc_light.fits")?;
    let pattern = bayer_pattern(&img).ok_or("no BAYERPAT, or one this code doesn't handle")?;
    img.debayer(pattern)?;
    println!("{pattern:?}: {} channels, {:?}", img.channels(), img.kind());
    println!("BAYERPAT after debayer: {:?}", img.get("BAYERPAT").as_str());
    img.save("osc_light_rgb.fits")?;
    Ok(())
}
Rggb: 3 channels, Rgb
BAYERPAT after debayer: None

debayer removes BAYERPAT, XBAYROFF and YBAYROFF, because they describe the mosaic and the pixels are RGB now. A program that opened the RGB file and still found them might try to debayer it a second time.

Some capture programs also write ROWORDER = 'BOTTOM-UP', which means the rows are stored bottom row first, or XBAYROFF and YBAYROFF, which shift the pattern by a pixel. Either one changes which pattern describes the data as stored. debayer doesn’t apply any of them, so adjust the pattern before you pass it in: with the rows flipped, RGGB becomes GBRG.

Debayer SER frames

A color planetary capture stores the pattern in the SER header’s color_id, and BayerPattern::from_color_id converts it. For captures deeper than 8 bits, read_frame_u16 decodes each frame and debayer_bilinear_u16 debayers the samples without building an Image:

use celestial_images::debayer::{debayer_bilinear_u16, BayerPattern};
use celestial_images::ser::header::SerHeader;
use celestial_images::ser::reader::SerReader;
use celestial_images::ser::types::ColorId;
use celestial_images::ser::writer::SerWriter;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A short 12-bit capture from a color planetary camera
    let header = SerHeader {
        color_id: ColorId::BayerRggb,
        image_width: 640,
        image_height: 480,
        pixel_depth_per_plane: 12,
        ..SerHeader::default()
    };
    let mut writer = SerWriter::create("saturn.ser", header)?;
    for _ in 0..3 {
        writer.write_frame(&vec![0u8; 640 * 480 * 2])?;
    }
    writer.finalize()?;

    let reader = SerReader::open("saturn.ser")?;
    let header = reader.header();
    let (width, height) = (header.image_width as usize, header.image_height as usize);
    let pattern = BayerPattern::from_color_id(header.color_id).ok_or("not a Bayer capture")?;

    for id in 0..reader.frame_count() {
        let raw = reader.read_frame_u16(id)?;
        let rgb = debayer_bilinear_u16(&raw, width, height, pattern)?;
        println!(
            "frame {id}: {} mosaic samples -> {} RGB samples",
            raw.len(),
            rgb.len()
        );
    }
    Ok(())
}
frame 0: 307200 mosaic samples -> 921600 RGB samples
frame 1: 307200 mosaic samples -> 921600 RGB samples
frame 2: 307200 mosaic samples -> 921600 RGB samples

debayer_bilinear_u8 does the same for 8-bit frames, which frame.data from iter_frames gives you directly. Both functions return the RGB samples interleaved, and return an error unless the slice holds exactly width × height samples and the mosaic is at least 2 x 2. from_color_id returns None for the CMY patterns SER also defines, since the crate debayers RGB filters only. SER Video Files covers reading captures.

How bilinear interpolation works

At each pixel, the color the filter recorded is kept, and each missing color is the mean of the nearest pixels that recorded it. A red site takes green from its four horizontal and vertical neighbors and blue from its four diagonal ones. A green site takes red and blue from its two neighbors on the row or column where those colors sit. At the edges of the frame, the mosaic is mirrored about its edge pixels: the missing neighbor at x = -1 is the pixel at x = 1, which recorded the same color as the one at x = -1 would have. Integer means are rounded down, toward negative infinity for signed types. Float means are rounded to the sample type, and f32 means are taken in f64 first.

Bilinear interpolation is fast, and with the parallel feature, on by default, it debayers rows on all cores. Its weakness is fine detail: it averages across edges, so sharp star profiles pick up colored fringes and the image loses a little resolution. Methods that follow edges, such as VNG or AHD, do better there, and the crate doesn’t have them. For stacking many frames, where the fringes average out, bilinear is the usual choice.

Limits

  • Image::debayer works on mono images of every PixelData variant, with dimensions [width, height] or [width, height, 1]. An image with more than one channel, other axes, or fewer than 2 pixels on a side is an ImageError::InvalidDimensions error, and the image is left unchanged.
  • The four RGB patterns are supported. CMY sensors and X-Trans sensors, which use a 6 x 6 tile, aren’t.
  • Image::debayer doesn’t read BAYERPAT, ROWORDER, XBAYROFF or YBAYROFF. It removes BAYERPAT, XBAYROFF and YBAYROFF.

Where next