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 DATASUM and CHECKSUM cards.

Same semantics as TableHDU.add_checksum(). This is the call most users want — writes both cards atomically.

add_datasum()

Compute and store the DATASUM checksum card.

Same semantics as TableHDU.add_datasum(): manual refresh, no auto-update on mutation. Call after write() / extend() / __setitem__.

bitpix

Raw FITS BITPIX value (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 NAXISn where n is the highest). Grows the on-disk data section to fit the combined shape, writes the new pixels, and bumps the corresponding NAXISn card in the header.

A first extend on an empty HDU created with create_image_hdu(dtype, (0, ...)) is the natural way to fill a streaming-write image: the 0 -> N growth 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 as write() (BITPIX-native, scaled, or f8 for general scaling; MaskedArray accepted).

  • start (list of int, optional) – Per-axis starting offset for the write. Default None appends at the current slow-axis end (hdu.shape[0]); explicit start[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

EXTNAME header value, or None when the keyword is absent.

EXTNAME is the user-visible name of the HDU (e.g. 'SCI', 'CATALOG'). Combined with extver it’s the standard way to identify HDUs without relying on position-by-index.

extver

EXTVER header value, defaulting to 1 when absent.

Per the FITS standard, multiple HDUs may share an EXTNAME and are distinguished by EXTVER. Returns 1 rather than None for the absent case so callers can compare/select without handling Optional[int].

has_data

True iff this HDU has a non-empty data section.

Works uniformly across image and table HDUs: the test is NAXIS > 0 AND every NAXISn > 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=0 but PCOUNT>0 (heap-only) returns False — 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 on FITSHeader.

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 FITS object — 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).

0 for primary HDUs with no data section. Same as len(hdu.shape).

read(*, scale=True, mask_blank=False)

Read the image into a numpy array.

Parameters:
  • scale (bool, optional) – If True (default), apply BSCALE / BZERO scaling. For files with the unsigned-int trick (BITPIX=16/32/64 + BZERO=2**(n-1), or BITPIX=8 + BZERO=-128), returns the matching unsigned (or i1) dtype with no precision loss. For general scaling, returns f8. If False, returns raw stored values in the BITPIX-native dtype.

  • mask_blank (bool, optional) – If True, return a numpy.ma.MaskedArray with True at pixels whose stored value matches the header’s BLANK keyword. Comparison is in stored (pre-scaling) space per the FITS spec. Only valid for integer BITPIX; float BITPIX rejects because the spec forbids BLANK on floats (NaN serves that role). When BLANK is absent, returns a MaskedArray with an all-False mask — return type stays consistent. Default False.

Returns:

Array of shape hdu.shape.

Return type:

numpy.ndarray or numpy.ma.MaskedArray

Raises:

ValueErrormask_blank=True on 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=0 return ().

size

Total pixel count (product of all NAXISn).

Returns 0 when NAXIS=0 (empty shape). Without the special case the empty-product identity would give 1, which is wrong for “no data”.

unit

BUNIT header value (e.g. 'Jy', 'counts/s'), or None when unset. Informational only; nothing in the read or write path consumes it.

verify_checksum()

Verify the stored CHECKSUM over the full HDU.

Returns True / False / None (None means the card is absent).

verify_datasum()

Verify the stored DATASUM against the current data.

Returns True / False / None (None means 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, when start= is set, fit within hdu.shape from start). Dtype must be the HDU’s BITPIX-native type, the matching scaled dtype (unsigned-int trick), or f8 (which goes through general reverse-scaling into the stored dtype, with rint + bounds check for integer BITPIX). MaskedArray input auto-fills masked positions with the sentinel from BLANK (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. Default None writes 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

extend

Grow the slow axis to fit larger data.

__setitem__

Slice-style partial writes.