Stretching for Display
Open a stacked image and show its pixels as they are, and you get a black frame with a few white stars. The data is linear: brightness on the sensor maps straight to numbers, and the faint nebula you spent hours on is a hair above the sky background, in the bottom percent of the range. A stretch is a curve that lifts those faint values into the range a screen shows, while it keeps stars from turning into white blobs.
Stretch::stf picks that curve from the image’s own statistics, so it works
on any frame without tuning:
use celestial_images::formats::image::Image;
use celestial_images::stretch::{StfParams, Stretch};
fn median(mut values: Vec<f64>) -> f64 {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
println!("linear: median {:.4}", median(img.pixels.to_f64_normalized()));
let stretched = img.stf(&StfParams::default())?;
println!("stretched: median {:.4}", median(stretched.pixels.to_f64_normalized()));
let display = stretched.to_u8()?;
let bytes = display.pixels.as_u8().ok_or("not u8")?;
let levels = bytes.iter().map(|&b| f64::from(b)).collect();
println!("8-bit: median {} of 255", median(levels));
display.save("cygnus_display.fits")?;
Ok(())
}
linear: median 0.0078
stretched: median 0.2509
8-bit: median 64 of 255
The median pixel of this image is sky background, at 0.8% of full scale.
Shown linearly, it maps to level 2 of 255, which is black. After the stretch
the background is at a quarter of the range, where it’s a dark gray, and
the nebula above it becomes visible. stf returns a new Image of F64
values in [0, 1] and leaves the original alone, so you can keep measuring the
linear data. to_u8 converts that to 8-bit samples for a texture, a PNG with
the standard-formats feature, or a preview file.
The stretch is for looking at. It changes the pixel values in ways that photometry and astrometry can’t undo, so measure on the linear image.
How the curve is chosen
stf works on each channel by itself and does three things:
- It measures the channel’s median, which is the sky background in nearly every astronomical image, and its noise. The noise is the median absolute deviation (MAD) times 1.4826. For Gaussian noise that equals the standard deviation, and unlike the standard deviation it barely moves when the frame has bright stars and hot pixels.
- It sets a black point
shadow_clipnoise widths below the median, -2.8 by default. Everything darker turns black. That’s mostly noise, so the background stops looking grainy. - It applies a midtones transfer function, a curve that maps the black point
to 0, white to 1, and moves the background to
target_background, 0.25 by default. Values above the background are compressed smoothly, so stars keep some shape.
Both numbers are fields of StfParams. Raise target_background for a brighter
image that shows more faint detail and more noise:
use celestial_images::formats::image::Image;
use celestial_images::stretch::{StfParams, Stretch};
fn median(mut values: Vec<f64>) -> f64 {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
for target_background in [0.15, 0.25, 0.40] {
let params = StfParams {
target_background,
..StfParams::default()
};
let stretched = img.stf(¶ms)?;
println!(
"target {target_background:.2}: median {:.4}",
median(stretched.pixels.to_f64_normalized())
);
}
let clipped = StfParams {
shadow_clip: 0.5,
..StfParams::default()
};
if let Err(e) = img.stf(&clipped) {
println!("{e}");
}
Ok(())
}
target 0.15: median 0.1506
target 0.25: median 0.2509
target 0.40: median 0.4011
Invalid input: STF shadow_clip is a non-positive multiple of MADN (default -2.8), got 0.5
The median lands near the target, not exactly on it, because the curve is
fitted to the background before the black point clips it. A positive
shadow_clip would put the black point above the background and turn most of
the image black, so stf refuses it. A target_background outside [0, 1] is
refused too.
Color images
Each channel of an RGB image gets its own black point and curve. That removes a color cast in the background, such as the orange of light pollution, since every channel’s background lands on the same target. The cost is that the colors of objects aren’t preserved. Use the stretched image to judge framing, focus and gradients, and don’t read star colors from it.
Before you stretch
stf scales the pixels to [0, 1] first with to_f64_normalized, so an
integer image is divided by the range of its type, 65535 for a U16 frame,
and a float image outside [0, 1] is rescaled by its own minimum and maximum.
The statistics leave out NaN pixels and pixels equal to a BLANK card, so
dead regions don’t drag the median down. A channel with no usable pixels at
all is an error.
Debayer a one-shot color frame before you stretch it. Stretched as a mosaic, its red, green and blue sites share one curve, and the result shows the Bayer grid. Debayering covers that step.
Normalize by the noise for detection
mad_normalized uses the same median and noise for a different job. It
subtracts the background from each channel and divides by the noise, so every
value reads as “how many noise widths above the sky”. Values are clipped to
[-5, 100] so a few saturated stars don’t dominate:
use celestial_images::formats::image::Image;
use celestial_images::stretch::Stretch;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
let normalized = img.mad_normalized()?;
let samples = normalized.pixels.as_f32().ok_or("not f32")?;
let above = samples.iter().filter(|&&v| v > 5.0).count();
println!(
"{above} of {} pixels are more than 5 sigma above the background",
samples.len()
);
Ok(())
}
1577 of 262144 pixels are more than 5 sigma above the background
One threshold then means the same thing on a bright frame and a dark one, which is what source detection wants.
Where next
- Debayering: turn a raw color mosaic into RGB before you stretch it.
- Open and Save Images: the
Imagetype these methods work on.