File I/O#
Use FileHandler to read images and labels or save prediction masks and polygons.
from pathlib import Path
from cellseg_models_pytorch.utils import FileHandler
Images and MATLAB labels#
image = FileHandler.read_img("data/image.png")
labels = FileHandler.read_mat("data/labels.mat")
instances = labels["inst"]
cell_types = labels["type"]
Images are RGB arrays in height, width, channels order, usually uint8 (0–255).
Select label arrays by their saved keys, such as inst and type.
For MATLAB v7.3 files, use an HDF5 reader.
Path("outputs").mkdir(exist_ok=True)
FileHandler.to_mat(
{"inst": instances, "type": cell_types},
"outputs/prediction.mat",
)
Create the output folder first. Saving may overwrite an existing file.
to_mat saves only inst, type, sem and cyto; see its parameters below for
optional object measurements.
Read existing HDF5 samples#
Install tables (PyTables). Choose the array names and sample index to read:
sample = FileHandler.read_h5("data/train.h5", 0, keys=("image", "inst", "type"))
For training, the HDF5 dataset reads these samples and applies transforms.
Save vector predictions#
For whole-slide results, see polygon merging.
gdf_to_file saves a GeoDataFrame as .parquet, .feather or .geojson.
It keeps the input’s coordinates and units. Empty data and unsupported suffixes
produce no file.
Create output folders first and choose new paths to preserve existing results.
Neither gdf_to_file nor write_img confirms that a file was written; check the
output when saving.
- class FileHandler#
Read RGB images, label arrays and selected vector output formats.
Methods are static; call them on FileHandler without constructing an instance. They do not create output directories or guarantee exclusive file creation.
- static gdf_to_file(gdf, path, silence_warnings=True)#
Save a nonempty GeoDataFrame in a supported vector format.
- Parameters:
gdf (GeoDataFrame) – GeoDataFrame containing geometries and their attributes. Coordinate units and coordinate reference system are preserved as supplied.
path (str) – Destination ending in .parquet, .feather or .geojson. Parent folders must exist; existing-file behavior follows the format writer.
silence_warnings (bool) – Suppress the warning when an empty frame is skipped.
- Returns:
None. Empty frames and unsupported suffixes produce no file. The method does not validate unsupported suffixes or signal this skip through a result.
- Raises:
ModuleNotFoundError – GeoPandas is unavailable. Format-writer errors propagate.
- Return type:
None
- static read_h5(path, ix, keys)#
Read one sample from selected root-level HDF5 arrays.
- Parameters:
path (Path | str) – Existing HDF5 file readable by PyTables.
ix (int) – Index on each selected array’s first axis.
keys (Tuple[str, ...]) – Root node names to read. Each must support node[ix, …]; scalar metadata nodes are not sample arrays.
- Returns:
Dictionary with exactly the requested keys and their NumPy sample values. Image nodes commonly contain HWC images and masks HW arrays, but this reader preserves stored shapes, dtypes, values and key names.
- Raises:
ModuleNotFoundError – PyTables is unavailable.
IOError – A requested node cannot be read. This wrapper reports missing nodes, invalid indices and other per-node reader failures this way.
- Return type:
Dict[str, ndarray]
- static read_img(path)#
Read an image as RGB pixel values.
- Parameters:
path (str | Path) – Image file readable by OpenCV.
- Returns:
NumPy array (height, width, 3) in RGB channel order, normally uint8 with values 0–255. OpenCV’s default colour read discards alpha. No model normalization is applied. Decode failures raise OpenCV errors.
- Return type:
ndarray
- static read_mat(path)#
Read arrays and metadata from a MATLAB file.
- Parameters:
path (str | Path) – MATLAB file supported by scipy.io.loadmat; HDF5-based MATLAB v7.3 files are not supported by this reader.
- Returns:
Dictionary from scipy.io.loadmat, including stored arrays and metadata keys such as __header__, __version__ and __globals__. Shapes and dtypes are retained. Select your label keys explicitly, for example inst/type; class mappings are not inferred or remapped.
- Return type:
Dict[str, ndarray]
- static to_mat(masks, path, coords=None, compute_centroids=False, compute_bboxes=False, compute_type_array=False)#
Save selected segmentation masks in a MATLAB file.
- Parameters:
masks (Dict[str, ndarray]) – Dictionary of NumPy label arrays. Recognized keys are inst, type, sem and cyto; unrecognized keys, including cyto_inst/cyto_type, are ignored. Masks normally have HW axes. Instance 0 is background.
path (str | Path) – Output filename; the suffix is replaced by .mat. Parent folders must exist and an existing file may be overwritten.
coords (Tuple[int, int, int, int]) – Optional (x, y, width, height) metadata, saved under coords. It does not shift mask pixels or derived measurements.
compute_centroids (bool) – Add centroid as (x, y) pixel coordinates, in sorted instance-ID order. Assumes zero background is present.
compute_bboxes (bool) – Add bbox from the inst mask. Assumes a background label is present, as the first sorted label is skipped.
compute_type_array (bool) – Add inst_type when inst and type are provided. Uses the smallest class ID within each instance, not a majority vote.
- Returns:
None. Saves recognized masks plus requested derived arrays. An input without recognized masks can still write a metadata-only or empty file.
- Return type:
None
- static write_img(path, img)#
Write an RGB image using OpenCV.
- Parameters:
path (str | Path) – Destination path; its suffix selects the codec. The parent folder must already exist and an existing file may be overwritten.
img (ndarray) – NumPy RGB image (height, width, 3), normally uint8 with values 0–255. Convert model-normalized floats to an appropriate image range first.
- Returns:
None. This wrapper does not check OpenCV’s success flag, so a failed write is not always reported as an exception. Verify output creation when the surrounding workflow needs a confirmed saved file.
- Return type:
None