acia.base#
All basic functionality for acia
- class acia.base.Instance[source]#
Bases:
objectCell instance based on an image mask and a label
- __init__(mask, frame, label, id=None, score=None, bbox=None)[source]#
Create an object instance
- Parameters:
mask (np.ndarray) – mask of the object where the object pixels are marked with [label] value
frame (int) – frame in the time-lapse
label (int) – label of the object (as marked in the mask)
id (_type_, optional) – Unique identifier for the object. Defaults to None.
score (float, optional) – E.g. confidence of the detection method. Defaults to None.
bbox (tuple[slice, slice], optional) – this label’s
(rows, cols)bounding box withinmask, as returned byscipy.ndimage.find_objects. Every derived geometry is computed inside it, so supplying it saves locating the label – the only step that still has to look at the whole frame. Onefind_objectscall yields the boxes for a whole frame at once (seeoverlay_from_masks()). Derived lazily when omitted.
- property label#
- property binary_mask#
Full-frame boolean mask of this instance.
Kept frame-sized because callers overlay it on the image (see
toMask()and the fluorescence extractor). Shape-derived properties use_cropped_maskinstead.
- property center#
- toMask(height, width)[source]#
Render contour mask onto new image
height: height of the image width: width of the image
- property polygon: Polygon | MultiPolygon | None#
Outline of this instance, traced from its mask.
Traced inside the label’s bounding box and then shifted back into frame coordinates. Polygonising the full frame instead – which is what this did – costs O(frame) per cell, so the same cell got ~4x more expensive each time the image dimensions doubled.
- property is_fragmented: bool#
Whether this instance’s mask has more than one connected component.
Such a mask has no single outline, so
coordinates(anddraw()) can only represent its largest part – seelargest_polygon(). Lets a caller that is about to persist or render many instances report how many are affected instead of losing the smaller parts silently.
- property coordinates: ndarray#
Extract contour coordinates
A mask with disconnected components has no single outline; its largest part is used (see
largest_polygon()), matching whatdraw()renders.is_fragmentedreports when that applies.- Raises:
ValueError – if the polygon is not valid or None
- Returns:
np.ndarray – Nx2 contour coordinates of the polygon
- draw(image, draw=None, outlineColor=(255, 255, 0), fillColor=None)[source]#
Draws instance onto an image
- Parameters:
image (np.array | PIL.Image) – the image to draw onto
draw (PIL.ImageDraw, optional) – Drawing Tool. Defaults to None.
outlineColor (tuple, optional) – Color of the Instance contour. None means no contour is drawn. Defaults to (255, 255, 0).
fillColor (tuple, optional) – Color of the contour fill. Defaults to None (no filling).
- Returns:
np.array | PIL.Image – The image containing the drawn contour.
- class acia.base.Contour[source]#
Bases:
objectClass for object contour detection (e.g. Cell object)
- property coordinates: ndarray#
The contour outline as an
(N, 2)array of(x, y)points.Note that mutating the returned array in place (
cont.coordinates[0] = ...) does not invalidate the cachedpolygon; assign to the attribute instead, asscale()does.
- toMask(height, width)[source]#
Render contour mask onto new image
height: height of the image width: width of the image
- scale(scale)[source]#
Apply scale factor to contour coordinates
- Parameters:
scale (float) – the multplication factor
- property center#
- property polygon: Polygon#
Shapely outline built from
coordinates(cached).Cached because a single extraction run reads it several times per contour – once per geometry property, plus once per filter – and rebuilding the polygon each time was a measurable share of that.
- class acia.base.Overlay[source]#
Bases:
objectOverlay contains Contours at different frames and provides functionalities iterate and modify them
- property timepoints#
Per-frame pint
Quantityof timepoints, orNoneif uncalibrated.
- property timestamps#
Pint
Quantityof per-contour timestamps (incontoursorder).
- with_timepoints(timepoints)[source]#
Attach explicit per-frame timepoints (pint) and stamp each detection.
- Return type:
- with_frame_interval(interval)[source]#
Attach a scalar frame interval (pint) and stamp each detection.
- Return type:
- scale(scale)[source]#
Scale the contour with the specified scale factor
Applies the scale factor to all coordinates individually
- Parameters:
scale (float) – [description]
- timeIterator(startFrame=None, endFrame=None, frame_range=None)[source]#
Creates an iterator that returns an Overlay for every frame between starFrame and endFrame
startFrame: first frame number endFrame: last frame number
- toMasks(height, width, binary_mask=True)[source]#
Turn the individual overlays into masks. For every time point we create a mask of all contours.
returns: List of masks (np.ndarray[bool])
height: height of the image width: width of the image
- draw(image, outlineColor=None, fillColor=None)[source]#
Draw an overly onto an image frame. Hint: overlay should only contain contours for a single frame
- Parameters:
image (np.ndarray | Image) – Image to draw onto
outlineColor (str | Callable[[Contour], tuple[int]], optional) – Color of the object outlines. If this is a function, the function computes the color for every contour/instance individually. Defaults to None (no contour is drawn).
fillColor (str | Callable[[Contour], tuple[int]], optional) – Fill color of the object. If this is a function, the function computes the color for every contour/instance individually. Defaults to None (no fill). Defaults to None.
- Returns:
np.ndarray | Image – the updated image object
- Return type:
ndarray | Image
- class acia.base.BaseImage[source]#
Bases:
objectBase class for an image from an image source
- property raw#
- property num_channels#
- class acia.base.ArrayImage[source]#
Bases:
BaseImageA BaseImage backed directly by a numpy array (e.g. a cropped frame).
- property raw#
- property num_channels#
- class acia.base.ImageSequenceSource[source]#
Bases:
Iterable[BaseImage],SizedBase class for an image sequence source (e.g. Tiff, OMERO, png, …).
Supports numpy-style indexing over the (T, H, W, C) axes:
src[5]-> the frame at index 5 (aBaseImage)src[::2]-> a view sequence of every second framesrc[3:23, 10:90, 10:90, 0]-> a cropped, single-channel subsequence
- property timepoints#
Per-frame pint
Quantityof timepoints, orNoneif uncalibrated.
- property pixel_size#
Pint length per pixel (scalar or
[y, x]), orNone.
- with_frame_interval(interval)[source]#
Tag this source with a scalar frame interval (pint); returns self.
- with_timepoints(timepoints)[source]#
Tag this source with explicit per-frame timepoints (pint); returns self.
- with_pixel_size(pixel_size)[source]#
Tag this source with a pixel size (pint length per pixel); returns self.
- to_channel(c)[source]#
Return a lazy single-channel view of this source.
- Parameters:
c (int) – the channel index to select.
- Returns:
ImageSequenceSource – a view of this source with only channel
c(equivalent toself[..., c]).- Return type:
- crop_rotated(spec)[source]#
Return a lazy rotated-rectangle crop view of this source.
The crop is defined by a
RotatedCropSpec(center, size, angle). Each frame is warped on demand so the resulting source stays lazy and the parent’s calibration (pixel_size/timepoints) is preserved.- Parameters:
spec (RotatedCropSpec) – The rotated-rectangle crop specification.
- Returns:
RotatedCropSequenceSource – A lazy straightened crop of this source.
- Return type:
- register(transforms, *, on_missing='warn')[source]#
Return a lazy drift-corrected view of this source.
Each frame is corrected on demand via
acia.registration.apply_correction()using the transform stored for that frame index.- Parameters:
transforms (dict[int, FrameTransform]) – Frame index ->
FrameTransform(within this source), as estimated by aRegistrationMethodand persisted viaacia.registration_persistence.on_missing (str) – How to handle a frame with no stored transform — see
RegisteredSequenceSource. Defaults to"warn".
- Returns:
RegisteredSequenceSource – A lazy corrected view of this source.
- Return type:
- to_rgb(*, channel=0, colors=None)[source]#
Return a lazy
(H, W, 3)uint8 RGB view of this source.With
colors=None(the default), renderschannelin grayscale: that channel’s plane is normalized to uint8 viaacia.notebook.normalize_to_uint8(), then triplicated across the color axis. Withcolors, renders a per-channel color composite: each channel present incolorsis normalized independently, scaled by its assigned color, and additively blended (clipped to[0, 255]); channels not present incolorsare not rendered.- Parameters:
channel (int) – Channel index to render in grayscale mode. Ignored when
colorsis given. Defaults to0.colors (dict[int, str] | None) – Optional mapping of channel index -> color, where each color is a hex string (e.g.
"#00FF00") or a name fromacia.colors.CHANNEL_COLORS(case-insensitive). Seeacia.colors.resolve_channel_color(). Defaults toNone(grayscale mode).
- Returns:
RGBSequenceSource – A lazy view of this source whose
get_frame(t)yields(H, W, 3)uint8 frames. No frame is read or converted until it is accessed.- Raises:
ValueError – if any color in
colorsis not a known channel name and not a colormatplotlib.colors.to_rgb()can parse.- Return type:
- materialize()[source]#
Eagerly freeze this (possibly lazy) source into an in-memory source.
Stacks every frame into a single
(T, H, W, C)array, normalizing grayscale(H, W)frames to(H, W, 1), and returns aTHWCSequenceSourcecarrying the samepixel_size/timepoints. This trades RAM for repeated warp/IO CPU and lets a large parent be released once a small ROI has been extracted.Frames are copied into a pre-allocated output array one at a time instead of being collected in a list first: a frame’s
rawis often only a view into a much larger parent buffer (a slice of a stack, a channel selection, a freshly decoded file), and holding allTviews alive at once would pinTparent buffers in memory. Peak usage here is the output array plus a single frame.- Returns:
THWCSequenceSource – An in-memory source independent of any parent.
- Return type:
- class acia.base.RotatedCropSpec[source]#
Bases:
objectSpecification of a rotated-rectangle crop.
The crop is described in the parent image’s pixel coordinate system. The region is straightened (de-rotated) into an axis-aligned output of shape
(size[1], size[0])==(h, w).- Variables:
- classmethod from_dict(data)[source]#
Build a
RotatedCropSpecfrom a plain dict.- Parameters:
- Returns:
RotatedCropSpec – The reconstructed spec.
- Return type:
- class acia.base.RotatedCropSequenceSource[source]#
Bases:
ImageSequenceSource,JupyterVisualizationMixinA lazy rotated-rectangle crop view over a parent sequence.
Each frame is warped on demand via OpenCV so the rotated region is straightened and centered into an axis-aligned
(h, w)output. Pixel spacing is unchanged by rotation and no frames are dropped, sopixel_sizeandtimepointspass through from the parent (own-wins-else-parent).A rotated rectangle that extends past the image bounds is filled with a zero border (no crash).
Note
pixel_sizepass-through is exact only for isotropic (square) pixels. For an anisotropic[y, x]pixel size, a rotation that is not a multiple of 90 degrees mixes the axes, so the reported pixel size is approximate. Frames are interpolated withINTER_LINEAR; this crops intensity images, not label/mask images (linear interpolation would blend label ids).- __init__(parent, spec)[source]#
- Parameters:
parent (ImageSequenceSource)
spec (RotatedCropSpec)
- property timepoints#
Per-frame pint
Quantityof timepoints, orNoneif uncalibrated.
- property pixel_size#
Pint length per pixel (scalar or
[y, x]), orNone.
- class acia.base.RegisteredSequenceSource[source]#
Bases:
ImageSequenceSourceA lazy drift-corrected view over a parent sequence.
Each frame is corrected on demand via
acia.registration.apply_correction(), using theFrameTransformstored for that frame index (a per-position transform dict, as produced by batch-apply and persisted viaacia.registration_persistence). A registration correction does not change frame dimensions, unlike a crop, sosize_h/size_w/size_c/num_channelssimply delegate straight to the parent – no dimension recomputation.on_missingdecides what happens to a frame that has no stored transform (one that failed during batch-apply):"warn"(default) – return it unchanged with a warning. Never a hard crash, so a segmentation/tracking notebook consuming this source can keep going even if a handful of frames never got a stored correction. Note that an uncorrected frame is off by the full accumulated drift, so in a sequence that has drifted it reads as a visible jump."nearest"– correct it with the nearest available frame’s transform instead. Drift between neighboring frames is usually far smaller than drift since the reference, so this is normally much closer to right than leaving the frame alone; it is still an approximation, and warns as such."error"– raiseKeyError. For callers that would rather stop than consume a partially-corrected sequence.
Warnings are emitted once per frame index rather than once per call, so a lazy multi-pass consumer (crop -> write) does not repeat them on every pass.
missing_frameslets a caller report the whole set once instead.- MISSING_POLICIES = ('warn', 'nearest', 'error')#
- __init__(parent, transforms, *, on_missing='warn')[source]#
- Parameters:
parent (ImageSequenceSource)
transforms (dict[int, FrameTransform])
on_missing (str)
- property timepoints#
Per-frame pint
Quantityof timepoints, orNoneif uncalibrated.
- property pixel_size#
Pint length per pixel (scalar or
[y, x]), orNone.
- class acia.base.RGBSequenceSource[source]#
Bases:
ImageSequenceSourceA lazy grayscale-to-RGB or per-channel color-composite view.
With
colors=None, each frame is rendered by selectingchannel’s plane, normalizing it to uint8 viaacia.notebook.normalize_to_uint8(), and triplicating it across the color axis. Withcolorsgiven, each channel present incolorsis normalized independently, scaled by its resolved RGB color, and additively blended, clipped to[0, 255]. Colors are resolved once at construction time (viaacia.colors.resolve_channel_color()), so an unknown color name or invalid hex string raisesValueErrorimmediately rather than on first frame access.colorsmust not be empty – passcolors=Nonefor grayscale mode instead. Channel indices (channeland every key ofcolors) are validated against each frame’s actual channel count as it is read, raising a clearValueErrorrather than a bare numpyIndexError; this does not special-case sources whose frames are already RGB-like (e.g. an already-3-channel source, or chainingto_rgb()on the output of anotherto_rgb()call) – those are still rendered viachannel/colorslike any other source, with no pass-through or idempotency guarantee.Rendering to RGB does not change the frame’s temporal/spatial extent, so
size_t/size_h/size_w/pixel_size/timepointsdelegate straight to the parent, mirroringRegisteredSequenceSource.size_c/num_channelsare always3(not delegated), since the output is always an RGB image regardless of how many channels the parent has.- __init__(parent, channel=0, colors=None)[source]#
- Parameters:
parent (ImageSequenceSource)
channel (int)
- property timepoints#
Per-frame pint
Quantityof timepoints, orNoneif uncalibrated.
- property pixel_size#
Pint length per pixel (scalar or
[y, x]), orNone.
- class acia.base.SlicedSequenceSource[source]#
Bases:
ImageSequenceSource,JupyterVisualizationMixinA lazy view over a parent sequence selecting frames and cropping each.
Holds the parent source, a list of original frame indices and a trailing spatial/channel key applied to every frame’s array. Re-slicing nests another view, so composition is automatic.
- __init__(parent, t_indices, spatial=())[source]#
- Parameters:
parent (ImageSequenceSource)
spatial (tuple)
- property timepoints#
Per-frame pint
Quantityof timepoints, orNoneif uncalibrated.
- property pixel_size#
Pint length per pixel (scalar or
[y, x]), orNone.
- class acia.base.RoISource[source]#
Bases:
Iterable[Overlay],SizedBase class for a RoI source (e.g. tiff metadata, OMERO, json, …)