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

Tile Compression

A night of 16-bit frames from a 26-megapixel camera fills tens of gigabytes, and most of each frame is sky background that varies by a few counts. Tile compression shrinks those files without changing a single pixel, and the result is still a FITS file that astropy, cfitsio and most capture and processing programs read. Files compressed this way usually end in .fits.fz, the extension the fpack tool gives them.

Here’s a 1024 x 1024 frame with a sky background near 1000 counts and a few counts of noise, saved four ways:

use celestial_images::fits::compression::CompressionAlgorithm;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;

// A 1024 x 1024 frame: a sky background near 1000 ADU with a little noise.
fn sky_frame() -> Image {
    let mut state = 12345u32;
    let samples: Vec<u16> = (0..1024 * 1024)
        .map(|_| {
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            1000 + (state >> 27) as u16
        })
        .collect();
    Image::new(PixelData::U16(samples), [1024, 1024])
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let frame = sky_frame();
    frame.save("sky.fits")?;
    frame.save_fits_compressed("sky_rice.fits", CompressionAlgorithm::Rice, None)?;
    frame.save_fits_compressed("sky_gzip.fits", CompressionAlgorithm::Gzip, None)?;
    frame.save_fits_compressed("sky_gzip2.fits", CompressionAlgorithm::Gzip2, None)?;

    for name in ["sky.fits", "sky_rice.fits", "sky_gzip.fits", "sky_gzip2.fits"] {
        let bytes = std::fs::metadata(name)?.len();
        let same = Image::open(name)?.pixels.as_u16() == frame.pixels.as_u16();
        println!("{name:<15} {:>9} bytes, pixels match: {same}", bytes);
    }
    Ok(())
}
sky.fits          2102400 bytes, pixels match: true
sky_rice.fits      803520 bytes, pixels match: true
sky_gzip.fits     1056960 bytes, pixels match: true
sky_gzip2.fits     961920 bytes, pixels match: true

Rice brought the frame to 38% of its size, and every pixel came back. The noise in a real frame sets how far it shrinks: each bit of noise per pixel is a bit Rice has to keep. Image::open reads a compressed file like any other, so code that reads your frames doesn’t change. AstroImage compresses with .compressed(algorithm), as Write a New Image shows.

How it works

The compressed file holds an empty primary HDU, then a binary table. The image is cut into tiles, and each tile is compressed on its own into one row of the table. Your header keywords are copied into the table’s header, next to Z keywords such as ZBITPIX and ZNAXIS1 that describe the original image. A reader that understands the convention rebuilds the image. One that doesn’t still sees a valid FITS file with a table in it.

Because tiles are independent, a reader can decompress part of an image without the rest. This crate always decompresses the whole image, so the tile shape matters only to other programs that read your files. By default each tile is one row of the image. Pass a tile size to save_fits_compressed or AstroImage::tile_size for rectangular tiles. Tiles at the right and bottom edges are cut short when the size doesn’t divide the image.

Choose an algorithm

  • Rice (RICE_1) codes the difference between neighboring pixels, which is small in astronomical images. It’s the fastest and usually the smallest for integer data, and it’s what fpack uses by default. It takes 8, 16 and 32-bit integers only.
  • Gzip (GZIP_1) runs deflate on each tile. It takes any pixel type.
  • Gzip2 (GZIP_2) shuffles the bytes of each tile first, putting all the most significant bytes together, then runs deflate. It compresses multi-byte pixels better than Gzip, and it’s the better choice for float images.

For a float image, Rice isn’t an option, and the two GZIP variants are lossless:

use celestial_images::fits::compression::CompressionAlgorithm;
use celestial_images::formats::image::Image;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut stack = Image::open("cygnus.fit")?;
    // Its 4174 HISTORY cards would add 340 KB to every file below
    stack.remove_keyword("HISTORY");
    stack.save("stack.fits")?;
    stack.save_fits_compressed("stack_gzip.fits", CompressionAlgorithm::Gzip, None)?;
    stack.save_fits_compressed("stack_gzip2.fits", CompressionAlgorithm::Gzip2, None)?;

    for name in ["stack.fits", "stack_gzip.fits", "stack_gzip2.fits"] {
        let bytes = std::fs::metadata(name)?.len();
        let same = Image::open(name)?.pixels.as_f32() == stack.pixels.as_f32();
        println!("{name:<17} {bytes:>8} bytes, pixels match: {same}");
    }
    Ok(())
}
stack.fits         1059840 bytes, pixels match: true
stack_gzip.fits     947520 bytes, pixels match: true
stack_gzip2.fits    815040 bytes, pixels match: true

Float data compresses poorly without loss, because the low bits of each value are noise. fpack gets much smaller float files by quantizing them: it rounds each value to a fraction of the noise and Rice-codes the integers. The crate reads those files, with or without dithering, but doesn’t write them, since quantization changes your pixel values. When you need smaller float files, the tradeoff is yours to make with fpack.

Limits

The writer refuses combinations it can’t store and tells you what to use instead. The reader reports codecs it doesn’t support:

use celestial_images::fits::compression::CompressionAlgorithm;
use celestial_images::formats::image::Image;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let stack = Image::open("cygnus.fit")?;
    if let Err(e) = stack.save_fits_compressed("stack_rice.fits", CompressionAlgorithm::Rice, None) {
        println!("{e}");
    }
    if let Err(e) = Image::open("hcompress_i16.fits.fz") {
        println!("{e}");
    }
    Ok(())
}
FITS error: Unsupported compression: RICE_1 tiles cannot hold floating-point pixels without lossy quantization, which is not written; use GZIP_1 or GZIP_2
FITS error: Unsupported compression: HCOMPRESS_1 tiles cannot be read
CodecReadWrite
RICE_1yes8, 16 and 32-bit integers
GZIP_1, GZIP_2yesevery type except U64
NOCOMPRESSyesno
Quantized floatsyesno
HCOMPRESS_1, PLIO_1nono

Unsigned 64-bit images aren’t written compressed with any codec, because other FITS readers don’t decode those tiles to the same values. Save them uncompressed.

Image::open decompresses only the first image in a file. A file with several compressed images, such as mef.fits.fz in FITS Files, gives you the first one through Image, and the rest through FitsFile::read_hdu_with_data.

Image::save picks the format from the extension, and .fz isn’t one it knows. Save compressed files with save_fits_compressed, which takes any path. Image::open recognizes a .fits.fz file from its first bytes.

Where next

  • FITS Files: HDUs, header keywords and how BZERO maps to pixel types.
  • XISF Files: XISF compresses its data blocks with LZ4 or zlib.