Mask#
- class lsst.images.Mask(array_or_fill=0, /, *, schema, bbox=None, yx0=None, shape=None, sky_projection=None, metadata=None)#
Bases:
GeneralizedImageA 2-d bitmask image backed by a 3-d byte array.
- Parameters:
array_or_fill (
ndarray|int, default:0) – Array or fill value for the mask. If a fill value,bboxorshapemust be provided.schema (
MaskSchema) – Schema that defines the planes and their bit assignments.bbox (
Box|None, default:None) – Bounding box for the mask. This sets the shape of the first two dimensions of the array.yx0 (
Sequence[int] |None, default:None) – Logical coordinates of the first pixel in the array, orderedy,x(unless anXYinstance is passed). Ignored ifbboxis provided. Defaults to zeros.shape (
Sequence[int] |None, default:None) – Leading dimensions of the array, orderedy,x(unless anXYinstance is passed). Only needed ifarray_or_fillis not an array andbboxis not provided. Like the bbox, this does not include the last dimension of the array.sky_projection (
SkyProjection|None, default:None) – Projection that maps the pixel grid to the sky.metadata (
dict[str,TypeAliasType] |None, default:None) – Arbitrary flexible metadata to associate with the mask.
Notes
Indexing the
arrayattribute of aMaskdoes not take into account itsyx0offset, but accessing a subimage mask by indexing aMaskwith aBoxdoes, and thebboxof the subimage is set to match its location within the original mask.A mask’s
bboxcorresponds to the leading dimensions of its backingnumpy.ndarray, while the last dimension’s size is always equal to themask_sizeof its schema, since a schema can in general require multiple array elements to represent all of its planes.Attributes Summary
A proxy object for slicing a generalized image using absolute pixel coordinates.
The low-level array (
numpy.ndarray).An Astropy WCS for this image's pixel array.
2-d bounding box of the mask (
Box).The butler dataset reference for this image (
lsst.daf.butler.SerializedDatasetRef|None).The butler inputs and ID of the task quantum that produced this dataset (
lsst.daf.butler.DatasetProvenance|None).An Astropy FITS WCS for this image's pixel array.
A proxy object for slicing a generalized image using "local" or "array" pixel coordinates.
Flexible metadata associated with the image (
MetadataView).Schema that defines the planes and their bit assignments (
MaskSchema).The projection that maps this mask's pixel grid to the sky (
SkyProjection|None).The coordinates of the first pixel in the array (
YX[int]).Methods Summary
add_plane(name, description)Return a new mask with one additional mask plane.
add_planes(planes, *[, drop])Return a new mask with planes added and/or dropped.
bbox_from_sky_circle(center, radius[, clip])Calculate the bounding box on this image corresponding to a circular region on the sky.
clear([plane, boolean_mask])Clear one or more mask planes.
compare(other)Return a plane-by-plane comparison with another mask.
copy()Deep-copy the mask and metadata.
describe(*[, brief, detail, exclude])Return a
Reportdescribing this object.from_legacy(legacy[, plane_map, sky_projection])Convert from an
lsst.afw.image.Maskinstance.get(plane)Return a 2-d boolean array for the given mask plane.
read(path, **kwargs)Read an instance of this class from a file.
read_legacy(uri, *[, plane_map, ext, ...])Read a FITS file written by
lsst.afw.image.Mask.writeFits.serialize(archive, *[, update_header, ...])Serialize the mask to an output archive.
set(plane[, boolean_mask])Set a mask plane.
to_legacy([plane_map])Convert to an
lsst.afw.image.Maskinstance.update(other)Update
selfto include all common mask values set inother.view(*[, schema, sky_projection, yx0])Make a view of the mask, with optional updates.
write(path, **kwargs)Write this object to a file.
Attributes Documentation
- absolute#
A proxy object for slicing a generalized image using absolute pixel coordinates.
Notes
In this convention, the first row and column of the pixel grid is
bbox.start. A subimage and its parent image share the same absolute pixel coordinate system, and mostlsst.imagestypes (e.g.Box,SkyProjection,PointSpreadFunction) operate exclusively in this system.Note that
astropy.wcsandnumpy.ndarrayare not aware of thebbox.startoffset that defines tihs coordinates system; uselocalslicing for indices obtained from those.
- array#
The low-level array (
numpy.ndarray).Assigning to this attribute modifies the existing array in place; the bounding box and underlying data pointer are never changed.
- astropy_wcs#
An Astropy WCS for this image’s pixel array.
Notes
As expected for Astropy WCS objects, this defines pixel coordinates such that the first row and column in any associated arrays are
(0, 0), notbbox.start, as is the case forsky_projection.This object satisfies the
astropy.wcs.wcsapi.BaseHighLevelWCSandastropy.wcs.wcsapi.BaseLowLevelWCSinterfaces, but it is not anastropy.wcs.WCS(usefits_wcsfor that).
- bbox#
2-d bounding box of the mask (
Box).This sets the shape of the first two dimensions of the array.
- butler_dataset#
The butler dataset reference for this image (
lsst.daf.butler.SerializedDatasetRef|None).
- butler_provenance#
The butler inputs and ID of the task quantum that produced this dataset (
lsst.daf.butler.DatasetProvenance|None).
- fits_wcs#
An Astropy FITS WCS for this image’s pixel array.
Notes
As expected for Astropy WCS objects, this defines pixel coordinates such that the first row and column in any associated arrays are
(0, 0), notbbox.start, as is the case forsky_projection.This may be an approximation or absent if
sky_projectionis not naturally representable as a FITS WCS.
- local#
A proxy object for slicing a generalized image using “local” or “array” pixel coordinates.
Notes
In this convention, the first row and column of the pixel grid is always at
(0, 0). This is also the convention used byastropy.wcsobjects. When a subimage is created from a parent image, its “local” coordinate system is offset from the coordinate systems of the parent image.Note that most
lsst.imagestypes (e.g.Box,SkyProjection,PointSpreadFunction) operate instead in “absolute” coordinates, which is shared by subimage and their parents.
- metadata#
Flexible metadata associated with the image (
MetadataView).Notes
The view combines two sources:
metadata.native: metadata that is part of the image’s data model and is saved with it. Keys are case-sensitive.metadata.external: read-only metadata carried in from the file the image was read from, such as the primary FITS header. Keys are case-insensitive, andCOMMENTandHISTORYcards are not included.
Lookups check native metadata first, matching case exactly, and then external metadata. Writes go to native metadata; adding a new key that case-insensitively matches an external key raises
KeyError. When an external key is repeated, which of its values is returned is unspecified; useget_allto obtain every value.Native metadata is shared with subimages and other views. Assigning a mapping replaces the native metadata with a shallow copy of it (of just its native metadata, for a
MetadataView), disconnecting this image from any others it was shared with while leaving external metadata readable. To disconnect while keeping the current contents, or to start empty:image.metadata = image.metadata image.metadata = {}
Assignment does not check for keys that shadow external metadata.
- schema#
Schema that defines the planes and their bit assignments (
MaskSchema).
- sky_projection#
The projection that maps this mask’s pixel grid to the sky (
SkyProjection|None).Notes
The pixel coordinates used by this projection account for the bounding box
start(i.e.yx0); they are not just array indices.
Methods Documentation
- add_plane(name, description)#
Return a new mask with one additional mask plane.
This is a convenience wrapper around
add_planesfor the common case of adding a single plane.- Parameters:
- Returns:
A new mask whose schema includes the new plane; see
add_planesfor the reallocation and view semantics.- Return type:
- Raises:
ValueError – Raised if a plane named
namealready exists.
- add_planes(planes, *, drop=())#
Return a new mask with planes added and/or dropped.
- Parameters:
- Returns:
A new mask with the updated schema. Retained planes keep their pixel values (copied by name); newly added planes start cleared.
- Return type:
- Raises:
ValueError – Raised if a name in
dropis not an existing plane, or if a plane inplanescollides with a retained plane name.
Notes
Adding or dropping planes always reallocates the backing array and returns a new
Mask; this mask is left unchanged and any views or subimages of it continue to refer to the original array with the original schema. This is deliberate: there is no way to update the schema of an existing view, and a stale view must never set bits that its now-outdated schema regards as unused. Dropping a plane compacts the schema, so planes after it are reassigned to lower bits and the pixel values are repacked by plane name to match.
- bbox_from_sky_circle(center, radius, clip=False)#
Calculate the bounding box on this image corresponding to a circular region on the sky.
- Parameters:
center (
SkyCoord) – The center of the circle, as a scalarastropy.coordinates.SkyCoordin any frame.radius (
Angle) – Radius of the circle, as a scalarastropy.coordinates.Angle.clip (
bool, default:False) – IfTrue(Falseis default), clip pixel bounds when the circle extends outside the image. IfFalsean exception is raised if any part of the circle is off the image.
- Returns:
Bounding box enclosing the circle in this image’s pixel coordinates.
- Return type:
- Raises:
NotContainedError – Raised if the requested region is entirely off the image or if any part of the region is off the image and clipping is
False.ValueError – Raised if
centerorradiusis not scalar, or if this image has no sky projection.
- clear(plane=None, boolean_mask=Ellipsis)#
Clear one or more mask planes.
- Parameters:
plane (
str|None, default:None) – Name of the mask plane to set. IfNoneall mask planes are cleared.boolean_mask (
ndarray|EllipsisType, default:Ellipsis) – A 2-d boolean array with the same shape asbboxthat isTruewhere the bit forplaneshould be cleared andFalsewhere it should be left unchanged. May be...to clear the bit everywhere.
- Return type:
- compare(other)#
Return a plane-by-plane comparison with another mask.
- Parameters:
other (
Mask) – The mask to compare against.- Returns:
Dictionary mask planes as keys, where the values are:
the number of pixels with that plane set in
selfbut notother;the number of pixels with that plane set in
otherbut notself.
Mask planes where the images have the same pixels set are not included, so the result is empty for identical masks. Mask planes present in only one operand are treated as though they were unset for all pixels in the other operand.
- Return type:
Notes
Two masks with different schemas can have an empty
compareresult while still not satisfying an equality check, as long as the planes they have in common have the same pixels set and any planes present in only one operand have no pixels set.
- describe(*, brief=False, detail=False, exclude=())#
Return a
Reportdescribing this object.- Parameters:
brief (
bool, optional) – Whether to build only whatreprandstrread.detail (
bool, optional) – Whether to include extras that are too expensive for a default report, such as per-plane set-pixel counts.exclude (
Collection[str], optional) – Names of report elements to omit.
- Returns:
report – Report describing this object.
- Return type:
- static from_legacy(legacy, plane_map=None, *, sky_projection=None)#
Convert from an
lsst.afw.image.Maskinstance.- Parameters:
legacy (
Any) – Anlsst.afw.image.Maskinstance. This will not share pixel data with the new object.plane_map (
Mapping[str,MaskPlane] |None, default:None) – A mapping from legacy mask plane name to the new plane name and description. If not provided, the right legacy mask plane will be guessed, but this can depend on which mask planes the legacy mask actually has set. Planes fromget_legacy_optional_mask_planesare added when the legacy mask defines them and has pixels set in them.sky_projection (
Optional[SkyProjection[Any]], default:None) – Projection from pixels to sky.
- Returns:
Converted mask.
- Return type:
- get(plane)#
Return a 2-d boolean array for the given mask plane.
- classmethod read(path, **kwargs)#
Read an instance of this class from a file.
A thin convenience wrapper around
lsst.images.serialization.read_archivethat fixes the expected in-memory type to this class. The container format is inferred frompath’s extension.- Parameters:
path (
str|ParseResult|ResourcePath|Path) – File to read; convertible tolsst.resources.ResourcePath.**kwargs (
Any) – Forwarded toread_archive(e.g.bboxto read a subimage).
- Return type:
Self
- static read_legacy(uri, *, plane_map=None, ext=1, fits_wcs_frame=None)#
Read a FITS file written by
lsst.afw.image.Mask.writeFits.- Parameters:
uri (
str|ParseResult|ResourcePath|Path) – URI or file name.plane_map (
Mapping[str,MaskPlane] |None, default:None) – A mapping from legacy mask plane name to the new plane name and description. If not provided, the right legacy mask plane will be guessed, but this can depend on which mask planes the legacy mask actually has set. Planes fromget_legacy_optional_mask_planesare added when the legacy mask defines them and has pixels set in them.ext (
str|int, default:1) – Name or index of the FITS HDU to read.fits_wcs_frame (
Frame|None, default:None) – If notNoneand the HDU containing the mask has a FITS WCS, attach aSkyProjectionto the returned mask by converting that WCS.
- Returns:
Mask read from the file.
- Return type:
- serialize(archive, *, update_header=<function no_header_updates>, save_projection=True, add_offset_wcs='A', tile_shape=None, options_name=None)#
Serialize the mask to an output archive.
- Parameters:
archive (
OutputArchive[TypeVar(P, bound=BaseModel)]) – Archive to write to.update_header (
Callable[[Header],None], default:<function no_header_updates at 0x7fe9f6f95620>) – A callback that will be given the FITS header for the HDU containing this mask in order to add keys to it. This callback may be provided but will not be called if the output format is not FITS. As multiple HDUs may be added, this function may be called multiple times.save_projection (
bool, default:True) – IfTrue, save theSkyProjectionattached to the image, if there is one. This does not affect whether a FITS WCS corresponding to the projection is written (it always is, if available, and ifadd_offset_wcsis not" ").add_offset_wcs (
str|None, default:'A') – A FITS WCS single-character suffix to use when adding a linear WCS that maps the FITS array to the logical pixel coordinates defined bybbox.start/yx0. Set toNoneto not write this WCS. If this is set to" ", it will prevent theSkyProjectionfrom being saved as a FITS WCS.tile_shape (
tuple[int,...] |None, default:None) – The recommended shape of each tile, if the archive will save the array in distinct tiles for faster subarray retrieval. This is a hint; archives are not required to use this value.options_name (
str|None, default:None) – Use this name to look up archive options.
- Return type:
MaskSerializationModel[TypeVar]
- set(plane, boolean_mask=Ellipsis)#
Set a mask plane.
- Parameters:
plane (
str) – Name of the mask plane to set.boolean_mask (
ndarray|EllipsisType, default:Ellipsis) – A 2-d boolean array with the same shape asbboxthat isTruewhere the bit forplaneshould be set andFalsewhere it should be left unchanged (not set to zero). May be...to set the bit everywhere.
- Return type:
- to_legacy(plane_map=None)#
Convert to an
lsst.afw.image.Maskinstance.The pixel data will not be shared between the two objects.
- Parameters:
plane_map (
Mapping[str,MaskPlane] |None, default:None) – A mapping from legacy mask plane name to the new plane name and description. Schema planes the map does not name are written under their own names. If not provided, every schema plane is written under its own name.- Returns:
Converted mask.
- Return type:
lsst.afw.image.Mask
- update(other)#
Update
selfto include all common mask values set inother.Notes
This only operates on the intersection of the two mask bounding boxes and the mask planes that are present in both. Mask bits are only set, not cleared (i.e. this uses
|=updates, not=assignments).
- view(*, schema=Ellipsis, sky_projection=Ellipsis, yx0=Ellipsis)#
Make a view of the mask, with optional updates.
- Parameters:
schema (
MaskSchema|EllipsisType, default:Ellipsis) – Replacement schema; defaults to the current schema.sky_projection (
SkyProjection|None|EllipsisType, default:Ellipsis) – Replacement sky projection; defaults to the current one.yx0 (
Sequence[int] |EllipsisType, default:Ellipsis) – Replacement origin of the mask; defaults to the current origin.
- Return type:
Notes
This can only be used to make changes to schema descriptions; plane names must remain the same (in the same order).
- write(path, **kwargs)#
Write this object to a file.
A thin convenience wrapper around
lsst.images.serialization.write_archive. The container format is chosen frompath’s extension.- Parameters:
path (
str) – Destination file path. Must not already exist.**kwargs (
Any) – Forwarded towrite_archive(e.g.compression_optionsandcompression_seedfor FITS).
- Return type: