File size: 6,411 Bytes
fa22c82 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | """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())
|