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

FITS Files

Image::open covers the common case: one image and its header. Some files hold more than that. A survey frame can carry a science image, a variance map and a mask. A .fits.fz file keeps its image in a binary table. A processing pipeline might write a catalog table after the image. When you need to see everything in a file, or check exactly what’s stored, you work with FitsFile.

A file is a chain of HDUs

A FITS file is a sequence of header and data units (HDUs). Each one has a header of 80-character cards and an optional block of data. The first is the primary HDU, and the rest are extensions: images, ASCII tables or binary tables. FitsFile scans the headers when it opens the file and reads data only when you ask for it, so opening a large file is fast.

This walks the HDUs of mef.fits.fz, one of the test files in celestial-images/test_data/compressed. It holds two tile-compressed images after an empty primary HDU:

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut fits = FitsFile::open("mef.fits.fz")?;
    for index in 0..fits.num_hdus() {
        let hdu = fits.read_hdu(index)?;
        let header = hdu.header();
        let name = header.get("EXTNAME").as_str().unwrap_or("-");
        let checksums = fits.validate_hdu_checksum(index)?;
        println!(
            "HDU {index}: {:<16} {name:<4} checksums valid: {}",
            format!("{:?}", hdu.logical_type()),
            checksums.all_valid()
        );
    }

    let img = Image::open("mef.fits.fz")?;
    println!("Image::open read {}x{}, EXTNAME {:?}", img.width(), img.height(), img.get("EXTNAME").as_str());
    Ok(())
}
HDU 0: Image            -    checksums valid: true
HDU 1: CompressedImage  SCI  checksums valid: true
HDU 2: CompressedImage  FLT  checksums valid: true
Image::open read 23x17, EXTNAME Some("SCI")

hdu_type() reports what the file stores, so HDUs 1 and 2 are BinaryTable. logical_type() reports what the HDU means, so a binary table that holds a compressed image reports CompressedImage. Image::open returned the first HDU with pixels, the SCI image. The empty primary HDU has no pixels, so it was skipped.

get_image_info and read_hdu_with_data reach the images after the first. For a compressed HDU they read ZNAXISn and ZBITPIX, and read_hdu_with_data decompresses the tiles:

use celestial_images::fits::io::reader::FitsFile;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut fits = FitsFile::open("mef.fits.fz")?;
    let (dimensions, bitpix) = fits.get_image_info(2)?;
    println!("FLT: {dimensions:?} {bitpix:?}");
    let (_, flat) = fits.read_hdu_with_data::<f32>(2)?;
    println!("{} samples, first {:?}", flat.len(), &flat[..3]);
    Ok(())
}
FLT: [23, 17] F32
391 samples, first [NaN, 937.50757, 1024.8617]

validate_hdu_checksum recomputes the DATASUM and CHECKSUM cards of one HDU. Each field of the result is None when the header has no such card, Some(true) when it matches and Some(false) when it doesn’t. A changed data unit fails both cards, since CHECKSUM covers the data too.

If the scan hits a malformed header partway through the file, open still succeeds. The HDUs before the problem stay readable, and scan_error() returns what went wrong. That way one damaged extension doesn’t cost you the image in front of it.

Headers and keywords

get_header(index) returns a Header, and get and get_last on it work as they do on Image. Each card is a Keyword with three public fields: name, value and comment. value is None for commentary cards such as HISTORY and COMMENT, whose text is in comment. The value types are Logical, Integer, Real, String and Complex.

Two conventions extend the 80-character card, and the crate reads and writes both:

  • Long strings. A string value longer than one card continues on CONTINUE cards. You get the whole string back as one value.
  • Long names. A keyword name longer than 8 characters, or one with characters FITS doesn’t allow, is stored as HIERARCH name = value. A lookup of "ESO DET DIT" finds HIERARCH ESO DET DIT, and set_keyword with a long name writes the HIERARCH form.

Data types, BZERO and BSCALE

FITS stores integers as signed values only, with one exception for 8-bit data. A camera’s unsigned 16-bit frame can’t be stored as it is, so writers subtract 32768 from every sample and record BZERO = 32768. A reader adds it back. Image does this in both directions:

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>> {
    // A 16-bit camera frame: unsigned samples from 0 to 65535
    let frame = Image::new(PixelData::U16(vec![0, 1000, 32768, 65535]), [2, 2]);
    frame.save("frame.fits")?;

    let mut fits = FitsFile::open("frame.fits")?;
    let header = fits.get_header(0)?;
    println!("BITPIX = {:?}", header.get("BITPIX").as_i64());
    println!("BZERO  = {:?}", header.get("BZERO").as_f64());
    let (_, stored) = fits.read_hdu_with_data::<i16>(0)?;
    println!("stored:    {stored:?}");

    let back = Image::open("frame.fits")?;
    println!("Image has: {:?}", back.pixels);
    Ok(())
}
BITPIX = Some(16)
BZERO  = Some(32768.0)
stored:    [-32768, -31768, 0, 32767]
Image has: U16([0, 1000, 32768, 65535])

read_hdu_with_data::<T> returns the values as stored, with no scaling. The type parameter must match BITPIX, or ZBITPIX for a compressed image: u8 for 8, i16 for 16, i32 for 32, i64 for 64, f32 for -32 and f64 for -64. A type that doesn’t match is an error. It’s the right tool when you want to see exactly what’s in the file. Image::open applies the scaling and picks the PixelData variant from BITPIX, BZERO and BSCALE:

BITPIXScaling in the headerPixelData
8noneU8
8BZERO = -128I8
16noneI16
16BZERO = 32768U16
32noneI32
32BZERO = 2147483648U32
64noneI64
64BZERO = 9223372036854775808U64
-32noneF32
-64noneF64
anyany other BZERO or BSCALEF64

“None” means BSCALE = 1 and BZERO = 0, or no scaling cards at all. The offsets in the table each shift a signed type onto the unsigned type of the same width, so the samples keep their size in memory.

Any other scaling turns the stored values into physical values, BZERO + BSCALE × stored, and those need a float type:

use celestial_images::fits::header::keywords::Keyword;
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::astro_image::AstroImage;
use celestial_images::formats::image::Image;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Stored bytes whose physical value is BZERO + BSCALE * stored
    let stored = vec![0u8, 1, 2, 255];
    AstroImage::new(&stored, [4])
        .keyword(Keyword::real("BSCALE", 0.5))
        .keyword(Keyword::real("BZERO", -10.0))
        .write_fits("scaled.fits")?;

    let img = Image::open("scaled.fits")?;
    println!("{:?}", img.pixels);
    println!("BSCALE card kept: {}", img.get("BSCALE").exists());

    img.save("resaved.fits")?;
    let mut fits = FitsFile::open("resaved.fits")?;
    println!("resaved BITPIX = {:?}", fits.get_header(0)?.get("BITPIX").as_i64());
    Ok(())
}
F64([-10.0, -9.5, -9.0, 117.5])
BSCALE card kept: false
resaved BITPIX = Some(-64)

The Image drops BSCALE and BZERO from its keywords, because its pixels already hold physical values. Keeping the cards would apply the scaling a second time on the next save. The cost shows when you save: the file is written as 64-bit floats, eight times the size of the 8-bit original. To keep the original encoding, write the stored values with AstroImage and set the scaling cards yourself.

Undefined pixels and BLANK

An integer image marks pixels with no measurement, such as dead columns or saturated regions, by setting them to the value of the BLANK card. When Image::open scales such an image to F64, those pixels become NaN. When it keeps an integer type, they keep their stored value and the BLANK card stays in keywords, converted to the in-memory value. normalize, stf and mad_normalized treat them as NaN, so a BLANK of -32768 doesn’t become the black point of your stretch. Float images mark undefined pixels with NaN and have no BLANK card.

Tables and random groups

read_hdu returns Hdu::AsciiTable or Hdu::BinaryTable for table extensions. Both table types have all_column_info, column_by_name, get_row, get_column_values and iter_rows, which return cells as TableValue, with TSCALn and TZEROn applied. Binary tables can hold variable-length arrays, and the crate reads them from the heap. These methods take a reader as an argument: open the same file with std::fs::File::open and pass it in. A primary HDU of random groups, an old format from radio interferometry, comes back as Hdu::RandomGroups, and read_groups returns its groups.

What’s supported

FeatureReadWrite
Primary and IMAGE extension HDUsyesprimary HDU only
Several image HDUs in one fileyesno
ASCII and binary tablesyesno
Random groupsyesno
CHECKSUM and DATASUMyesyes
CONTINUE long strings, HIERARCHyesyes
Tile compression: Rice, GZIP 1 and 2yesyes
Tile compression: HCOMPRESS, PLIOnono

The writers produce one image per file: a primary HDU, or an empty primary HDU followed by one compressed image. Image::open returns only the first image HDU. FitsFile::read_hdu_with_data reads any image HDU, compressed or not, as stored values without BZERO or BSCALE applied. Tile Compression covers what each codec supports.

Where next