Reconstruction algorithms (2D)¶
Build dw2d's mesh reconstruction algorithm, step by step or at its defaults, with dw3d's names.
dw3d's factory chooses among several EDTs, point placements, tesselations and face scores; dw2d has one of each, so
its factory keeps the setters that have a 2D meaning (set_peak_local_points_placement_method,
set_junction_relocation, set_canonical_triangle_order) and adds the 2D-only options as setters
(set_interface_projection, set_pinch_vertex_repair, set_near_tie_sliver_relabelling, set_label_expansion,
set_score_samples).
get_default_mesh_reconstruction_algorithm
module-attribute
¶
get_default_mesh_reconstruction_algorithm = MeshReconstructionAlgorithmFactory.get_default_algorithm
dw2d's default mesh reconstruction algorithm, named as in dw3d.
The same function as MeshReconstructionAlgorithmFactory.get_default_algorithm, which gives its arguments
(min_distance, print_info) and what it returns.
MeshReconstructionAlgorithmFactory ¶
MeshReconstructionAlgorithmFactory(print_info: bool = False)
Factory of 2-D mesh reconstruction algorithms. Each set_* method returns the factory, so calls chain;
make_algorithm builds the algorithm. A new factory builds the default algorithm.
Start from the default configuration (get_default_algorithm).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_info
|
bool
|
print the size of the triangulation's dual graph. Defaults to False. |
False
|
set_peak_local_points_placement_method ¶
set_peak_local_points_placement_method(min_distance: int = DEFAULT_MIN_DISTANCE) -> Self
Place the triangulation's points at the maxima of the distance map, at least min_distance pixels apart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_distance
|
int
|
in pixels. Defaults to 4 (dw3d's default is 3 voxels). |
DEFAULT_MIN_DISTANCE
|
set_junction_relocation ¶
set_junction_relocation(enabled: bool = True) -> Self
Move the junction vertices onto the mask's own junctions after meshing (on by default since 0.8.0;
dw2d.junction_relocation says what it was measured to buy).
set_canonical_triangle_order ¶
set_canonical_triangle_order(enabled: bool = True) -> Self
Make the triangulation and the watershed's tie order independent of the machine (on by default).
Qhull's triangulation of the integer points is not unique where four or more are cocircular, and Qhull
resolves those cells differently on different machines; with this option such cells are re-triangulated by a
fixed rule and triangles, dual-graph edges and equal scores are taken in canonical order. False is dw2d
0.1.5's route (named deterministic=False before 0.8.0). dw3d's analogue is canonical_tetrahedron_order.
set_interface_projection ¶
set_interface_projection(enabled: bool = True) -> Self
After the junction relocation, move interface vertices onto the mask's interface locus (opt-in; requires
the relocation, because alone it made junction angles worse: dw2d.locus_projection).
set_pinch_vertex_repair ¶
set_pinch_vertex_repair(enabled: bool = True) -> Self
Absorb label fragments and repair pinch vertices after the watershed (on by default; dw2d.mesh_surgery).
set_near_tie_sliver_relabelling ¶
set_near_tie_sliver_relabelling(enabled: bool | None = None) -> Self
Relabel near-tie slivers after the watershed (dw2d.sliver_relabelling): None (default) turns it on
without junction relocation and off with it, True or False force it.
set_label_expansion ¶
set_label_expansion(pixels: int = 0) -> Self
Grow every label by pixels before meshing (skimage.segmentation.expand_labels), for masks whose cells
are separated by background and never meet. Defaults to 0 (dw2d 0.1.5's expansion_labels).
set_score_samples ¶
set_score_samples(n: int = 10) -> Self
Sample n points along each triangle edge to score it (dw2d 0.1.5's interpolation_points).
make_algorithm ¶
make_algorithm() -> MeshReconstructionAlgorithm
Build a new algorithm with the options set so far.
Raises:
| Type | Description |
|---|---|
ValueError
|
for the interface projection without the junction relocation. |
get_default_algorithm
staticmethod
¶
get_default_algorithm(min_distance: int = DEFAULT_MIN_DISTANCE, print_info: bool = False) -> MeshReconstructionAlgorithm
The default 2-D algorithm: points at least min_distance pixels apart, canonical triangle order, pinch-vertex
repair and junction relocation on, interface projection off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_distance
|
int
|
in pixels. Defaults to 4. |
DEFAULT_MIN_DISTANCE
|
print_info
|
bool
|
print the size of the triangulation's dual graph. Defaults to False. |
False
|
dw2d's mesh reconstruction algorithm, with the names, arguments and return layout of dw3d's.
Configure, then run: dw2d.get_default_mesh_reconstruction_algorithm or dw2d.MeshReconstructionAlgorithmFactory
build a MeshReconstructionAlgorithm; construct_mesh_from_segmentation_mask(mask) runs it and returns
(points, segments, labels); one object can mesh several masks, each reconstruction replacing the last mesh and every
report about it. The computation is dw2d's (the engine behind the deprecated geometry_reconstruction_2d), unchanged:
the same mask and options give the same arrays, bit for bit.
Conventions, stated once here and in dw3d's package docstring:
- The mask is a 2-D integer array; label
0is the medium, every other label a cell.pointsare in the mask's index order,(row, column), in pixels: the centre of pixel(i, j)is the point(i, j). labels[n] = (a, b)witha < bare the two materials edgenseparates. Orientation, dw3d's rule in index order (since 0.8.0): each edge is the positively oriented boundary ofa. Materialalies on the left ofpoints[segments[n, 0]] -> points[segments[n, 1]]in the(row, column)frame, so the edges of each material, taken as stored where it isaand reversed where it isb, run counter-clockwise around it in(row, column), and the edge's normal(dc, -dr)points out ofaintob, as a dw3d triangle's right-hand normal does. See the user guide's page on orientation, which states the rule and the test that decides it. Until 0.8.0 each edge was stored the other way round; only the order of the two vertices within each edge changed.min_distancecounts pixels; its default is 4 (dw3d's is 3 voxels).
MeshReconstructionAlgorithm ¶
MeshReconstructionAlgorithm(print_info: bool = False, min_distance: int = DEFAULT_MIN_DISTANCE, *, relocate_junctions: bool = True, canonical_triangle_order: bool = True, interface_projection: bool = False, pinch_vertex_repair: bool = True, near_tie_sliver_relabelling: bool | None = None, label_expansion: int = 0, score_samples: int = 10, pad_thin_medium_margins: bool = True)
Algorithm that builds a 2-D multimaterial polyline mesh from a 2-D segmentation mask.
Build one with dw2d.get_default_mesh_reconstruction_algorithm or dw2d.MeshReconstructionAlgorithmFactory. The
mesh is (points, segments, labels): points (n, 2) float64 in the mask's (row, column) order, in pixels unless
built by construct_mesh_in_physical_units; segments (m, 2) int64 vertex indices; labels (m, 2) int64, the
two materials each edge separates, smaller first (orientation: the module docstring).
Attributes:
| Name | Type | Description |
|---|---|---|
print_info |
bool
|
whether to print the size of the triangulation's dual graph. |
min_distance |
int
|
the point placement's minimum distance between points, in pixels. |
relocate_junctions |
bool
|
move junction vertices onto the mask's own junctions after meshing (default True). |
canonical_triangle_order |
bool
|
a machine-independent triangulation and tie order (default True; dw3d's
analogue is |
interface_projection |
bool
|
project interface vertices onto the mask's interface locus (default False;
requires |
pinch_vertex_repair |
bool
|
absorb label fragments and repair pinch vertices after the watershed (default True). |
near_tie_sliver_relabelling |
bool | None
|
relabel near-tie slivers (default None: on without relocation, off with it). |
label_expansion |
int
|
grow the labels by this many pixels before meshing ( |
score_samples |
int
|
points sampled along each triangle edge to score it (default 10). |
pad_thin_medium_margins |
bool
|
mesh the mask padded with label 0 on every side of the image that no cell
reaches and whose margin is below |
Set the options; see the class docstring. Every option is also an attribute that can be set before a run.
medium_margin_padding
property
¶
medium_margin_padding: dict[str, int] | None
The label-0 padding the last reconstruction added to the mask's sides, in pixels, by side name.
Empty when the mask was meshed as given (the common case); None before any reconstruction. See
pad_thin_medium_margins and dw2d.thin_medium_margins.
last_constructed_mesh
property
¶
last_constructed_mesh: tuple[NDArray[float64], NDArray[int64], NDArray[int64]]
The last mesh built, (points, segments, labels). The algorithm's own arrays, not copies.
image_border_vertices
property
¶
image_border_vertices: NDArray[int64]
The indices of the mesh vertices on the image border, sorted.
Taken from the triangulation's structure (the endpoints of its hull edges) before any vertex moves; the junction relocation and the projection never move them. foambryo's 2D inference excludes the junctions there, where a cell-cell interface meets the image border at a straight 180-degree wedge that is not a contact angle.
cut_cells
property
¶
cut_cells: tuple[int, ...]
The cells (non-zero labels) with a vertex on the image border: cells the image cuts, ascending.
dw3d's cut_cells names the cells with a crop face; in 2D a cell is cut where its boundary reaches the image
border. Their pressures are not withheld by foambryo in 2D: Laplace's law reads them from the interfaces
inside the image.
medium_labels
property
¶
medium_labels: tuple[int, ...]
The labels that are a medium: (0,) (dw2d has no enclosed-medium region).
unresolved_cells
property
¶
unresolved_cells: tuple[int, ...]
The labels of the last mask that are absent from its mesh, ascending (see UnresolvedCellWarning).
enclosed_medium_pockets
property
¶
enclosed_medium_pockets: tuple[EnclosedMediumPocket, ...]
The pieces of label 0 of the last mask that touch no side of the image (see EnclosedMediumWarning).
relocation_report
property
¶
relocation_report: JunctionRelocationReport | None
What the junction relocation did on the last mesh, or None when it was off.
interface_projection_report
property
¶
interface_projection_report: InterfaceProjectionReport | None
What the interface projection did on the last mesh, or None when it was off.
last_constructed_dcel
property
¶
last_constructed_dcel
The last mesh as dw2d's half-edge structure, dw2d.DCEL_Data, which measures angles, lengths, areas and
curvatures; it carries image_border_vertices. Built from the points as they are now (physical if scaled).
last_compressed_segmentation
property
¶
last_compressed_segmentation: dict[str, Any]
The last mesh, the watershed seeds and the mask's shape, as a dictionary.
Keys: points, segments, labels, seeds (one pixel index per label of the mask, in ascending label
order), image_shape and image_border_vertices. dw2d.reconstruct_mask_from_dict turns it back into an
approximate mask; it expects the points in pixels, so read this before any scaling (after
construct_mesh_in_physical_units, divide the points by the pixel size first).
construct_mesh_from_segmentation_mask ¶
construct_mesh_from_segmentation_mask(segmented_image: NDArray[integer]) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64]]
Build a 2-D mesh from a segmentation mask.
After the call, last_constructed_mesh, image_border_vertices, cut_cells, relocation_report,
interface_projection_report, unresolved_cells and enclosed_medium_pockets describe this mesh, and
save_to_rec_mesh writes no physical frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmented_image
|
NDArray[integer]
|
the 2-D integer label mask; label 0 is the medium, every other label a cell. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[NDArray[float64], NDArray[int64], NDArray[int64]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
for a mask that is not 2-D (see |
Warns:
| Type | Description |
|---|---|
UserWarning
|
for a mask whose dtype is not an integer type. |
EnclosedMediumWarning
|
once, when a piece of label 0 touches no side of the image (it is meshed as the outer medium), naming each such pocket. |
UnresolvedCellWarning
|
once, when a label of the mask is absent from the mesh, naming each. Since 0.8.0
this includes a mask whose mesh has no edge at all (returned empty, |
ThinMediumMarginWarning
|
once, when a cell's edges lie on a side of the image its pixels do not reach and
that could not be padded (see |
A mask with a side that no cell reaches and whose margin is below 2 * min_distance + 2 pixels is meshed padded
with label 0 on such sides (pad_thin_medium_margins, medium_margin_padding); the mesh and the compressed
segmentation are in the mask's frame either way.
construct_mesh_in_physical_units ¶
construct_mesh_in_physical_units(segmented_image: NDArray[integer], spacing: tuple[float, float], *, spacing_unit: str | None = None, axis_order: str = 'yx') -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64]]
Build a mesh in physical units from a mask of square pixels.
The mask is meshed on its own pixel grid (construct_mesh_from_segmentation_mask, min_distance in pixels),
and the points are multiplied by the pixel size: a point at pixel index i is at i * h, so the centre of the
first pixel is the origin. Only square pixels are accepted in 0.8.0 (dw3d resamples anisotropic voxels to cubic
ones; the accuracy of the same route in 2D has not been measured).
After this call save_to_rec_mesh records coordinate_frame = physical, axis_order, spacing,
spacing_unit (when given) and source_shape in the file's appendix. Any later reconstruction clears them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmented_image
|
NDArray[integer]
|
the 2-D integer label mask. |
required |
spacing
|
tuple[float, float]
|
the pixel size along the mask's axes 0 and 1, |
required |
spacing_unit
|
str | None
|
the unit of |
None
|
axis_order
|
str
|
what the mask's axes are, recorded, not used. Defaults to |
'yx'
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[NDArray[float64], NDArray[int64], NDArray[int64]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
for a spacing that is not two positive finite numbers, or whose two values differ. |
compress_segmentation_mask ¶
compress_segmentation_mask(segmented_image: NDArray[integer]) -> dict[str, Any]
Mesh a mask and return its compressed segmentation (see last_compressed_segmentation).
both_construct_mesh_and_compressed_segmentation ¶
both_construct_mesh_and_compressed_segmentation(segmented_image: NDArray[integer]) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64], dict[str, Any]]
Mesh a mask; return (points, segments, labels, compressed_segmentation).
rec_metadata ¶
rec_metadata() -> dict[str, Any]
The appendix fields save_to_rec_mesh writes: dimension = 2, axis_order, orientation (the rule the
edges follow, dw2d.io.ORIENTATION_RECORDED), source_shape (the label image's shape), the image border
vertices, the unresolved cells (when any) and, after construct_mesh_in_physical_units, the physical frame.
save_to_rec_mesh ¶
save_to_rec_mesh(filename: str | Path, binary_mode: bool = False) -> None
Save the last mesh in the 2-D .rec format, with its current points and a metadata appendix.
The appendix (version 1, as dw3d writes it) records dimension = 2, so that every reader can tell the file
from a 3-D one, the orientation rule of the edges (orientation), and the other fields of rec_metadata. A
reader that ignores the appendix reads the mesh unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | Path
|
where to write the file ( |
required |
binary_mode
|
bool
|
write the binary variant of the format. Defaults to False (text), as dw3d. |
False
|
simple_plot ¶
simple_plot() -> None
Draw the labels, the polylines over the distance map, and the labelled triangles (matplotlib).
plot_polylines_and_seeds ¶
plot_polylines_and_seeds() -> None
Draw the polylines and the watershed seeds (matplotlib).
checked_two_dimensional_mask ¶
checked_two_dimensional_mask(segmented_image: object) -> NDArray
The mask as an array, after the input checks every dw2d entry point runs.
Raises:
| Type | Description |
|---|---|
ValueError
|
if the mask is not 2-D. A 3-D mask with an axis of length 1 is refused with a message suggesting
|
Warns:
| Type | Description |
|---|---|
UserWarning
|
when the mask's dtype is not an integer (or boolean) type. The mask is meshed anyway, as before: refusing it would break callers; its labels are read as the numbers they hold. |
save_mesh_to_rec_mesh ¶
save_mesh_to_rec_mesh(points: NDArray[float64], segments: NDArray[int64], labels: NDArray[int64], filename: str | Path, binary_mode: bool = False) -> None
Save a 2-D mesh in the .rec format, with an appendix recording dimension = 2 (as dw3d's function of this name).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
NDArray[float64]
|
|
required |
segments
|
NDArray[int64]
|
|
required |
labels
|
NDArray[int64]
|
|
required |
filename
|
str | Path
|
where to write the file. |
required |
binary_mode
|
bool
|
write the binary variant. Defaults to False. |
False
|
save_compressed_segmentation ¶
save_compressed_segmentation(filename: str | Path, compressed_segmentation: dict[str, Any]) -> None
Save a compressed segmentation with numpy.save (a pickled dictionary; numpy adds .npy). Read it back with
dw2d.reconstruct_mask_from_saved_file_dict.