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

Open and Save Images

Your camera writes 16-bit FITS. Your stacking program writes 32-bit float XISF. A friend sends a tile-compressed .fits.fz. You want the pixels and the header keywords from each of them without writing three readers. Image::open reads any of these files into the same type:

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let img = Image::open("cygnus.fit")?;

    println!("{} x {}, {} channel(s)", img.width(), img.height(), img.channels());
    println!("OBJECT   = {:?}", img.get("OBJECT").as_str());
    println!("FOCALLEN = {:?}", img.get("FOCALLEN").as_f64());
    println!("EXPTIME  = {:?}", img.get("EXPTIME").as_f64());

    match &img.pixels {
        PixelData::F32(samples) => println!("{} f32 samples", samples.len()),
        PixelData::U16(samples) => println!("{} u16 samples", samples.len()),
        other => println!("{} samples, BITPIX {:?}", other.len(), other.bitpix()),
    }
    Ok(())
}
512 x 512, 1 channel(s)
OBJECT   = Some("Cygnus Wall")
FOCALLEN = Some(675.0)
EXPTIME  = None
262144 f32 samples

cygnus.fit is in celestial-images/test_data: a 512 x 512 crop of a stacked image, stored as 32-bit floats. Image::open picks the format from the file extension: .fits, .fit and .fts are FITS, and .xisf is XISF. For any other extension it reads the first bytes of the file and decides from those.

What an Image holds

An Image has four public fields:

  • pixels, a PixelData with one variant per sample type, from U8 to F64.
  • dimensions, the axis lengths in FITS order: [width, height] for a mono image and [width, height, 3] for RGB.
  • keywords, the header cards as a Vec<Keyword>. An XISF file stores FITS keywords too, so both formats fill this field.
  • xisf_properties, the XISF properties of the image. It’s empty for FITS.

The pixel type follows the file. A 16-bit camera frame comes back as U16 and a float stack as F32, with no conversion, so the values you read are the values the camera or the stacking program wrote. Each PixelData variant has an accessor (as_u16, as_f32 and so on) that returns None for the other variants. FITS Files explains which variant each FITS BITPIX and BZERO combination produces.

Read header keywords

img.get(name) returns a Field, which converts the card’s value on request:

MethodReturns Some for
as_strstring cards, with trailing spaces removed
as_f64real and integer cards, so CRPIX1 = 800 reads as 800.0
as_i64integer cards only
as_boollogical cards (T or F)
existstrue when the card is present, whatever its value

A missing keyword is not an error. Every method returns None, as EXPTIME did above, so you decide what a missing value means for your program.

When a header repeats a name, get returns the first card and get_last returns the last one. FITS readers apply the last value of a repeated card, so use get_last for anything that changes how you interpret the pixels, such as WCS keywords. Pixels and Sky Coordinates shows a KeywordProvider built on get_last that turns an image header into a WCS.

Change keywords and save in another format

set_keyword replaces every card of the same name with one new card, and remove_keyword deletes them. HISTORY and COMMENT cards are appended instead, since a header holds many of each. save picks the format from the extension, the same way open does:

use celestial_images::fits::header::keywords::Keyword;
use celestial_images::formats::image::Image;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut img = Image::open("cygnus.fit")?;
    img.set_keyword(Keyword::string("OBSERVER", "A. Observer"));
    img.set_keyword(Keyword::history("Converted to XISF"));
    img.remove_keyword("ROWORDER");
    img.save("cygnus.xisf")?;

    let copy = Image::open("cygnus.xisf")?;
    println!("OBSERVER = {:?}", copy.get("OBSERVER").as_str());
    println!("ROWORDER = {:?}", copy.get("ROWORDER").as_str());
    println!("same pixels: {}", copy.pixels.as_f32() == img.pixels.as_f32());
    Ok(())
}
OBSERVER = Some("A. Observer")
ROWORDER = None
same pixels: true

save writes the whole file to memory first and then replaces the file on disk, so a save that fails leaves an existing file as it was.

Converting between formats keeps every pixel value, but XISF has no signed integer samples. A FITS file with BITPIX = 16 and no BZERO holds i16 samples, and saving it as XISF fails until you convert the samples:

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A bias frame stored as BITPIX = 16 with no BZERO, so its samples are i16
    let mut bias = Image::new(PixelData::I16(vec![-12, 0, 7, 3]), [2, 2]);

    if let Err(e) = bias.save("bias.xisf") {
        println!("{e}");
    }

    bias.pixels = bias.pixels.signed_to_float()?;
    bias.save("bias.xisf")?;
    println!("{:?}", Image::open("bias.xisf")?.pixels);
    Ok(())
}
XISF error: Unsupported sample format: Int16 pixels: XISF 1.0 has no signed integer sample format; convert them with PixelData::signed_to_offset_unsigned or PixelData::signed_to_float
F32([-12.0, 0.0, 7.0, 3.0])

signed_to_float keeps the values. signed_to_offset_unsigned adds 32768 so the samples fit u16, which keeps the file the same size but shifts every value.

Color images

An RGB Image holds its samples interleaved: red, green and blue of the first pixel, then of the second, and so on. That’s the order a display or a texture upload wants. FITS stores the three colors as separate planes, all the red samples first, and XISF usually does the same. open and save reorder the samples for you:

use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Two pixels, an orange one and a blue one, stored R G B R G B
    let img = Image::new(PixelData::U8(vec![255, 128, 0, 0, 64, 255]), [2, 1, 3]);
    img.save("two.fits")?;

    let (_, on_disk) = FitsFile::open("two.fits")?.read_hdu_with_data::<u8>(0)?;
    println!("in the file: {on_disk:?}");

    let back = Image::open("two.fits")?;
    println!("in memory:   {:?}, {:?}", back.pixels, back.kind());
    Ok(())
}
in the file: [255, 0, 128, 64, 0, 255]
in memory:   U8([255, 128, 0, 0, 64, 255]), Rgb

Only an image with exactly three axes and three planes counts as RGB. A data cube with any other number of planes keeps its planes one after another. interleaved_to_planar and planar_to_interleaved convert an RGB image in place when you need the other order.

Scale pixels to [0, 1]

Display code and many algorithms want floats between 0 and 1. There are two ways to get them, and they answer different questions:

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

fn main() {
    let mut frame = Image::new(PixelData::U16(vec![1000, 1010, 1040, 2000]), [4]);

    println!("{:?}", frame.pixels.to_f32());
    println!("{:?}", frame.pixels.to_f32_normalized());

    frame.normalize();
    println!("{:?}", frame.pixels);
}
[1000.0, 1010.0, 1040.0, 2000.0]
[0.015259022, 0.015411613, 0.015869383, 0.030518044]
F64([0.0, 0.01, 0.04, 1.0])
  • to_f32 converts the values and doesn’t scale them.
  • to_f32_normalized divides by the range of the type, 65535 for u16. A value means the same thing in every image of that type, which is what you want when you compare frames. Float images already in [0, 1] stay as they are, and 64-bit integers and other float images are scaled by their own minimum and maximum.
  • normalize scales by the image’s own minimum and maximum, so the faintest pixel becomes 0 and the brightest 1. That’s useful for a quick look, but one hot pixel sets the maximum, and two frames scaled this way can’t be compared. NaN and infinite samples don’t count toward the minimum and maximum, and keep their value.

normalize replaces the pixels: integer images become F64, and float images keep their type. For a display stretch that ignores hot pixels, see Stretching for Display.

What Image::open reads

Image::open returns one image per file. For FITS, that’s the first HDU that holds image data, which is what most programs mean by “the image”. A tile-compressed image counts, so a .fits.fz file opens like any other. For XISF, it’s the first Image element. To reach the other HDUs of a FITS file, use FitsFile as FITS Files shows. To reach the other images of an XISF file, use XisfFile as XISF Files shows.

With the standard-formats feature, Image also opens and saves PNG and TIFF files. They have no header keywords, so keywords comes back empty.

Where next