Download infer_binary.py from fedeceri/cochlea-calcium-waves-binary-segmentation-unet3d: direct link, hf CLI and curl.
- Browser
- Download file 6.41 kB
-
https://huggingface.co/fedeceri/cochlea-calcium-waves-binary-segmentation-unet3d/resolve/main/infer_binary.py
- Command line
-
hf download hf://fedeceri/cochlea-calcium-waves-binary-segmentation-unet3d/infer_binary.py
-
curl -L -o infer_binary.py https://huggingface.co/fedeceri/cochlea-calcium-waves-binary-segmentation-unet3d/resolve/main/infer_binary.py
6.41 kB
| """Run 3D calcium-wave segmentation on a TIFF stack or OME-Zarr movie.""" | |
| import argparse | |
| from pathlib import Path | |
| import numpy as np | |
| import tifffile | |
| import torch | |
| import yaml | |
| import zarr | |
| from monai.inferers import sliding_window_inference | |
| from monai.networks.nets import UNet | |
| from scipy import ndimage as ndi | |
| RELEASE_DIR = Path(__file__).resolve().parent | |
| def load_config(): | |
| with open(RELEASE_DIR / "config.yml", encoding="utf-8") as file: | |
| return yaml.safe_load(file) | |
| def select_device(requested): | |
| if requested != "auto": | |
| return torch.device(requested) | |
| if torch.cuda.is_available(): | |
| return torch.device("cuda") | |
| if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): | |
| return torch.device("mps") | |
| return torch.device("cpu") | |
| def load_movie(path): | |
| path = Path(path) | |
| if path.is_dir() or path.suffix.lower() == ".zarr": | |
| root = zarr.open(str(path), mode="r") | |
| movie = root["s0"] if hasattr(root, "keys") and "s0" in root else root | |
| movie = np.asarray(movie) | |
| elif path.suffix.lower() in (".tif", ".tiff"): | |
| movie = tifffile.imread(path) | |
| else: | |
| raise ValueError("Input must be a TIFF stack or an OME-Zarr directory.") | |
| movie = np.asarray(movie) | |
| if movie.ndim != 3: | |
| raise ValueError( | |
| f"Expected a (time, height, width) movie, got shape {movie.shape}." | |
| ) | |
| return movie | |
| def build_model(config, device): | |
| model_config = config["model"] | |
| if model_config["architecture"] != "unet": | |
| raise ValueError("This release supports the configured MONAI UNet model.") | |
| model = UNet( | |
| spatial_dims=model_config["spatial_dims"], | |
| in_channels=model_config["in_channels"], | |
| out_channels=model_config["out_channels"], | |
| channels=tuple(model_config["channels"]), | |
| strides=tuple(model_config["strides"]), | |
| num_res_units=model_config["num_res_units"], | |
| ) | |
| weights_path = RELEASE_DIR / model_config["weights"] | |
| state_dict = torch.load(weights_path, map_location="cpu", weights_only=True) | |
| model.load_state_dict(state_dict) | |
| return model.to(device).eval() | |
| def predict(model, movie, device, config): | |
| inference_config = config["inference"] | |
| image = torch.as_tensor(movie, dtype=torch.float32).unsqueeze(0).unsqueeze(0) | |
| minimum = image.amin() | |
| maximum = image.amax() | |
| intensity_range = maximum - minimum | |
| if intensity_range > 0: | |
| image = (image - minimum) / intensity_range | |
| else: | |
| image = torch.zeros_like(image) | |
| with torch.inference_mode(): | |
| logits = sliding_window_inference( | |
| inputs=image, | |
| roi_size=tuple(inference_config["roi_size"]), | |
| sw_batch_size=inference_config["sw_batch_size"], | |
| predictor=model, | |
| sw_device=device, | |
| device="cpu", | |
| overlap=inference_config["overlap"], | |
| mode=inference_config["blend_mode"], | |
| sigma_scale=inference_config["sigma_scale"], | |
| buffer_steps=inference_config["buffer_steps"], | |
| buffer_dim=0, | |
| progress=True, | |
| ) | |
| probabilities = torch.sigmoid(logits)[0, 0].numpy() | |
| mask = probabilities >= inference_config["threshold"] | |
| return mask, probabilities | |
| def reorder_labels_temporally(labels): | |
| objects = ndi.find_objects(labels) | |
| existing = [ | |
| label_id | |
| for label_id, slices in enumerate(objects, start=1) | |
| if slices is not None | |
| ] | |
| ordered = sorted( | |
| existing, | |
| key=lambda label_id: tuple( | |
| objects[label_id - 1][axis].start for axis in range(3) | |
| ), | |
| ) | |
| lookup = np.zeros(labels.max() + 1, dtype=np.uint32) | |
| lookup[ordered] = np.arange(1, len(ordered) + 1, dtype=np.uint32) | |
| return lookup[labels] | |
| def binary_to_instance_labels(mask, config): | |
| postprocessing = config["postprocessing"] | |
| closing_structure = np.ones( | |
| tuple(postprocessing["closing_size"]), dtype=bool | |
| ) | |
| mask = ndi.binary_closing(mask, structure=closing_structure) | |
| label_structure = ndi.generate_binary_structure( | |
| rank=3, | |
| connectivity=postprocessing["connectivity"], | |
| ) | |
| labels, _ = ndi.label(mask, structure=label_structure) | |
| sizes = np.bincount(labels.ravel()) | |
| remove = sizes < postprocessing["min_size"] | |
| remove[0] = False | |
| labels[remove[labels]] = 0 | |
| return reorder_labels_temporally(labels) | |
| def labels_output_path(mask_output, explicit_path): | |
| if explicit_path: | |
| return Path(explicit_path) | |
| mask_output = Path(mask_output) | |
| return mask_output.with_name(f"{mask_output.stem}_labels.tif") | |
| def main(args): | |
| config = load_config() | |
| device = select_device(args.device) | |
| print(f"Using device: {device}") | |
| movie = load_movie(args.input) | |
| model = build_model(config, device) | |
| mask, probabilities = predict(model, movie, device, config) | |
| if args.output_type in ("mask", "both"): | |
| tifffile.imwrite(args.output, mask.astype(np.uint8), compression="zlib") | |
| print(f"Saved binary mask: {args.output}") | |
| if args.output_type in ("labels", "both"): | |
| output_path = labels_output_path(args.output, args.labels_output) | |
| labels = binary_to_instance_labels(mask, config) | |
| tifffile.imwrite(output_path, labels, compression="zlib") | |
| print(f"Saved instance labels: {output_path}") | |
| if args.probabilities_output: | |
| tifffile.imwrite( | |
| args.probabilities_output, | |
| probabilities.astype(np.float32, copy=False), | |
| compression="zlib", | |
| ) | |
| print(f"Saved probabilities: {args.probabilities_output}") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("input", help="Input 3D TIFF stack or OME-Zarr directory.") | |
| parser.add_argument( | |
| "--output", default="prediction_mask.tif", help="Binary mask output path." | |
| ) | |
| parser.add_argument( | |
| "--output-type", | |
| choices=("mask", "labels", "both"), | |
| default="mask", | |
| ) | |
| parser.add_argument("--labels-output", help="Optional instance-label output path.") | |
| parser.add_argument( | |
| "--probabilities-output", help="Optional float32 probability TIFF path." | |
| ) | |
| parser.add_argument( | |
| "--device", default="auto", help="Device: auto, cpu, cuda, or mps." | |
| ) | |
| main(parser.parse_args()) | |