ImageHDU¶
Uncompressed image HDU. Subclass of rustfits.HDU.
- class rustfits.ImageHDU¶
Bases:
HDU- __getitem__(key, /)¶
Return self[key].
- __len__()¶
Return len(self).
- __setitem__(key, value, /)¶
Set self[key] to value.
- add_checksum()¶
Compute and store both
DATASUMandCHECKSUMcards.Same semantics as
TableHDU.add_checksum(). This is the call most users want — writes both cards atomically.
- add_datasum()¶
Compute and store the
DATASUMchecksum card.Same semantics as
TableHDU.add_datasum(): manual refresh, no auto-update on mutation. Call afterwrite()/extend()/__setitem__.
- bitpix¶
Raw FITS
BITPIXvalue (e.g.8,16,-32,-64).Useful for round-trip / standards-level inspection; everyday code should prefer
dtype, which reflects scaling.
- dtype¶
The numpy dtype
read()would return.Reflects the default-read (
scale=True) dtype: BITPIX 8/16/32/64 →u1/i2/i4/i8(or the matching unsigned for the unsigned-int trick); BITPIX -32 / -64 →f4/f8.
- extend(data, start=None)¶
Grow the slow axis of the image and write new pixels into it.
The slow axis is numpy axis 0 (FITS
NAXISnwherenis the highest). Grows the on-disk data section to fit the combined shape, writes the new pixels, and bumps the correspondingNAXISncard in the header.A first
extendon an empty HDU created withcreate_image_hdu(dtype, (0, ...))is the natural way to fill a streaming-write image: the0 -> Ngrowth uses the same machinery as growing a non-empty image.For HDUs that are not the last on disk, the file tail is shifted forward and every later HDU’s offsets are bumped in lockstep — previously-issued handles remain valid.
- Parameters:
data (numpy.ndarray or numpy.ma.MaskedArray) – New pixels. Dtype and inner-axis shape must match
hdu.shape[1:]; the slow axis can be any size. Same dtype rules aswrite()(BITPIX-native, scaled, orf8for general scaling; MaskedArray accepted).start (list of int, optional) – Per-axis starting offset for the write. Default
Noneappends at the current slow-axis end (hdu.shape[0]); explicitstart[0]can overlap existing rows for in-place rewrites.
Notes
Validate-then-mutate: dtype/shape errors leave the file untouched. Mid-write I/O failures taint the file (close + reopen to recover).
- extending()¶
No-op batched-extend context manager.
Uncompressed image extends already go straight to disk (there’s no partial-trailing-tile re-encode tax to amortize), so this context does nothing on enter or exit — it exists for API symmetry with
CompressedImageHDU.extending(), where the context does meaningful work. Generic code that iterates HDUs of mixed compressed / uncompressed types can therefore use the pattern uniformly:for hdu in fits: with hdu.extending(): for batch in batches: hdu.extend(batch)
- extname¶
EXTNAMEheader value, orNonewhen the keyword is absent.EXTNAME is the user-visible name of the HDU (e.g.
'SCI','CATALOG'). Combined withextverit’s the standard way to identify HDUs without relying on position-by-index.
- extver¶
EXTVERheader value, defaulting to1when absent.Per the FITS standard, multiple HDUs may share an
EXTNAMEand are distinguished byEXTVER. Returns1rather thanNonefor the absent case so callers can compare/select without handlingOptional[int].
- has_data¶
Trueiff this HDU has a non-empty data section.Works uniformly across image and table HDUs: the test is
NAXIS > 0AND everyNAXISn > 0. For images that means “at least one pixel”; for tables it means “at least one row of at least one column”.Useful for picking the first HDU worth reading in a file (primary HDUs are often empty stubs):
hdu = next(h for h in fits if h.has_data) arr = hdu.read()
Edge case: a VLA table with
NAXIS2=0butPCOUNT>0(heap-only) returnsFalse— no main rows means there’s nothing to interpret the heap through, which is the right answer for the “is this HDU worth reading?” question.
- header¶
The HDU’s
FITSHeader.Returns a live view of this HDU’s header cards. Mutations via the header object (
__setitem__,__delitem__,update,add_comment,add_history,add_blank) write through to disk immediately, following the disk-write-before-commit ordering documented onFITSHeader.Reads are cheap; mutations may grow the reserved header blocks in place if the new card list exceeds the current allotment.
- index¶
The HDU’s 0-based position in its file.
Stable for the lifetime of the
FITSobject — even when an earlier HDU grows and shifts this HDU’s bytes forward, the index is unchanged because the HDU is still at the same position in the file’s HDU list.
- ndim¶
Number of image axes (
NAXIS).0for primary HDUs with no data section. Same aslen(hdu.shape).
- read(*, scale=True, mask_blank=False)¶
Read the image into a numpy array.
- Parameters:
scale (bool, optional) – If
True(default), applyBSCALE/BZEROscaling. For files with the unsigned-int trick (BITPIX=16/32/64+BZERO=2**(n-1), orBITPIX=8+BZERO=-128), returns the matching unsigned (ori1) dtype with no precision loss. For general scaling, returnsf8. IfFalse, returns raw stored values in the BITPIX-native dtype.mask_blank (bool, optional) – If
True, return anumpy.ma.MaskedArraywithTrueat pixels whose stored value matches the header’sBLANKkeyword. Comparison is in stored (pre-scaling) space per the FITS spec. Only valid for integerBITPIX; float BITPIX rejects because the spec forbids BLANK on floats (NaN serves that role). WhenBLANKis absent, returns aMaskedArraywith an all-False mask — return type stays consistent. DefaultFalse.
- Returns:
Array of shape
hdu.shape.- Return type:
- Raises:
ValueError –
mask_blank=Trueon a float-BITPIX image.
- shape¶
Image dimensions in numpy axis order (slowest first).
Returned as a tuple so the value is immutable from the caller side. Primary HDUs with
NAXIS=0return().
- size¶
Total pixel count (product of all
NAXISn).Returns
0whenNAXIS=0(empty shape). Without the special case the empty-product identity would give1, which is wrong for “no data”.
- unit¶
BUNITheader value (e.g.'Jy','counts/s'), orNonewhen unset. Informational only; nothing in the read or write path consumes it.
- verify_checksum()¶
Verify the stored
CHECKSUMover the full HDU.Returns
True/False/None(Nonemeans the card is absent).
- verify_datasum()¶
Verify the stored
DATASUMagainst the current data.Returns
True/False/None(Nonemeans the card is absent).
- write(data, start=None)¶
Write pixel data to the HDU’s data section.
- Parameters:
data (numpy.ndarray or numpy.ma.MaskedArray) – Image pixels. Shape must match
hdu.shape(or, whenstart=is set, fit withinhdu.shapefromstart). Dtype must be the HDU’s BITPIX-native type, the matching scaled dtype (unsigned-int trick), orf8(which goes through general reverse-scaling into the stored dtype, with rint + bounds check for integer BITPIX).MaskedArrayinput auto-fills masked positions with the sentinel fromBLANK(integer dtypes) or NaN (float dtypes).start (list of int, optional) – Per-axis starting offset (numpy order) for a partial write. Must be
len(hdu.shape)long and non-negative. DefaultNonewrites the entire image starting at the origin.
- Raises:
ValueError – Shape mismatch, dtype incompatibility, NaN/Inf on integer BITPIX with general scaling, out-of-range value on integer BITPIX, or missing BLANK on MaskedArray integer input.
See also
extendGrow the slow axis to fit larger data.
__setitem__Slice-style partial writes.