XISF Files
XISF (Extensible Image Serialization Format) is the format many astrophotography processing tools save stacks and processed images in. A file starts with an XML header that describes each image, followed by the pixel data in binary blocks. The XML can hold FITS keywords, so a header read from FITS carries over, and typed properties: named values such as strings, numbers, vectors and matrices, which FITS cards can’t express.
Pleiades Astrophoto created XISF for PixInsight, and publishes the XISF 1.0 specification that the reader and writer follow.
Image::open and Image::save read and write XISF the same way they do FITS,
and Open and Save Images covers that path. This page is
about XisfFile and XisfWriter, which you need for properties, compression,
checksums and files with more than one image.
Write and read a file
XisfWriter takes images, keywords and properties, and writes them when you
call write:
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::formats::image::Image;
use celestial_images::xisf::header::compression::XisfCompression;
use celestial_images::xisf::header::property::XisfProperty;
use celestial_images::xisf::reader::XisfFile;
use celestial_images::xisf::writer::XisfWriter;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A 4 x 2 RGB image, planar: all red samples, then green, then blue
let planar: Vec<f32> = [[0.1f32; 8], [0.2; 8], [0.3; 8]].concat();
let mut writer = XisfWriter::create("m42.xisf")?
.compression(XisfCompression::Lz4)
.sha1_checksums(true);
writer.add_image(&planar, 4, 2, 3)?;
writer.add_keyword(Keyword::string("OBJECT", "M42"));
writer.add_keyword(Keyword::real("EXPTIME", 120.0).with_comment("seconds"));
writer.add_property(XisfProperty::string(
"Observation:Object:Name",
"Orion Nebula",
));
writer.add_property(XisfProperty::float64("Instrument:ExposureTime", 120.0));
writer.write()?;
let mut xisf = XisfFile::open("m42.xisf")?;
let info = xisf.image_info(0).ok_or("no image")?;
println!(
"{:?} {:?} {:?}",
info.geometry, info.sample_format, info.color_space
);
println!("EXPTIME = {:?}", xisf.get("EXPTIME").as_f64());
for property in xisf.properties(0)? {
println!("{} = {:?}", property.id, property.value);
}
let samples = xisf.read_image_data_typed::<f32>(0)?;
println!("XisfFile: {:?}", &samples[..3]);
let img = Image::open("m42.xisf")?;
println!(
"Image: {:?}",
&img.pixels.as_f32().ok_or("not f32")?[..3]
);
Ok(())
}
[4, 2, 3] Float32 Rgb
EXPTIME = Some(120.0)
Observation:Object:Name = String("Orion Nebula")
Instrument:ExposureTime = Float64(120.0)
XisfFile: [0.1, 0.1, 0.1]
Image: [0.1, 0.2, 0.3]
The last two lines show the one difference between the two readers.
XisfFile returns samples planar, the way the writer took them, so the first
three are all red. Image interleaves RGB, so its first three samples are the
red, green and blue of the first pixel.
add_image takes the width, height and channel count, and sets the color
space from the channel count: three channels are RGB and anything else is
gray. read_image_data_typed::<T> must ask for the stored sample type, and
returns an error naming both types when it doesn’t. read_image_data_raw
returns the little-endian bytes instead.
Keywords and properties
Keywords and properties do overlapping jobs. Keywords are FITS cards, so any
program that reads FITS headers understands them, and they survive a
conversion to FITS. Properties have types and namespaced names such as
Instrument:ExposureTime, and their values can be vectors and matrices. Use
keywords for anything a FITS reader should see, and properties for values that
have no FITS form.
On the reading side, get and keywords() return the keywords of the first
image, and image_keywords(index) those of any other. properties(index)
returns the properties of one image, with vector and matrix values read from
their data blocks. On the writing side, keywords and properties attach to the
first image. set_keyword replaces a keyword of the same name, and
add_keyword appends one.
The reader decodes six property types into values: String, Boolean,
Int32, Float64, F64Vector and F64Matrix. The other types in the
specification are kept without decoding:
- A scalar, complex or
TimePointproperty, such asUInt16,Float32orComplex64, is anXisfPropertyValue::Otherthat holds its type name and the text of itsvalueattribute. - A vector or matrix of another element type, such as
I32VectororF32Matrix, is anXisfPropertyValue::OtherArraythat holds its type name, its dimensions and its elements as little-endian bytes.
The writer writes both back as they were read, and refuses a type name the specification doesn’t define or array data that doesn’t match its dimensions. Data blocks of properties may be compressed with zlib or LZ4, as image blocks are.
A data block that lies past the end of the file, fails its checksum or
doesn’t decompress makes properties return an error, because the header
says the data exists. A property the reader can’t interpret is left out of
the list without an error: one with a type the specification doesn’t define,
malformed attributes, a block in another file or a zstd block.
Data types and compression
XISF stores unsigned integers and floats: UInt8, UInt16, UInt32,
UInt64, Float32 and Float64. The writer takes slices of the matching
Rust types, u8 through f64. There are no signed integer samples, so an
i16 image from FITS needs converting first, as Open and Save
Images shows.
compression sets how the writer stores each data block: Lz4, Lz4Hc or
Zlib. LZ4 is fast to read and write, and zlib gives smaller files that take
longer to read. Lz4Hc writes the same blocks as Lz4, labeled as LZ4HC,
because the LZ4 encoder the crate uses has no high-compression mode. A block
that doesn’t get smaller is stored uncompressed. The reader also decodes
byte-shuffled blocks, which other programs write, but Zstd is not supported
in either direction.
Image::save writes XISF without compression. Use XisfWriter when you want
it.
sha1_checksums(true) adds a SHA-1 digest to every data block. The reader
checks SHA-1, SHA-256 and SHA-512 digests when it reads a block, and a block
that fails is an error.
The astrometric solution
A plate-solved XISF image can describe its WCS twice: as the FITS WCS
keywords, and as a set of astrometric solution properties with ids that start
with PCL:AstrometricSolution:. The crate keeps the two in agreement in both
directions.
When you write an image with a WCS, through AstroImage with .wcs() or
Image::save on an image with WCS keywords, the writer adds the solution
properties derived from the keywords:
use celestial_images::formats::astro_image::AstroImage;
use celestial_images::xisf::header::property::XisfPropertyValue;
use celestial_images::xisf::reader::XisfFile;
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wcs = WcsBuilder::new()
.crpix(800.5, 600.5)
.crval(148.8882, 69.0653)
.cd_matrix([[-3.3333e-4, 0.0], [0.0, 3.3333e-4]])
.projection(Projection::tan())
.build()?;
let pixels = vec![0.0f32; 1600 * 1200];
AstroImage::new(&pixels, [1600, 1200])
.wcs(&wcs)
.write_to("m81.xisf")?;
let mut xisf = XisfFile::open("m81.xisf")?;
println!("CRPIX1 keyword = {:?}", xisf.get("CRPIX1").as_f64());
for property in xisf.properties(0)? {
let id = property.id.trim_start_matches("PCL:AstrometricSolution:");
match property.value {
XisfPropertyValue::String(text) => println!("{id} = {text}"),
XisfPropertyValue::F64Vector(v) => println!("{id} = {v:?}"),
XisfPropertyValue::F64Matrix { data, .. } => println!("{id} = {data:?}"),
other => println!("{id} = {other:?}"),
}
}
Ok(())
}
CRPIX1 keyword = Some(800.5)
ProjectionSystem = Gnomonic
ReferenceCelestialCoordinates = [148.8882, 69.0653]
ReferenceImageCoordinates = [800.0, 600.0]
LinearTransformationMatrix = [-0.00033333, 0.0, 0.0, 0.00033333]
ReferenceNativeCoordinates = [0.0, 90.0]
CelestialPoleNativeCoordinates = [180.0, 69.0653]
The properties map onto FITS WCS keywords this way:
| Property | FITS keywords |
|---|---|
ProjectionSystem | the projection code in CTYPEi |
ReferenceCelestialCoordinates | CRVAL1, CRVAL2 |
ReferenceImageCoordinates | CRPIX1 - 0.5, CRPIX2 - 0.5 |
LinearTransformationMatrix | CD1_1, CD1_2, CD2_1, CD2_2 |
ReferenceNativeCoordinates | PV1_1, PV1_2 |
CelestialPoleNativeCoordinates | LONPOLE, LATPOLE |
ReferenceImageCoordinates is half a pixel less than CRPIX because the two
formats count pixels differently. FITS puts the center of the first pixel at
1, and XISF puts it at 0.5. The native reference and pole come from the
projection, so a cylindrical projection such as CAR gets (0, 0) where the
zenithal TAN above gets (0, 90).
Reading works the other way. When an XISF file has the solution properties
and no WCS keywords, Image::open turns the properties into keywords, so the
WCS code in Pixels and Sky Coordinates and the
plate solver read it the same as a FITS header:
use celestial_images::formats::image::Image;
use celestial_images::xisf::header::property::XisfProperty;
use celestial_images::xisf::writer::XisfWriter;
const SOLUTION: &str = "PCL:AstrometricSolution";
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A file whose solution is stored only as properties
let mut writer = XisfWriter::create("solved.xisf")?;
writer.add_image(&vec![0u16; 1600 * 1200], 1600, 1200, 1)?;
writer.add_properties([
XisfProperty::string(format!("{SOLUTION}:ProjectionSystem"), "Gnomonic"),
XisfProperty::f64_vector(
format!("{SOLUTION}:ReferenceCelestialCoordinates"),
vec![148.8882, 69.0653],
),
XisfProperty::f64_vector(
format!("{SOLUTION}:ReferenceImageCoordinates"),
vec![800.0, 600.0],
),
XisfProperty::f64_matrix(
format!("{SOLUTION}:LinearTransformationMatrix"),
2,
2,
vec![-3.3333e-4, 0.0, 0.0, 3.3333e-4],
),
]);
writer.write()?;
let img = Image::open("solved.xisf")?;
for keyword in &img.keywords {
println!("{:<6} = {:?}", keyword.name, keyword.value);
}
println!("properties left: {}", img.xisf_properties.len());
Ok(())
}
CTYPE1 = Some(String("RA---TAN"))
CTYPE2 = Some(String("DEC--TAN"))
CRPIX1 = Some(Real(800.5))
CRPIX2 = Some(Real(600.5))
CRVAL1 = Some(Real(148.8882))
CRVAL2 = Some(Real(69.0653))
CD1_1 = Some(Real(-0.00033333))
CD1_2 = Some(Real(0.0))
CD2_1 = Some(Real(0.0))
CD2_2 = Some(Real(0.00033333))
properties left: 0
The Image keeps one copy of the solution, as keywords, and drops the
properties, so an edit to the keywords can’t leave a stale solution behind.
The next save writes fresh properties from the keywords. When a file has
both, the keywords win.
The mapping has limits, set by what the properties can say:
- The XISF specification names seven projections:
TAN,SIN,STG,ZEA,CAR,MERandAIT. A WCS with any other projection, or with projection parameters, is written as keywords only. - The properties hold equatorial coordinates in the ICRS. A header with
RADESYS = 'FK5'at equinox 2000 is accepted, since the two frames differ by tens of milliarcseconds. Other systems, such as galactic coordinates or FK4, are written as keywords only, so they aren’t mislabeled. - SIP and TPV distortion terms have no property form. The properties describe the linear solution, and the keywords keep the distortion.
Distortion: SIP and TPV explains the distortion keywords, and Projections the projection codes.
Limits
- One image through
Image.Image::openreads the first image of the file. UseXisfFilewithnum_imagesand an index for the rest. The writer attaches keywords and properties to the first image only. - Monolithic files only. A file whose header points to data in other files, or a header stored on its own, can’t be read.
- Float bounds. XISF records a range,
bounds, for each image. For float images,add_imageandImage::saverecord the minimum and maximum sample value, which some programs use to rescale the image when they open it. If your floats are already in [0, 1] and you want them shown that way, write withXisfWriter::add_image_with_bounds(..., (0.0, 1.0)). The reader ignoresboundsand returns the stored values. - Properties on a round trip.
Image::openkeeps every property it can interpret, andImage::savewrites them back. A property left out of the list, as described under Keywords and properties, is lost.
Where next
- Open and Save Images: the format-agnostic
Imagetype. - Pixels and Sky Coordinates: read the WCS from an
Image, whichever format it came from. - Hints and Image Metadata: what the plate solver reads from an image header.