diff --git a/caiman/source_extraction/volpy/mrcnn/config.py b/caiman/source_extraction/volpy/mrcnn/config.py index 20357f24e..aa1f8ce1d 100644 --- a/caiman/source_extraction/volpy/mrcnn/config.py +++ b/caiman/source_extraction/volpy/mrcnn/config.py @@ -9,13 +9,25 @@ Revised by Changjia Cai, Eric Thompson, Manuel Paez """ +import os + +from caiman.paths import caiman_datadir + class Config: # Paths - DATA_DIR = r'~/volpy_training_data/' #Edit to your data directory - MODEL_SAVE_DIR = r'~/volpy_models/' #Edit to your model directory + DATA_DIR = os.path.expanduser(os.environ.get( + "CAIMAN_VOLPY_TRAINING_DATA", + os.path.join(caiman_datadir(), "volpy_training_data"), + )) + MODEL_SAVE_DIR = os.path.expanduser(os.environ.get( + "CAIMAN_VOLPY_MODEL_DIR", + os.path.join(caiman_datadir(), "model"), + )) + ALLOW_OVERWRITE = False # Model and Training Hyperparameters NUM_CLASSES = 1 + 1 # Background + Neuron + MODEL_VARIANT = "maskrcnn_resnet50_fpn_v2" BATCH_SIZE = 2 NUM_EPOCHS = 100 MAX_LR = 0.005 @@ -26,7 +38,8 @@ class Config: # Data Loading, Splitting, and Inference RANDOM_SPLIT = False # True for random split, False for fixed split from map below. NUM_TEST_RANDOM = 8 - NUM_TORCH_WORKERS = 4 + NUM_TORCH_WORKERS = 4 + RANDOM_SEED = 42 DATASET_REGION_MAP = { 'HPC': [0, 1, 2, 3], 'L1': [12, 13, 14], @@ -34,15 +47,27 @@ class Config: 'Train': [4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19, 20, 22, 23] } + # Inference settings used by the current FPN-v2 checkpoints. INFERENCE_THRESHOLD = 0.5 + MASK_THRESHOLD = 0.5 + BOX_NMS_THRESHOLD = 0.5 + MASK_EROSION_RADIUS = 1 # Logging and Saving Frequency PRINT_FREQ = 1 - SAVE_FREQ = 20 + SAVE_FREQ = 5 + + def to_dict(self): + """Return public configuration values.""" + return { + name: getattr(self, name) + for name in dir(self) + if name.isupper() and not callable(getattr(self, name)) + } def display(self): """Display Configuration values.""" print("\nConfigurations:") for key, val in self.to_dict().items(): print(f"{key:30} {val}") - print("\n") \ No newline at end of file + print("\n") diff --git a/caiman/source_extraction/volpy/mrcnn/model.py b/caiman/source_extraction/volpy/mrcnn/model.py index 29333dd59..50d786f48 100644 --- a/caiman/source_extraction/volpy/mrcnn/model.py +++ b/caiman/source_extraction/volpy/mrcnn/model.py @@ -10,16 +10,19 @@ Revised by Eric Thompson, Chanjia Cai, and Manuel Paez """ -import numpy as np -import torch +import pickle +import warnings + +import torch import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor -from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor - -from caiman.source_extraction.volpy.mrcnn.utils import ScaleImage, data_transform +from torchvision.models.detection.mask_rcnn import ( + MaskRCNNPredictor, + MaskRCNN_ResNet50_FPN_V2_Weights, +) # Model (Pre-trained on the COCO Dataset) -def get_model_instance_segmentation(num_classes): +def get_model_instance_segmentation(num_classes, pretrained=True): """ Loads a pre-trained Mask R-CNN model and modifies its classification and mask prediction heads for a custom number of classes. @@ -31,8 +34,12 @@ def get_model_instance_segmentation(num_classes): Returns: torch.nn.Module: The modified Mask R-CNN model ready for fine-tuning. """ - # load an instance segmentation model pre-trained on COCO, fpn_v2 provides better performance - model = torchvision.models.detection.maskrcnn_resnet50_fpn_v2(weights='COCO_V1', trainable_backbone_layers=3) + weights = MaskRCNN_ResNet50_FPN_V2_Weights.DEFAULT if pretrained else None + model = torchvision.models.detection.maskrcnn_resnet50_fpn_v2( + weights=weights, + weights_backbone=None, + trainable_backbone_layers=3 if pretrained else None, + ) # get number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features @@ -50,11 +57,37 @@ def get_model_instance_segmentation(num_classes): num_classes) return model + +def load_mrcnn_weights(model, weights_path, device): + """Load legacy state dictionaries and metadata-bearing checkpoints.""" + try: + checkpoint = torch.load(weights_path, map_location=device, weights_only=True) + except TypeError: # torch < 2.0 compatibility + checkpoint = torch.load(weights_path, map_location=device) + except pickle.UnpicklingError: + warnings.warn( + "This legacy checkpoint requires pickle loading. Only load model files " + "from a trusted source.", + RuntimeWarning, + stacklevel=2, + ) + checkpoint = torch.load(weights_path, map_location=device, weights_only=False) + if isinstance(checkpoint, torch.nn.Module): + state_dict = checkpoint.state_dict() + elif isinstance(checkpoint, dict): + state_dict = checkpoint.get('model_state_dict', checkpoint) + else: + raise TypeError(f"Unsupported Mask R-CNN checkpoint type: {type(checkpoint).__name__}") + model.load_state_dict(state_dict) + return checkpoint + def mrcnn_inference(model, img, eval_transform, device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'), - thresh=0.5): + thresh=0.5, + mask_threshold=0.5, + return_scores=False): """ inference using Mask R-CNN network """ @@ -66,16 +99,22 @@ def mrcnn_inference(model, predictions = model([x, ]) pred = predictions[0] - predicted_masks, predicted_boxes = thresholded_predictions(pred, threshold=thresh) - binarized_masks = (0.5+predicted_masks).detach().cpu().numpy().astype(np.uint8) + predicted_masks, predicted_boxes, predicted_scores = thresholded_predictions( + pred, threshold=thresh + ) + binarized_masks = (predicted_masks >= mask_threshold).to(torch.uint8).cpu().numpy() + + if return_scores: + return predicted_masks, predicted_boxes, binarized_masks, predicted_scores return predicted_masks, predicted_boxes, binarized_masks def thresholded_predictions(pred, threshold=0.7): """ Get masks and boxes for those above threshold """ - numels = len(torch.where(pred['scores'] >= threshold)[0]) - masks = pred['masks'][:numels].squeeze() - boxes = pred['boxes'][:numels] - - return masks, boxes \ No newline at end of file + keep = pred['scores'] >= threshold + masks = pred['masks'][keep, 0] + boxes = pred['boxes'][keep] + scores = pred['scores'][keep] + + return masks, boxes, scores diff --git a/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb b/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb index e8c2b366d..2f5b7d968 100644 --- a/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb +++ b/caiman/source_extraction/volpy/mrcnn/mrcnn_training.ipynb @@ -36,18 +36,22 @@ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import os\n", - "from skimage.color import rgb2gray, gray2rgb\n", "import torch\n", + "import torchvision\n", "from torch.optim.lr_scheduler import CyclicLR\n", - "from torch.utils.data import Dataset, DataLoader\n", - "from torchvision import tv_tensors\n", - "from tqdm import tqdm\n", + "from torch.utils.data import DataLoader\n", "\n", "from config import Config\n", - "from model import get_model_instance_segmentation, mrcnn_inference, thresholded_predictions \n", - "from neurons import NeuronsDataset, train_one_epoch, validate, perform_final_evaluation\n", - "from utils import ScaleImage, collate_fn, data_transform, f1_score, nf_match_neurons_in_binary_masks, normalize_image\n", - "from visualize import apply_masks, draw_boxes, vp_load_image" + "from model import get_model_instance_segmentation\n", + "from neurons import (\n", + " NeuronsDataset,\n", + " _atomic_torch_save,\n", + " _check_output_directory,\n", + " perform_final_evaluation,\n", + " train_one_epoch,\n", + " validate,\n", + ")\n", + "from utils import collate_fn, data_transform" ] }, { @@ -86,12 +90,20 @@ " ... \n", "\n", "### Config \n", - "The base configuration class 'Config' from 'config.py' contains the variables necessary for training and validation on the Volpy Dataset. The following 'DATASET_PATH' should be directed to 'volpy_training_data'. \n", + "The base configuration class `Config` from `config.py` contains the variables necessary for training and validation on the VolPy dataset. By default it reads training data from `caiman_datadir()/volpy_training_data` and writes checkpoints to `caiman_datadir()/model`. CaImAn's data directory can be changed with `CAIMAN_DATA`; the two VolPy locations can also be overridden independently with `CAIMAN_VOLPY_TRAINING_DATA` and `CAIMAN_VOLPY_MODEL_DIR`.\n", + "\n", + "For data or model directories outside the standard CaImAn data directory, set portable environment variables before starting Jupyter (replace the example placeholders with paths appropriate for your system):\n", + "\n", + " export CAIMAN_DATA=/path/to/caiman_data\n", + " export CAIMAN_VOLPY_TRAINING_DATA=/path/to/volpy_training_data\n", + " export CAIMAN_VOLPY_MODEL_DIR=/path/to/new/model_output_directory\n", + "\n", + "Training saves `mrcnn_latest.pt` and `volpy_train_history.pt` after every completed epoch, periodic `mrcnn_epoch_N.pt` snapshots according to `SAVE_FREQ`, and an epoch-numbered checkpoint for the final epoch. Existing training artifacts are protected by default; select a new `CAIMAN_VOLPY_MODEL_DIR` for a new run, or set `config.ALLOW_OVERWRITE = True` deliberately.\n", "\n", " Config: \n", " # Paths\n", - " DATASET_PATH = r'~./volpy_training_data/'\n", - " MODEL_SAVE_DIR = r'~/volpy_models/'\n", + " DATA_DIR = caiman_datadir()/volpy_training_data\n", + " MODEL_SAVE_DIR = caiman_datadir()/model\n", "\n", " # Model and Training Hyperparameters\n", " NUM_CLASSES = 1 + 1 # Background + Neuron\n", @@ -106,7 +118,8 @@ " # IMAGES_PER_GPU = 2\n", " RANDOM_SPLIT = False # True for random split, False for fixed split from map below.\n", " NUM_TEST_RANDOM = 8\n", - " NUM_TORCH_WORKERS = 4 \n", + " NUM_TORCH_WORKERS = 4\n", + " RANDOM_SEED = 42\n", " DATASET_REGION_MAP = {\n", " 'HPC': [0, 1, 2, 3],\n", " 'L1': [12, 13, 14],\n", @@ -118,7 +131,7 @@ "\n", " # Logging and Saving Frequency\n", " PRINT_FREQ = 1 \n", - " SAVE_FREQ = 20 \n", + " SAVE_FREQ = 5\n", "\n", "### Dataset \n", "\n", @@ -153,9 +166,9 @@ " transforms.append(T.SanitizeBoundingBoxes(min_size=2))\n", "\n", "#### Additional Training Setup:\n", - "Best Validation indices: [ 0, 1, 2, 3, 12, 13, 14, 21] \n", + "Validation indices: [0, 1, 2, 3, 12, 13, 14, 21]\n", "\n", - "Best Training indices:[4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19, 20, 22, 23] " + "Training indices: [4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19, 20, 22, 23]" ] }, { @@ -166,35 +179,66 @@ "outputs": [], "source": [ "config = Config()\n", - "\"\"\" Main function to run the training and validation pipeline.\"\"\"\n", - "os.makedirs(config.MODEL_SAVE_DIR, exist_ok=True)\n", - "\n", - "print(\"Loading datasets...\")\n", + "if config.NUM_EPOCHS < 1:\n", + " raise ValueError('NUM_EPOCHS must be at least 1')\n", + "if config.SAVE_FREQ < 1:\n", + " raise ValueError('SAVE_FREQ must be at least 1')\n", + "_check_output_directory(\n", + " config.MODEL_SAVE_DIR,\n", + " config.ALLOW_OVERWRITE,\n", + " num_epochs=config.NUM_EPOCHS,\n", + " save_freq=config.SAVE_FREQ,\n", + ")\n", + "print(f'Saving training artifacts to: {os.path.abspath(config.MODEL_SAVE_DIR)}')\n", + "config.display()\n", + "\n", + "np.random.seed(config.RANDOM_SEED)\n", + "torch.manual_seed(config.RANDOM_SEED)\n", + "\n", + "print('Loading datasets...')\n", "dataset_train = NeuronsDataset(config.DATA_DIR, data_transform(train=True))\n", "dataset_val = NeuronsDataset(config.DATA_DIR, data_transform(train=False))\n", "\n", "if config.RANDOM_SPLIT:\n", - " print(\"Using random split for train/validation sets.\")\n", - " indices = list(range(len(dataset_train)))\n", - " np.random.shuffle(indices)\n", + " print('Using random train/validation split.')\n", + " indices = np.random.default_rng(config.RANDOM_SEED).permutation(len(dataset_train)).tolist()\n", " train_indices = indices[:-config.NUM_TEST_RANDOM]\n", " val_indices = indices[-config.NUM_TEST_RANDOM:]\n", "else:\n", - " print(\"Using fixed split based on DATASET_REGION_MAP.\")\n", + " print('Using fixed split from DATASET_REGION_MAP.')\n", " train_indices = config.DATASET_REGION_MAP['Train']\n", - " val_indices = [idx for region, inds in config.DATASET_REGION_MAP.items() if region != 'Train' for idx in inds]\n", - " \n", - "val_indices_path = os.path.join(config.MODEL_SAVE_DIR, 'validation_indices.npy')\n", - "np.save(val_indices_path, val_indices)\n", - "print(f\"Validation indices for this run have been saved to {val_indices_path}\")\n", - "\n", - "dataset_train = torch.utils.data.Subset(dataset_train, train_indices)\n", - "dataset_val = torch.utils.data.Subset(dataset_val, val_indices)\n", + " val_indices = [\n", + " idx\n", + " for region, region_indices in config.DATASET_REGION_MAP.items()\n", + " if region != 'Train'\n", + " for idx in region_indices\n", + " ]\n", "\n", - "data_loader_train = DataLoader(dataset_train, batch_size=config.BATCH_SIZE, shuffle=True,\n", - " num_workers=config.NUM_TORCH_WORKERS, collate_fn=collate_fn)\n", - "data_loader_val = DataLoader(dataset_val, batch_size=1, shuffle=False,\n", - " num_workers=config.NUM_TORCH_WORKERS, collate_fn=collate_fn)" + "val_indices_path = os.path.join(config.MODEL_SAVE_DIR, 'validation_indices.npy')\n", + "temporary_indices_path = f'{val_indices_path}.tmp.npy'\n", + "np.save(temporary_indices_path, val_indices)\n", + "os.replace(temporary_indices_path, val_indices_path)\n", + "print(f'Validation indices saved to {val_indices_path}')\n", + "\n", + "train_dataset = torch.utils.data.Subset(dataset_train, train_indices)\n", + "val_dataset = torch.utils.data.Subset(dataset_val, val_indices)\n", + "\n", + "shuffle_generator = torch.Generator().manual_seed(config.RANDOM_SEED)\n", + "data_loader_train = DataLoader(\n", + " train_dataset,\n", + " batch_size=config.BATCH_SIZE,\n", + " shuffle=True,\n", + " generator=shuffle_generator,\n", + " num_workers=config.NUM_TORCH_WORKERS,\n", + " collate_fn=collate_fn,\n", + ")\n", + "data_loader_val = DataLoader(\n", + " val_dataset,\n", + " batch_size=1,\n", + " shuffle=False,\n", + " num_workers=config.NUM_TORCH_WORKERS,\n", + " collate_fn=collate_fn,\n", + ")" ] }, { @@ -203,10 +247,10 @@ "metadata": {}, "source": [ "### Model\n", - "We use a model pre-trained on the COCO dataset, and fine-tune the last layer. \n", + "We start from torchvision's COCO-pretrained Mask R-CNN FPN-v2 model, replace its box and mask predictors for background-plus-neuron classification, and fine-tune the trainable layers. \n", "\n", "### Optimizer + lr scheduler\n", - "We use the SGD optimizer and a CycleLR scheduler " + "We use the SGD optimizer and a CyclicLR scheduler." ] }, { @@ -216,18 +260,26 @@ "metadata": {}, "outputs": [], "source": [ - "# Model\n", + "# Start from torchvision's COCO-pretrained Mask R-CNN and replace its heads\n", + "# with the two-class (background + neuron) VolPy heads.\n", "model = get_model_instance_segmentation(config.NUM_CLASSES)\n", "model.to(device)\n", "\n", - "# Optimizer + lr scheduler\n", - "params = [p for p in model.parameters() if p.requires_grad]\n", - "optimizer = torch.optim.SGD(params, lr=config.MAX_LR, momentum=0.9, weight_decay=0.0001) \n", - "lr_scheduler = CyclicLR(optimizer, base_lr=config.BASE_LR, # Initial learning rate which is the lower boundary in the cycle for each parameter group\n", - " max_lr=config.MAX_LR, # Upper learning rate boundaries in the cycle for each parameter group\n", - " step_size_up=config.STEP_SIZE_UP, # Number of training iterations in the increasing half of a cycle\n", - " step_size_down=config.STEP_SIZE_DOWN,\n", - " mode=\"triangular2\")" + "params = [parameter for parameter in model.parameters() if parameter.requires_grad]\n", + "optimizer = torch.optim.SGD(\n", + " params,\n", + " lr=config.MAX_LR,\n", + " momentum=0.9,\n", + " weight_decay=0.0001,\n", + ")\n", + "lr_scheduler = CyclicLR(\n", + " optimizer,\n", + " base_lr=config.BASE_LR,\n", + " max_lr=config.MAX_LR,\n", + " step_size_up=config.STEP_SIZE_UP,\n", + " step_size_down=config.STEP_SIZE_DOWN,\n", + " mode='triangular2',\n", + ")" ] }, { @@ -246,31 +298,65 @@ "outputs": [], "source": [ "all_train_losses, all_val_losses, all_lrs = [], [], []\n", - "print(f\"**TRAIN {config.NUM_EPOCHS} epochs. PRINT every {config.PRINT_FREQ} epoch(s). \"\n", - " f\"SAVE every {config.SAVE_FREQ} epoch(s).**\")\n", + "history_path = os.path.join(config.MODEL_SAVE_DIR, 'volpy_train_history.pt')\n", + "latest_path = os.path.join(config.MODEL_SAVE_DIR, 'mrcnn_latest.pt')\n", + "final_model_path = os.path.join(\n", + " config.MODEL_SAVE_DIR, f'mrcnn_epoch_{config.NUM_EPOCHS}.pt'\n", + ")\n", + "print(\n", + " f'**TRAIN {config.NUM_EPOCHS} epochs. '\n", + " f'PRINT every {config.PRINT_FREQ} epoch(s). '\n", + " f'SAVE every {config.SAVE_FREQ} epoch(s).**'\n", + ")\n", "\n", "for epoch in range(config.NUM_EPOCHS):\n", " train_loss = train_one_epoch(model, optimizer, data_loader_train, device, epoch)\n", " val_loss = validate(model, data_loader_val, device, epoch)\n", - " current_lr = optimizer.param_groups[0][\"lr\"]\n", + " current_lr = optimizer.param_groups[0]['lr']\n", "\n", " all_train_losses.append(train_loss)\n", " all_val_losses.append(val_loss)\n", " all_lrs.append(current_lr)\n", - "\n", " lr_scheduler.step()\n", "\n", - " if (epoch + 1) % config.PRINT_FREQ == 0:\n", - " print(f\"Epoch {epoch+1}/{config.NUM_EPOCHS} | Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, LR: {current_lr:.6f}\")\n", - "\n", - " if (epoch + 1) % config.SAVE_FREQ == 0:\n", - " model_path = os.path.join(config.MODEL_SAVE_DIR, f'mrcnn_epoch_{epoch+1}.pt')\n", - " torch.save(model.state_dict(), model_path)\n", - " print(f\"\\t Model saved to {model_path}\")\n", - "\n", - "history = {'train_loss': all_train_losses, 'val_loss': all_val_losses, 'lr': all_lrs}\n", - "torch.save(history, os.path.join(config.MODEL_SAVE_DIR, 'volpy_train_history.pt'))\n", - "print(\"\\nDONE!\")" + " completed_epoch = epoch + 1\n", + " history = {\n", + " 'train_loss': all_train_losses,\n", + " 'val_loss': all_val_losses,\n", + " 'lr': all_lrs,\n", + " }\n", + " checkpoint = {\n", + " 'model_state_dict': model.state_dict(),\n", + " 'optimizer_state_dict': optimizer.state_dict(),\n", + " 'scheduler_state_dict': lr_scheduler.state_dict(),\n", + " 'epoch': completed_epoch,\n", + " 'config': config.to_dict(),\n", + " 'torch_version': str(torch.__version__),\n", + " 'torchvision_version': str(torchvision.__version__),\n", + " 'train_indices': train_indices,\n", + " 'validation_indices': val_indices,\n", + " 'history': history,\n", + " }\n", + "\n", + " # These writes are atomic: an interrupted write cannot replace a good checkpoint.\n", + " _atomic_torch_save(checkpoint, latest_path)\n", + " _atomic_torch_save(history, history_path)\n", + "\n", + " if completed_epoch % config.PRINT_FREQ == 0:\n", + " print(\n", + " f'Epoch {completed_epoch}/{config.NUM_EPOCHS} | '\n", + " f'Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, '\n", + " f'LR: {current_lr:.6f}'\n", + " )\n", + "\n", + " if completed_epoch % config.SAVE_FREQ == 0 or completed_epoch == config.NUM_EPOCHS:\n", + " model_path = os.path.join(\n", + " config.MODEL_SAVE_DIR, f'mrcnn_epoch_{completed_epoch}.pt'\n", + " )\n", + " _atomic_torch_save(checkpoint, model_path)\n", + " print(f'Checkpoint saved to {model_path}')\n", + "\n", + "print(f'DONE! Final checkpoint: {final_model_path}')" ] }, { @@ -340,15 +426,12 @@ "metadata": {}, "outputs": [], "source": [ - "\"\"\"Loads a trained model and runs inference on the validation set.\"\"\"\n", "val_indices_path = os.path.join(config.MODEL_SAVE_DIR, 'validation_indices.npy')\n", - " \n", - "val_indices = np.load(val_indices_path)\n", - "\n", - "full_dataset = NeuronsDataset(config.DATA_DIR, data_transform(train=False))\n", - "dataset_val = torch.utils.data.Subset(full_dataset, val_indices)\n", - "data_loader_val = DataLoader(dataset_val, batch_size=1, shuffle=False, num_workers=config.NUM_TORCH_WORKERS, collate_fn=collate_fn)\n", + "if not os.path.exists(val_indices_path):\n", + " raise FileNotFoundError(f'Validation indices not found at {val_indices_path}')\n", "\n", + "saved_val_indices = np.load(val_indices_path)\n", + "print(f'Evaluating {len(saved_val_indices)} validation images')\n", "perform_final_evaluation(model, config, device, plot_results=True)" ] }, diff --git a/caiman/source_extraction/volpy/mrcnn/neurons.py b/caiman/source_extraction/volpy/mrcnn/neurons.py index 328ceb305..2aef5b14c 100644 --- a/caiman/source_extraction/volpy/mrcnn/neurons.py +++ b/caiman/source_extraction/volpy/mrcnn/neurons.py @@ -11,26 +11,82 @@ import matplotlib.pyplot as plt import os -import sys +import tempfile import numpy as np from skimage.color import gray2rgb -import skimage.draw -from skimage.draw import polygon2mask import torch import torch.nn as nn -from torch.utils.data import Dataset, DataLoader +from torch.utils.data import DataLoader import torchvision from torchvision import tv_tensors from torch.optim.lr_scheduler import CyclicLR from torchvision.transforms.v2 import functional as F -import torchvision.transforms.v2 as T from torchvision.ops.boxes import masks_to_boxes from tqdm import tqdm -from typing import List, Dict, Any from caiman.source_extraction.volpy.mrcnn.config import Config -from caiman.source_extraction.volpy.mrcnn.model import get_model_instance_segmentation, mrcnn_inference -from caiman.source_extraction.volpy.mrcnn.utils import ScaleImage, create_mask, collate_fn, data_transform, nf_match_neurons_in_binary_masks, normalize_image +from caiman.source_extraction.volpy.mrcnn.model import ( + get_model_instance_segmentation, + load_mrcnn_weights, + mrcnn_inference, +) +from caiman.source_extraction.volpy.mrcnn.utils import ( + collate_fn, + create_mask, + data_transform, + nf_match_neurons_in_binary_masks, + normalize_image, + prepare_mrcnn_image, +) + + +def _atomic_torch_save(value, path): + """Write a torch artifact atomically so interrupted writes do not replace a good file.""" + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, exist_ok=True) + fd, temporary_path = tempfile.mkstemp( + prefix=f'.{os.path.basename(path)}.', suffix='.tmp', dir=directory + ) + os.close(fd) + try: + torch.save(value, temporary_path) + os.replace(temporary_path, path) + finally: + if os.path.exists(temporary_path): + os.remove(temporary_path) + + +def _check_output_directory(path, allow_overwrite=False, num_epochs=None, save_freq=None): + """Create a writable output directory and protect existing training artifacts.""" + os.makedirs(path, exist_ok=True) + artifact_names = { + 'mrcnn_latest.pt', + 'validation_indices.npy', + 'volpy_train_history.pt', + } + if num_epochs is not None: + if save_freq is None or num_epochs < 1 or save_freq < 1: + raise ValueError("num_epochs and save_freq must both be positive") + artifact_names.update( + f'mrcnn_epoch_{epoch}.pt' + for epoch in range(save_freq, num_epochs + 1, save_freq) + ) + artifact_names.add(f'mrcnn_epoch_{num_epochs}.pt') + existing_artifacts = sorted(artifact_names.intersection(os.listdir(path))) + else: + existing_artifacts = sorted( + name for name in os.listdir(path) + if name in artifact_names or (name.startswith('mrcnn_epoch_') and name.endswith('.pt')) + ) + if existing_artifacts and not allow_overwrite: + raise FileExistsError( + f"Training artifacts already exist in {os.path.abspath(path)}: " + f"{existing_artifacts}. Choose a new MODEL_SAVE_DIR or set " + "config.ALLOW_OVERWRITE = True explicitly." + ) + fd, probe_path = tempfile.mkstemp(prefix='.volpy-write-test-', dir=path) + os.close(fd) + os.remove(probe_path) # Dataset class NeuronsDataset(torch.utils.data.Dataset): @@ -51,9 +107,26 @@ def __init__(self, root, transforms): self.root = root self.transforms = transforms - # load all image files, sorting them to ensure that they are aligned - self.image_filenames = list(sorted(os.listdir(os.path.join(self.root, "images")))) - self.mask_filenames = list(sorted(os.listdir(os.path.join(self.root, "masks")))) + image_filenames = sorted(os.listdir(os.path.join(self.root, "images"))) + mask_filenames = sorted(os.listdir(os.path.join(self.root, "masks"))) + + def sample_stem(filename): + stem = os.path.splitext(filename)[0] + return stem[:-5] if stem.endswith('_mask') else stem + + images_by_stem = {sample_stem(name): name for name in image_filenames} + masks_by_stem = {sample_stem(name): name for name in mask_filenames} + if images_by_stem.keys() != masks_by_stem.keys(): + missing_masks = sorted(images_by_stem.keys() - masks_by_stem.keys()) + missing_images = sorted(masks_by_stem.keys() - images_by_stem.keys()) + raise ValueError( + "VolPy image/mask filenames do not match. " + f"Missing masks for {missing_masks}; missing images for {missing_images}" + ) + + sample_stems = sorted(images_by_stem) + self.image_filenames = [images_by_stem[stem] for stem in sample_stems] + self.mask_filenames = [masks_by_stem[stem] for stem in sample_stems] def __getitem__(self, idx): """ @@ -65,7 +138,7 @@ def __getitem__(self, idx): Returns: A tuple containing: - image (tv_tensors.Image): The image tensor. - - target (Dict[str, Any]): A dictionary containing the masks, bounding boxes, + - target (dict): A dictionary containing the masks, bounding boxes, labels, and other metadata. """ image_id = idx @@ -73,9 +146,7 @@ def __getitem__(self, idx): # Image: (C x H x W) image_path = os.path.join(self.root, "images", self.image_filenames[idx]) image = np.load(image_path)['img'] # mean/mean/corr channels (h w c) - image = torch.from_numpy(image).permute(2,0,1) # convert to tensor and get into pytorch order C x H x W - image = ScaleImage()(image) # scale so it is in 0,1 range - image = tv_tensors.Image(image) + image = prepare_mrcnn_image(image) # Masks: N x H x W mask array (N masks) mask_path = os.path.join(self.root, "masks", self.mask_filenames[idx]) @@ -168,15 +239,24 @@ def validate(model: nn.Module, data_loader: torch.utils.data.DataLoader, Returns: float: The average validation loss for the epoch. """ + was_training = model.training model.train() + # Torchvision detection models only return losses in training mode. Keep + # BatchNorm frozen so validation data cannot update running statistics. + for module in model.modules(): + if isinstance(module, nn.modules.batchnorm._BatchNorm): + module.eval() val_epoch_loss = 0 - with torch.no_grad(): - for images, targets in tqdm(data_loader, desc=f"Epoch {epoch+1} [val]"): - images = list(image.to(device) for image in images) - targets = [{k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in t.items()} for t in targets] - loss_dict = model(images, targets) - losses = sum(loss for loss in loss_dict.values()) - val_epoch_loss += losses.item() + try: + with torch.no_grad(): + for images, targets in tqdm(data_loader, desc=f"Epoch {epoch+1} [val]"): + images = list(image.to(device) for image in images) + targets = [{k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in t.items()} for t in targets] + loss_dict = model(images, targets) + losses = sum(loss for loss in loss_dict.values()) + val_epoch_loss += losses.item() + finally: + model.train(was_training) return val_epoch_loss / len(data_loader) def perform_final_evaluation(model: nn.Module, config, device: torch.device, plot_results: bool = False): @@ -222,6 +302,7 @@ def perform_final_evaluation(model: nn.Module, config, device: torch.device, plo # Run inference to get predicted masks _, _, binarized_masks = mrcnn_inference(model, img=vp_im.to(device), thresh=config.INFERENCE_THRESHOLD, + mask_threshold=config.MASK_THRESHOLD, eval_transform=data_transform(train=False), device=device) # Compare GT and Predicted Masks @@ -257,9 +338,22 @@ def perform_final_evaluation(model: nn.Module, config, device: torch.device, plo def train_validate(config, plot_results=False): """ Main function to run the training and validation pipeline.""" - os.makedirs(config.MODEL_SAVE_DIR, exist_ok=True) + if config.NUM_EPOCHS < 1: + raise ValueError("NUM_EPOCHS must be at least 1") + if config.SAVE_FREQ < 1: + raise ValueError("SAVE_FREQ must be at least 1") + _check_output_directory( + config.MODEL_SAVE_DIR, + getattr(config, 'ALLOW_OVERWRITE', False), + num_epochs=config.NUM_EPOCHS, + save_freq=config.SAVE_FREQ, + ) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Using device: {device}") + print(f"Saving training artifacts to: {os.path.abspath(config.MODEL_SAVE_DIR)}") + + np.random.seed(config.RANDOM_SEED) + torch.manual_seed(config.RANDOM_SEED) print("Loading datasets...") dataset_train = NeuronsDataset(config.DATA_DIR, data_transform(train=True)) @@ -267,8 +361,7 @@ def train_validate(config, plot_results=False): if config.RANDOM_SPLIT: print("Using random split for train/validation sets.") - indices = list(range(len(dataset_train))) - np.random.shuffle(indices) + indices = np.random.default_rng(config.RANDOM_SEED).permutation(len(dataset_train)).tolist() train_indices = indices[:-config.NUM_TEST_RANDOM] val_indices = indices[-config.NUM_TEST_RANDOM:] else: @@ -277,14 +370,23 @@ def train_validate(config, plot_results=False): val_indices = [idx for region, inds in config.DATASET_REGION_MAP.items() if region != 'Train' for idx in inds] val_indices_path = os.path.join(config.MODEL_SAVE_DIR, 'validation_indices.npy') - np.save(val_indices_path, val_indices) + temporary_indices_path = f'{val_indices_path}.tmp.npy' + np.save(temporary_indices_path, val_indices) + os.replace(temporary_indices_path, val_indices_path) print(f"Validation indices for this run have been saved to {val_indices_path}") dataset_train = torch.utils.data.Subset(dataset_train, train_indices) dataset_val = torch.utils.data.Subset(dataset_val, val_indices) - data_loader_train = DataLoader(dataset_train, batch_size=config.BATCH_SIZE, shuffle=True, - num_workers=config.NUM_TORCH_WORKERS, collate_fn=collate_fn) + shuffle_generator = torch.Generator().manual_seed(config.RANDOM_SEED) + data_loader_train = DataLoader( + dataset_train, + batch_size=config.BATCH_SIZE, + shuffle=True, + generator=shuffle_generator, + num_workers=config.NUM_TORCH_WORKERS, + collate_fn=collate_fn, + ) data_loader_val = DataLoader(dataset_val, batch_size=1, shuffle=False, num_workers=config.NUM_TORCH_WORKERS, collate_fn=collate_fn) @@ -298,6 +400,8 @@ def train_validate(config, plot_results=False): mode="triangular2") all_train_losses, all_val_losses, all_lrs = [], [], [] + history_path = os.path.join(config.MODEL_SAVE_DIR, 'volpy_train_history.pt') + latest_path = os.path.join(config.MODEL_SAVE_DIR, 'mrcnn_latest.pt') print(f"**TRAIN {config.NUM_EPOCHS} epochs. PRINT every {config.PRINT_FREQ} epoch(s). " f"SAVE every {config.SAVE_FREQ} epoch(s).**") @@ -315,42 +419,60 @@ def train_validate(config, plot_results=False): if (epoch + 1) % config.PRINT_FREQ == 0: print(f"Epoch {epoch+1}/{config.NUM_EPOCHS} | Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, LR: {current_lr:.6f}") - if (epoch + 1) % config.SAVE_FREQ == 0: + completed_epoch = epoch + 1 + history = {'train_loss': all_train_losses, 'val_loss': all_val_losses, 'lr': all_lrs} + checkpoint = { + 'model_state_dict': model.state_dict(), + 'optimizer_state_dict': optimizer.state_dict(), + 'scheduler_state_dict': lr_scheduler.state_dict(), + 'epoch': completed_epoch, + 'config': config.to_dict(), + 'torch_version': str(torch.__version__), + 'torchvision_version': str(torchvision.__version__), + 'train_indices': train_indices, + 'validation_indices': val_indices, + 'history': history, + } + _atomic_torch_save(checkpoint, latest_path) + _atomic_torch_save(history, history_path) + print(f"\tLatest checkpoint saved to {latest_path}") + + if completed_epoch % config.SAVE_FREQ == 0 or completed_epoch == config.NUM_EPOCHS: model_path = os.path.join(config.MODEL_SAVE_DIR, f'mrcnn_epoch_{epoch+1}.pt') - torch.save(model.state_dict(), model_path) + _atomic_torch_save(checkpoint, model_path) print(f"\tModel saved to {model_path}") history = {'train_loss': all_train_losses, 'val_loss': all_val_losses, 'lr': all_lrs} - torch.save(history, os.path.join(config.MODEL_SAVE_DIR, 'volpy_train_history.pt')) - print("\nDONE!") - - # Plotting results - plt.figure(figsize=(12, 5)) - plt.subplot(1, 2, 1) - plt.plot(history['train_loss'], label='Train Loss') - plt.plot(history['val_loss'], label='Validation Loss') - plt.legend() - plt.grid(True) - plt.xlabel('Epoch') - plt.ylabel('Loss') - plt.title('Training & Validation Loss') - - plt.subplot(1, 2, 2) - plt.plot(history['lr']) - plt.xlabel('Epoch') - plt.ylabel('Learning Rate') - plt.title('Learning Rate Schedule') - plt.grid(True) - - plt.tight_layout() - plt.show() + print(f"\nDONE! Final checkpoint: {model_path}") + + if plot_results: + plt.figure(figsize=(12, 5)) + plt.subplot(1, 2, 1) + plt.plot(history['train_loss'], label='Train Loss') + plt.plot(history['val_loss'], label='Validation Loss') + plt.legend() + plt.grid(True) + plt.xlabel('Epoch') + plt.ylabel('Loss') + plt.title('Training & Validation Loss') + + plt.subplot(1, 2, 2) + plt.plot(history['lr']) + plt.xlabel('Epoch') + plt.ylabel('Learning Rate') + plt.title('Learning Rate Schedule') + plt.grid(True) + + plt.tight_layout() + plt.show() + return model, history def run_inference(config, plot_results=True): """Loads a trained model and runs inference on the validation set.""" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Using device: {device}") - model = get_model_instance_segmentation(config.NUM_CLASSES) + model = get_model_instance_segmentation(config.NUM_CLASSES, pretrained=False) model_path = os.path.join(config.MODEL_SAVE_DIR, f'mrcnn_epoch_{config.NUM_EPOCHS}.pt') if not os.path.exists(model_path): @@ -358,7 +480,7 @@ def run_inference(config, plot_results=True): return print(f"Loading model from {model_path}") - model.load_state_dict(torch.load(model_path)) + load_mrcnn_weights(model, model_path, device) model.to(device) val_indices_path = os.path.join(config.MODEL_SAVE_DIR, 'validation_indices.npy') @@ -372,7 +494,7 @@ def run_inference(config, plot_results=True): dataset_val = torch.utils.data.Subset(full_dataset, val_indices) data_loader_val = DataLoader(dataset_val, batch_size=1, shuffle=False, num_workers=config.NUM_TORCH_WORKERS, collate_fn=collate_fn) - perform_final_evaluation(model, config, device, plot_results=True) + perform_final_evaluation(model, config, device, plot_results=plot_results) if __name__ == '__main__': import argparse @@ -389,8 +511,7 @@ def run_inference(config, plot_results=True): config.RANDOM_SPLIT = True if args.mode == 'train': - # Call evaluation at the end of training, passing the plotting flag - train_validate(config, plot_results=args.plot_results) + train_validate(config, plot_results=args.plot_results) elif args.mode == 'infer': # Call inference, passing the plotting flag run_inference(config, plot_results=args.plot_results) diff --git a/caiman/source_extraction/volpy/mrcnn/utils.py b/caiman/source_extraction/volpy/mrcnn/utils.py index 39ae8dc07..42101cb64 100644 --- a/caiman/source_extraction/volpy/mrcnn/utils.py +++ b/caiman/source_extraction/volpy/mrcnn/utils.py @@ -20,21 +20,36 @@ from skimage.draw import polygon2mask import time import torch -from torchvision.transforms.v2 import functional as F +from torchvision import tv_tensors import torchvision.transforms.v2 as T from typing import Any, Optional -from caiman.base.rois import norm_nrg - - class ScaleImage: """ Scale image so it is between 0-1: works on floats only """ def __call__(self, img): + img = img.to(torch.float32) min_val, max_val = img.min(), img.max() - range = max_val - min_val - return F.normalize_image(img, mean=[min_val, min_val, min_val], std=[range, range, range]) + value_range = max_val - min_val + if value_range == 0: + return torch.zeros_like(img) + return (img - min_val) / value_range + + +def prepare_mrcnn_image(img): + """Convert an HxW or HxWx3 summary image to a normalized CHW tensor.""" + img = np.asarray(img) + if img.ndim == 2: + img = np.repeat(img[..., None], 3, axis=-1) + elif img.ndim == 3 and img.shape[-1] == 1: + img = np.repeat(img, 3, axis=-1) + + if img.ndim != 3 or img.shape[-1] != 3: + raise ValueError(f"Expected an HxW or HxWx3 image, got shape {img.shape}") + + image = torch.from_numpy(np.array(img, dtype=np.float32, copy=True)).permute(2, 0, 1) + return tv_tensors.Image(ScaleImage()(image)) def bounding_box(mask_coords): """ @@ -129,7 +144,8 @@ def data_transform(train: bool = False): transforms.append(T.GaussianBlur(kernel_size=(5, 5), sigma=(0.001, 0.3))) transforms.append(T.SanitizeBoundingBoxes(min_size=2)) - transforms.append(T.ToDtype(torch.float32, scale=False)) + transforms.append(T.ToDtype(torch.float32, scale=True)) + transforms.append(T.ToPureTensor()) return T.Compose(transforms) @@ -391,7 +407,11 @@ def nf_match_neurons_in_binary_masks(masks_gt, # find the distance between each masks D = distance_masks([A_ben, A_cnmf], [cm_ben, cm_cnmf], min_dist, enclosed_thr=enclosed_thr) - level = 0.98 + # These inputs are binary instance masks. Contour them directly at the + # boundary between background (0) and foreground (1). Passing them + # through ``norm_nrg`` makes both values equal to 1 with the current + # tie-preserving implementation, which leaves no visible contour. + level = 0.5 matches, costs = find_matches(D, print_assignment=print_assignment) matches = matches[0] @@ -434,8 +454,10 @@ def nf_match_neurons_in_binary_masks(masks_gt, plt.imshow(Cn, vmin=lp, vmax=hp, cmap=cmap) #import pdb #pdb.set_trace() - [plt.contour(norm_nrg(mm), levels=[level], colors=colors[1], linewidths=1) for mm in masks_comp[idx_tp_comp]] - [plt.contour(norm_nrg(mm), levels=[level], colors=colors[0], linewidths=1) for mm in masks_gt[idx_tp_gt]] + for mm in masks_comp[idx_tp_comp]: + plt.contour(mm, levels=[level], colors=colors[1], linewidths=1) + for mm in masks_gt[idx_tp_gt]: + plt.contour(mm, levels=[level], colors=colors[0], linewidths=1) if labels is None: plt.title('MATCHES') else: @@ -447,16 +469,18 @@ def nf_match_neurons_in_binary_masks(masks_gt, plt.imshow(Cn, vmin=lp, vmax=hp, cmap=cmap) - [plt.contour(norm_nrg(mm), levels=[level], colors=colors[1], linewidths=1) for mm in masks_comp[idx_fp_comp]] - [plt.contour(norm_nrg(mm), levels=[level], colors=colors[0], linewidths=1) for mm in masks_gt[idx_fn_gt]] + for mm in masks_comp[idx_fp_comp]: + plt.contour(mm, levels=[level], colors=colors[1], linewidths=1) + for mm in masks_gt[idx_fn_gt]: + plt.contour(mm, levels=[level], colors=colors[0], linewidths=1) if labels is None: plt.title(f'FALSE POSITIVE ({colors[1][0]}), FALSE NEGATIVE ({colors[0][0]})') else: plt.title(labels[1] + f'({colors[1][0]}), ' + labels[0] + f'({colors[0][0]})') #pl.legend(handles=[ses_1, ses_2]) plt.axis('off') - plt.show() plt.tight_layout() + plt.show() #except Exception as e: # logging.warning("not able to plot precision recall: graphics failure") # logging.warning(e) diff --git a/caiman/source_extraction/volpy/utils.py b/caiman/source_extraction/volpy/utils.py index 2d3ba857b..3e4107432 100644 --- a/caiman/source_extraction/volpy/utils.py +++ b/caiman/source_extraction/volpy/utils.py @@ -10,16 +10,17 @@ from matplotlib.widgets import Slider import numpy as np import os +from skimage.morphology import disk, erosion import torch -import torchvision import caiman as cm from caiman.external.cell_magic_wand import cell_magic_wand_single_point -from caiman.paths import caiman_datadir - -from caiman.source_extraction.volpy.mrcnn import utils from caiman.source_extraction.volpy.mrcnn.config import Config -from caiman.source_extraction.volpy.mrcnn.model import get_model_instance_segmentation, mrcnn_inference -from caiman.source_extraction.volpy.mrcnn.utils import ScaleImage, data_transform +from caiman.source_extraction.volpy.mrcnn.model import ( + get_model_instance_segmentation, + load_mrcnn_weights, + mrcnn_inference, +) +from caiman.source_extraction.volpy.mrcnn.utils import data_transform, prepare_mrcnn_image def quick_annotation(img, min_radius, max_radius, roughness=2): """ Quick annotation method in VolPy using cell magic wand plugin @@ -95,7 +96,9 @@ def tellme(s): return ROIs -def mrcnn_inference_pytorch(img, size_range, weights_path, display_result=True): +def mrcnn_inference_pytorch(img, size_range, weights_path, display_result=True, + confidence_threshold=None, mask_threshold=None, + box_nms_threshold=None, erosion_radius=None): """ Mask R-CNN inference in VolPy using PyTorch. Args: @@ -111,66 +114,94 @@ def mrcnn_inference_pytorch(img, size_range, weights_path, display_result=True): display_result (bool): If True, the function will plot the result of the inference. - confidence_threshold (float): - The confidence threshold for accepting detected instances. + confidence_threshold (float, optional): + Minimum detection score. Defaults to ``Config.INFERENCE_THRESHOLD``. + + mask_threshold (float, optional): + Probability threshold used to binarize masks. + + box_nms_threshold (float, optional): + IoU threshold for torchvision's final box non-maximum suppression. + + erosion_radius (int, optional): + Radius of the disk used to erode accepted masks. Set to zero to disable. Returns: ROIs: 3-D np.ndarray: A 3-D array of ROIs (# of components, height, width). """ - # Setup Configuration and Device - class InferenceConfig(Config): - GPU_COUNT = 1 - IMAGES_PER_GPU = 1 - NUM_CLASSES = 1 + 1 # background + neuron - DETECTION_MIN_CONFIDENCE = 0.7 # - config = InferenceConfig() + config = Config() + confidence_threshold = (config.INFERENCE_THRESHOLD if confidence_threshold is None + else confidence_threshold) + mask_threshold = config.MASK_THRESHOLD if mask_threshold is None else mask_threshold + box_nms_threshold = (config.BOX_NMS_THRESHOLD if box_nms_threshold is None + else box_nms_threshold) + erosion_radius = (config.MASK_EROSION_RADIUS if erosion_radius is None + else erosion_radius) + + if len(size_range) != 2 or size_range[0] < 0 or size_range[0] >= size_range[1]: + raise ValueError("size_range must contain increasing non-negative radii") + if erosion_radius < 0: + raise ValueError("erosion_radius must be non-negative") device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Using device: {device}") #Load Model and weights - model = get_model_instance_segmentation(num_classes=config.NUM_CLASSES) - model.load_state_dict(torch.load(weights_path, map_location=device)) + model = get_model_instance_segmentation(num_classes=config.NUM_CLASSES, pretrained=False) + load_mrcnn_weights(model, weights_path, device) + model.roi_heads.nms_thresh = box_nms_threshold model.to(device) - model.eval() #Set to evaluation mode + model.eval() # Pre-process Image - img_tensor = torch.from_numpy(img.copy().astype(np.float32)).permute(2, 0, 1) # - img_tensor = img_tensor / 255.0 # Normalize to 0-1 range - img_tv_tensor = torchvision.tv_tensors.Image(img_tensor) + img_tv_tensor = prepare_mrcnn_image(img) # Perform Inference - _, _, binarized_masks = mrcnn_inference( + _, predicted_boxes, binarized_masks, predicted_scores = mrcnn_inference( model=model, img=img_tv_tensor, - thresh=config.DETECTION_MIN_CONFIDENCE, + thresh=confidence_threshold, + mask_threshold=mask_threshold, eval_transform=data_transform(train=False), - device=device + device=device, + return_scores=True, ) # Post-process and Filter by Size if binarized_masks.size == 0: - ROIs = np.empty((0, *img.shape[:2]), dtype=bool) # + ROIs = np.empty((0, *img.shape[:2]), dtype=bool) + display_boxes = np.empty((0, 4), dtype=np.float32) + display_scores = np.empty((0,), dtype=np.float32) else: - mask_areas = binarized_masks.sum(axis=(1, 2)) # + mask_areas = binarized_masks.sum(axis=(1, 2)) selection = np.logical_and(mask_areas > size_range[0] ** 2, - mask_areas < size_range[1] ** 2) # - ROIs = binarized_masks[selection].astype(bool) + mask_areas < size_range[1] ** 2) + ROIs = binarized_masks[selection].astype(bool) + if erosion_radius and len(ROIs): + footprint = disk(erosion_radius) + ROIs = np.stack([erosion(mask, footprint) for mask in ROIs]) + display_boxes = predicted_boxes.detach().cpu().numpy()[selection] + display_scores = predicted_scores.detach().cpu().numpy()[selection] - print(f"Inference complete. Found {ROIs.shape[0]} neurons.") # + print(f"Inference complete. Found {ROIs.shape[0]} neurons.") if display_result: - plt.figure(figsize=(12, 12)) - plt.imshow(img) - # Overlay each ROI with a distinct color - if ROIs.any(): - composite_mask = np.zeros_like(ROIs[0], dtype=float) - for i, roi in enumerate(ROIs): - composite_mask += roi * (i + 1) - plt.imshow(np.ma.masked_where(composite_mask == 0, composite_mask), cmap='nipy_spectral', alpha=0.6) - plt.title(f"PyTorch Predictions ({len(ROIs)} ROIs found)") - plt.axis('off') + from caiman.source_extraction.volpy.mrcnn.visualize import display_instances + _, ax = plt.subplots(1, 1, figsize=(16, 16)) + boxes_yx = display_boxes[:, [1, 0, 3, 2]] + masks_hwn = ROIs.astype(np.uint8).transpose(1, 2, 0) + class_ids = np.ones(len(ROIs), dtype=int) + display_instances( + np.asarray(img) if np.asarray(img).ndim == 3 else np.repeat(np.asarray(img)[..., None], 3, axis=-1), + boxes_yx, + masks_hwn, + class_ids, + ['BG', 'neurons'], + display_scores, + ax=ax, + title=f"PyTorch Predictions ({len(ROIs)} ROIs found)", + ) plt.show() return ROIs diff --git a/caiman/tests/test_mrcnn.py b/caiman/tests/test_mrcnn.py index 108c4ccd1..4aa9f30d7 100644 --- a/caiman/tests/test_mrcnn.py +++ b/caiman/tests/test_mrcnn.py @@ -1,98 +1,163 @@ #!/usr/bin/env python import numpy as np -import os -import h5py import torch -import torch.nn as nn -import torchvision +import matplotlib.pyplot as plt import caiman as cm -from caiman.paths import caiman_datadir -from caiman.utils.utils import download_model, download_demo -from caiman.source_extraction.volpy.mrcnn import neurons -import caiman.source_extraction.volpy.mrcnn.model as modellib - +from caiman.source_extraction.volpy import utils as volpy_utils from caiman.source_extraction.volpy.mrcnn.config import Config -from caiman.source_extraction.volpy.mrcnn.model import get_model_instance_segmentation, mrcnn_inference -from caiman.source_extraction.volpy.mrcnn.utils import ScaleImage, data_transform - -def mrcnn_pytorch(model, img, size_range, confidence_threshold=0.5, - device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')): - """ - Performs inference using the PyTorch Mask R-CNN model and filters the results. - """ - model.to(device) - - img_tensor = torch.from_numpy(img.copy()).permute(2, 0, 1) - img_tensor = ScaleImage()(img_tensor) # Apply the same 0-1 scaling used during training - img_tv_tensor = torchvision.tv_tensors.Image(img_tensor) # Wrap the tensor in the tv_tensors.Image class - - _, _, binarized_masks = mrcnn_inference( - model, - img=img_tv_tensor, - thresh=confidence_threshold, - eval_transform=data_transform(train=False), - device=device +from caiman.source_extraction.volpy.mrcnn.model import ( + mrcnn_inference, + thresholded_predictions, +) +from caiman.source_extraction.volpy.mrcnn.neurons import ( + _atomic_torch_save, + _check_output_directory, + validate, +) +from caiman.source_extraction.volpy.mrcnn.utils import ( + nf_match_neurons_in_binary_masks, + prepare_mrcnn_image, +) +from caiman.utils.utils import download_demo, download_model + + +def _prediction(count, height=8, width=9): + scores = torch.tensor([0.9, 0.6, 0.1])[:count] + return { + 'scores': scores, + 'masks': torch.ones((count, 1, height, width)), + 'boxes': torch.zeros((count, 4)), + } + + +def test_thresholded_predictions_preserves_instance_dimension(): + for count, expected in ((0, 0), (1, 1), (3, 2)): + masks, boxes, scores = thresholded_predictions(_prediction(count), threshold=0.5) + assert masks.shape == (expected, 8, 9) + assert boxes.shape == (expected, 4) + assert scores.shape == (expected,) + + +def test_prepare_mrcnn_image_supports_2d_and_constant_images(): + image = prepare_mrcnn_image(np.full((8, 9), 3.0, dtype=np.float32)) + assert image.shape == (3, 8, 9) + assert image.dtype == torch.float32 + assert torch.count_nonzero(image) == 0 + + +def test_default_split_matches_reference_training_protocol(): + assert Config.DATASET_REGION_MAP == { + 'HPC': [0, 1, 2, 3], + 'L1': [12, 13, 14], + 'TEG': [21], + 'Train': [4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19, 20, 22, 23], + } + + +def test_binary_mask_evaluation_draws_visible_contours(monkeypatch): + mask = np.zeros((1, 20, 20), dtype=np.uint8) + mask[0, 5:10, 6:11] = 1 + contour_inputs = [] + original_contour = plt.contour + + def record_contour(values, *args, **kwargs): + contour_inputs.append((np.asarray(values), kwargs.get('levels'))) + return original_contour(values, *args, **kwargs) + + monkeypatch.setattr(plt, 'contour', record_contour) + monkeypatch.setattr(plt, 'show', lambda: None) + nf_match_neurons_in_binary_masks( + mask, + mask, + plot_results=True, + Cn=np.zeros((20, 20)), + labels=['GT', 'VolPy'], + colors=['red', 'yellow'], + ) + + assert len(contour_inputs) == 2 + assert all(np.array_equal(values, mask[0]) for values, _ in contour_inputs) + assert all(levels == [0.5] for _, levels in contour_inputs) + plt.close('all') + + +def test_mrcnn_inference_keeps_legacy_three_value_contract(): + class FakeModel(torch.nn.Module): + def forward(self, images): + return [_prediction(1, images[0].shape[-2], images[0].shape[-1])] + + image = prepare_mrcnn_image(np.arange(72, dtype=np.float32).reshape(8, 9)) + masks, boxes, binary_masks = mrcnn_inference( + FakeModel(), + image, + eval_transform=lambda value: value, + device=torch.device('cpu'), + thresh=0.5, ) + assert masks.shape == (1, 8, 9) + assert boxes.shape == (1, 4) + assert binary_masks.shape == (1, 8, 9) + + +def test_validation_does_not_update_batch_norm_statistics(): + class LossModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.batch_norm = torch.nn.BatchNorm2d(1) + + def forward(self, images, targets): + value = self.batch_norm(images[0].unsqueeze(0)) + return {'loss': value.sum()} + + model = LossModel() + running_mean = model.batch_norm.running_mean.clone() + data_loader = [([torch.ones((1, 2, 2))], [{}])] + validate(model, data_loader, torch.device('cpu'), epoch=0) + assert torch.equal(model.batch_norm.running_mean, running_mean) + + +def test_atomic_torch_save_replaces_artifact(tmp_path): + artifact_path = tmp_path / 'checkpoint.pt' + _atomic_torch_save({'epoch': 1}, artifact_path) + _atomic_torch_save({'epoch': 2}, artifact_path) + + assert torch.load(artifact_path, weights_only=True) == {'epoch': 2} + assert list(tmp_path.iterdir()) == [artifact_path] + - print(f"Model detected {len(binarized_masks)} raw masks before size filtering.") - - if binarized_masks.size == 0: - ROIs = np.empty((0, *img.shape[:2]), dtype=bool) # - else: - mask_areas = binarized_masks.sum(axis=(1, 2)) # - selection = np.logical_and(mask_areas > size_range[0] ** 2, - mask_areas < size_range[1] ** 2) # - ROIs = binarized_masks[selection].astype(bool) - - ROIs = binarized_masks[selection].astype(bool) - return ROIs - -def test_mrcnn_pytorch(): - """ - Test function for the PyTorch Mask R-CNN neuron detector. - """ - class InferenceConfig(Config): - GPU_COUNT = 1 - IMAGES_PER_GPU = 1 - NUM_CLASSES = 1 + 1 # Number of classes: background + neuron - DETECTION_MIN_CONFIDENCE = 0.7 # Minimum probability value to accept a detected instance. - - config = InferenceConfig() # Load configuration to get model paths - - # Use the PyTorch model weights from the already trained model - weights_path = download_model('mask_rcnn') - if not os.path.exists(weights_path): - raise FileNotFoundError(f"PyTorch model weights not found at: {weights_path}\n" - "Please run the training script first.") - print(f"Using PyTorch weights from: {weights_path}") - - # Load the model architecture and state - device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') - print(f"Using device: {device}") - model = get_model_instance_segmentation(num_classes=config.NUM_CLASSES) - model.load_state_dict(torch.load(weights_path, map_location=device)) - model.eval() - - # Load the same Caiman demo data +def test_training_output_directory_protects_existing_artifacts(tmp_path): + artifact_path = tmp_path / 'mrcnn_epoch_1.pt' + artifact_path.touch() + + with np.testing.assert_raises(FileExistsError): + _check_output_directory(tmp_path) + + _check_output_directory(tmp_path, allow_overwrite=True) + + +def test_training_output_directory_only_blocks_planned_epochs(tmp_path): + (tmp_path / 'mrcnn_epoch_200.pt').touch() + _check_output_directory(tmp_path, num_epochs=100, save_freq=5) + + (tmp_path / 'mrcnn_epoch_100.pt').touch() + with np.testing.assert_raises(FileExistsError): + _check_output_directory(tmp_path, num_epochs=100, save_freq=5) + + +def test_mrcnn_pytorch_demo_inference(): + weights_path = download_model('mask_rcnn') summary_images = cm.load(download_demo('demo_voltage_imaging_summary_images.tif')) - # Run inference - ROIs = mrcnn_pytorch( - model=model, + rois = volpy_utils.mrcnn_inference_pytorch( img=summary_images.transpose([1, 2, 0]), size_range=[5, 22], - confidence_threshold=config.DETECTION_MIN_CONFIDENCE, - device=device + weights_path=weights_path, + display_result=False, ) - print(f"Inference complete. Found {ROIs.shape[0]} neurons.") - # Assert the number of neurons found - # Note: The number of detected neurons might differ from the original TensorFlow model - # Adjust the assertion number based on your model's performance. - assert ROIs.shape[0] == 11, f"Test failed: Expected 14 neurons, but found {ROIs.shape[0]}." #Originally 14 so need to see - print("\nTest passed successfully!") - -if __name__ == "__main__": - test_mrcnn_pytorch() + assert rois.dtype == bool + assert rois.ndim == 3 + assert rois.shape[1:] == summary_images.shape[1:] + assert len(rois) == 14 diff --git a/caiman/tests/test_volpy.py b/caiman/tests/test_volpy.py index 4dd77a0f5..646085b9e 100644 --- a/caiman/tests/test_volpy.py +++ b/caiman/tests/test_volpy.py @@ -2,9 +2,10 @@ import numpy as np import pytest +import matplotlib.pyplot as plt import caiman -from caiman.source_extraction.volpy import spikepursuit +from caiman.source_extraction.volpy import spikepursuit, utils as volpy_utils from caiman.source_extraction.volpy.volparams import volparams @@ -111,3 +112,57 @@ def test_whitened_matched_filter_runs(): assert filtered.shape == (T,) assert np.all(np.isfinite(filtered)) + + +def test_volspike_builds_two_dimensional_context_footprint(monkeypatch): + class ContextFootprintObserved(Exception): + pass + + def inspect_context_footprint(image, footprint): + assert image.shape == (4, 4) + assert footprint.ndim == 2 + # Even dimensions are padded by _shift_footprint_old so that the + # footprint remains centered for skimage.morphology.dilation. + assert footprint.shape == (5, 5) + raise ContextFootprintObserved + + movie_matrix = np.zeros((16, 2), dtype=np.float32) + monkeypatch.setattr( + spikepursuit.cm, + 'load_memmap', + lambda _: (movie_matrix, (4, 4), 2), + ) + monkeypatch.setattr(spikepursuit, 'dilation', inspect_context_footprint) + + roi = np.zeros((4, 4), dtype=bool) + roi[1:3, 1:3] = True + args = {'template_size': 0.02, 'context_size': 4} + + with pytest.raises(ContextFootprintObserved): + spikepursuit.volspike(['movie.mmap', 400, 0, roi, None, args]) + + +def test_view_components_renders_initial_component(monkeypatch): + frame_count = 10 + estimates = { + 'weights': np.ones((2, 4, 4), dtype=float), + 't': np.ones((2, frame_count), dtype=float), + 't_sub': np.full((2, frame_count), 0.5), + 't_rec': np.full((2, frame_count), 0.75), + 'spikes': [np.array([1, 3]), np.array([2, 4])], + 'snr': np.array([2.0, 3.0]), + 'locality': np.array([True, True]), + } + monkeypatch.setattr(plt, 'show', lambda: None) + + volpy_utils.view_components( + estimates, + np.ones((4, 4), dtype=float), + np.array([0, 1]), + ) + + figure = plt.gcf() + assert len(figure.axes) == 4 + assert figure.axes[1].get_title() == 'Spatial component 1' + assert figure.axes[3].get_title() == 'Signal and spike times 1' + plt.close(figure) diff --git a/caiman/utils/utils.py b/caiman/utils/utils.py index 1b8b16f2e..01399ec27 100644 --- a/caiman/utils/utils.py +++ b/caiman/utils/utils.py @@ -65,28 +65,28 @@ def download_demo(name:str='Sue_2x_3000_40_-46.tif', save_folder:str='') -> str: logger = logging.getLogger("caiman") file_dict = { - 'Sue_2x_3000_40_-46.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/Sue_2x_3000_40_-46.tif', - 'Sue_Split1.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/Sue_Split1.tif', - 'Sue_Split2.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/Sue_Split2.tif', - 'Tolias_mesoscope_1.hdf5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/Tolias_mesoscope_1.hdf5', - 'Tolias_mesoscope_2.hdf5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/Tolias_mesoscope_2.hdf5', - 'Tolias_mesoscope_3.hdf5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/Tolias_mesoscope_3.hdf5', - 'alignment.pickle': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/alignment.pickle', - 'blood_vessel_10Hz.mat': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/blood_vessel_10Hz.mat', - 'data_dendritic.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/2014-04-05-003.tif', - 'data_endoscope.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/data_endoscope.tif', - 'demoMovieJ.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/demoMovieJ.tif', - 'demo_behavior.h5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/demo_behavior.h5', - 'demo_voltage_imaging_ROIs.hdf5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/demo_voltage_imaging_ROIs.hdf5', - 'demo_voltage_imaging.hdf5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/demo_voltage_imaging.hdf5', - 'demo_voltage_imaging_summary_images.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/demo_voltage_imaging_summary_images.tif', - 'gmc_960_30mw_00001_red.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/gmc_960_30mw_00001_red.tif', - 'gmc_960_30mw_00001_green.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/gmc_960_30mw_00001_green.tif', - 'k53.tif': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/k53.tif', - 'k53_ROIs.hdf5': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/k53_ROIs.hdf5', - 'mrcnn_epoch_100.pt': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/model/mrcnn_epoch_100.pt', - 'msCam13.avi': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/msCam13.avi', - 'online_vs_offline.npz': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/online_vs_offline.npz', + 'Sue_2x_3000_40_-46.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/Sue_2x_3000_40_-46.tif', + 'Sue_Split1.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/Sue_Split1.tif', + 'Sue_Split2.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/Sue_Split2.tif', + 'Tolias_mesoscope_1.hdf5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/Tolias_mesoscope_1.hdf5', + 'Tolias_mesoscope_2.hdf5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/Tolias_mesoscope_2.hdf5', + 'Tolias_mesoscope_3.hdf5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/Tolias_mesoscope_3.hdf5', + 'alignment.pickle': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/alignment.pickle', + 'blood_vessel_10Hz.mat': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/blood_vessel_10Hz.mat', + 'data_dendritic.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/2014-04-05-003.tif', + 'data_endoscope.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/data_endoscope.tif', + 'demoMovieJ.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/demoMovieJ.tif', + 'demo_behavior.h5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/demo_behavior.h5', + 'demo_voltage_imaging_ROIs.hdf5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/demo_voltage_imaging_ROIs.hdf5', + 'demo_voltage_imaging.hdf5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/demo_voltage_imaging.hdf5', + 'demo_voltage_imaging_summary_images.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/demo_voltage_imaging_summary_images.tif', + 'gmc_960_30mw_00001_red.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/gmc_960_30mw_00001_red.tif', + 'gmc_960_30mw_00001_green.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/gmc_960_30mw_00001_green.tif', + 'k53.tif': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/k53.tif', + 'k53_ROIs.hdf5': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/k53_ROIs.hdf5', + 'mrcnn_epoch_100.pt': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/model/mrcnn_epoch_100.pt', + 'msCam13.avi': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/msCam13.avi', + 'online_vs_offline.npz': 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/online_vs_offline.npz', } base_folder = os.path.join(caiman_datadir(), 'example_movies') @@ -138,16 +138,26 @@ def download_model(name:str='mask_rcnn', save_folder:str='') -> str: """ logger = logging.getLogger("caiman") - file_dict = {'mask_rcnn': 'https://caiman.flatironinstitute.org/~neuro/caiman_downloadables/model/mrcnn_epoch_100.pt'} + file_dict = { + 'mask_rcnn': ( + 'mrcnn_epoch_100.pt', + 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/model/mrcnn_epoch_100.pt', + ), + 'mask_rcnn_v2': ( + 'mrcnn_epoch_200.pt', + 'https://users.flatironinstitute.org/~neuro/caiman_downloadables/model/mrcnn_epoch_200.pt', + ), + } +filename, url = file_dict[name] + filename, url = file_dict[name] base_folder = os.path.join(caiman_datadir(), 'model') if os.path.exists(base_folder): if not os.path.isdir(os.path.join(base_folder, save_folder)): os.makedirs(os.path.join(base_folder, save_folder)) - path_movie = os.path.join(base_folder, save_folder, name) + path_movie = os.path.join(base_folder, save_folder, filename) if not os.path.exists(path_movie): - url = file_dict[name] - logger.info(f"downloading {name} with urllib") + logger.info(f"downloading {filename} with urllib") logger.info(f"GET {url} HTTP/1.1") # Set SSL context for cross-platform compatibility if os.name == 'nt': @@ -165,7 +175,7 @@ def download_model(name:str='mask_rcnn', save_folder:str='') -> str: with open(path_movie, "wb") as code: code.write(data) else: - logger.info("File " + str(name) + " already downloaded") + logger.info("File " + filename + " already downloaded") else: raise Exception('Cannot find the model folder in your caiman_datadir - did you make one with caimanmanager?') return path_movie @@ -607,7 +617,7 @@ def get_caiman_version() -> tuple[str, str]: # Attempt: 'FILE' # Right now this samples the utils directory - modpath = os.path.dirname(inspect.getfile(caiman.utils)) # Probably something like /mnt/home/pgunn/miniconda3/envs/caiman/lib/python3.7/site-packages/caiman + modpath = os.path.dirname(inspect.getfile(caiman.utils)) # Locate the installed CaImAn package. newest = 0 for fn in os.listdir(modpath): last_modified = os.stat(os.path.join(modpath, fn)).st_mtime diff --git a/caiman/utils/visualization.py b/caiman/utils/visualization.py index 8f27913cb..b03a8ece4 100644 --- a/caiman/utils/visualization.py +++ b/caiman/utils/visualization.py @@ -570,8 +570,8 @@ def nb_view_patches3d(Y_r, A, C, dims, image_type='mean', Yr=None, plt.close() K = np.max([[len(cor['coordinates']) for cor in cc] for cc in coors]) - cc1 = np.nan * np.zeros(coors.shape + (K,)) - cc2 = np.nan * np.zeros(coors.shape + (K,)) + cc1 = np.full((len(coors), nr, K), np.nan) + cc2 = np.full((len(coors), nr, K), np.nan) for i, cor in enumerate(coors[0]): cc1[0, i, :len(cor['coordinates']) ] = cor['coordinates'][:, 0] + offset1 @@ -1479,4 +1479,4 @@ def nb_view_quilt(template_image: np.ndarray, overlap_slider.js_on_change('value', callback) - bpl.show(bokeh.layouts.row(plot, bokeh.layouts.column(stride_slider, overlap_slider))) \ No newline at end of file + bpl.show(bokeh.layouts.row(plot, bokeh.layouts.column(stride_slider, overlap_slider))) diff --git a/demos/general/demo_pipeline_voltage_imaging.py b/demos/general/demo_pipeline_voltage_imaging.py index 0e6d6eb2a..954e3903e 100755 --- a/demos/general/demo_pipeline_voltage_imaging.py +++ b/demos/general/demo_pipeline_voltage_imaging.py @@ -162,8 +162,12 @@ def main(): elif cfg.method == 'maskrcnn': weights_path = download_model('mask_rcnn') - ROIs = utils.mrcnn_inference(img=summary_images.transpose([1, 2, 0]), size_range=[5, 22], - weights_path=weights_path, display_result=True) # size parameter decides size range of masks to be selected + ROIs = utils.mrcnn_inference_pytorch( + img=summary_images.transpose([1, 2, 0]), + size_range=[5, 22], + weights_path=weights_path, + display_result=True, + ) caiman.movie(ROIs).save(fnames[:-5] + '_mrcnn_ROIs.hdf5') elif cfg.method == 'gui_annotation': @@ -287,4 +291,3 @@ def handle_args(): ######## main() - diff --git a/demos/notebooks/demo_Ring_CNN.ipynb b/demos/notebooks/demo_Ring_CNN.ipynb index 0478f118b..5b99a4fa3 100644 --- a/demos/notebooks/demo_Ring_CNN.ipynb +++ b/demos/notebooks/demo_Ring_CNN.ipynb @@ -333,7 +333,10 @@ "metadata": {}, "outputs": [], "source": [ - "fname_mmap = cm.save_memmap([saved_files], order='C', border_to_0=0)\n", + "# saved_files is already the list of background-subtracted movie batches.\n", + "if not saved_files:\n", + " raise ValueError('No saved movie batches found. Run the preceding save/load cell first.')\n", + "fname_mmap = cm.save_memmap(saved_files, order='C', border_to_0=0)\n", "Yr, dims, T = cm.load_memmap(fname_mmap)\n", "images_mmap = Yr.T.reshape((T,) + dims, order='F')" ] diff --git a/demos/notebooks/demo_pipeline_voltage_imaging.ipynb b/demos/notebooks/demo_pipeline_voltage_imaging.ipynb index 4200c89a7..abd7761dd 100644 --- a/demos/notebooks/demo_pipeline_voltage_imaging.ipynb +++ b/demos/notebooks/demo_pipeline_voltage_imaging.ipynb @@ -74,9 +74,6 @@ "cell_type": "code", "execution_count": null, "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, "id": "EW54aHS_HRnE", "outputId": "6fd13521-983f-4711-ac76-fc3a601075f4", "tags": [] @@ -128,8 +125,7 @@ "execution_count": null, "metadata": { "colab": { - "background_save": true, - "base_uri": "https://localhost:8080/" + "background_save": true }, "id": "_HqUNdCyPBBW", "outputId": "ea7cfec7-8fe9-43cd-8ea0-ab32b6befbd6", diff --git a/demos/notebooks/demo_seeded_CNMF.ipynb b/demos/notebooks/demo_seeded_CNMF.ipynb index b9b784659..bd55b44e4 100644 --- a/demos/notebooks/demo_seeded_CNMF.ipynb +++ b/demos/notebooks/demo_seeded_CNMF.ipynb @@ -554,8 +554,15 @@ "# swap_dim should be set to True if the movie is in MATLAB format (time is last instead of first axis)\n", "Cn = cm.local_correlations(images, swap_dim=False)\n", "Cn[np.isnan(Cn)] = 0\n", - "save_path = fnames[0].split('.')[0] + '_local_corr.png'\n", - "imsave(save_path,Cn)\n", + "# Save beside the green-channel movie used to construct images.\n", + "from pathlib import Path\n", + "movie_path = Path(fname_green[0])\n", + "save_path = str(movie_path.with_name(movie_path.stem + '_local_corr.png'))\n", + "# PNG requires integer pixels; keep the floating-point Cn for analysis.\n", + "# For this visual template, map correlations 0..1 to grayscale 0..255.\n", + "Cn_png = np.rint(255 * np.clip(Cn, 0, 1)).astype(np.uint8)\n", + "imsave(save_path, Cn_png)\n", + "print(f'Saved local-correlation template: {save_path}')\n", "\n", "'''\n", "# Create image from structural or functional channel and check automatically extracted contours\n", @@ -605,31 +612,38 @@ "metadata": {}, "outputs": [], "source": [ - "# Choose expand method and morphological element of expansion. Dilation of masks provides more room for error\n", - "# and ensures that the complete neuron is included\n", - "expand_method = 'dilation'\n", - "selem = np.ones(3,3)\n", + "# Load individual binary masks exported from Fiji/ImageJ.\n", + "from skimage.morphology import dilation, closing\n", "\n", - "# Set the path of the individual masks. Adapt file extension if masks are not saved as .png\n", + "expand_method = 'dilation' # 'dilation', 'closing', or None\n", + "footprint = np.ones((3, 3), dtype=bool)\n", + "\n", + "# Replace this with the directory containing your individual PNG masks.\n", "dir_path = 'path of directory with masks'\n", - "file_list = glob(dir_path+'/*.png')\n", - "\n", - "for i in range(len(file_list)):\n", - " # temporarily save the current mask as a boolean array\n", - " temp = np.asarray(imageio.imread(file_list[i]), dtype=bool)\n", - " \n", - " # the csc_matrix has to be initialized before adding the first mask\n", - " if i == 0:\n", - " A = np.zeros((np.prod(temp.shape), len(file_list)), dtype=bool)\n", - " \n", - " # apply dilation or closing to the mask (optional)\n", + "if not os.path.isdir(dir_path):\n", + " raise FileNotFoundError(\n", + " 'Set dir_path to the directory containing your exported binary PNG masks. '\n", + " 'This optional tutorial section requires masks created in Fiji/ImageJ.'\n", + " )\n", + "file_list = sorted(glob(os.path.join(dir_path, '*.png')))\n", + "if not file_list:\n", + " raise FileNotFoundError(f'No PNG masks found in {dir_path}')\n", + "if expand_method not in ('dilation', 'closing', None):\n", + " raise ValueError(\"expand_method must be 'dilation', 'closing', or None\")\n", + "\n", + "A = np.zeros((int(np.prod(dims)), len(file_list)), dtype=bool)\n", + "for i, filename in enumerate(file_list):\n", + " temp = np.asarray(imageio.imread(filename), dtype=bool)\n", + " if temp.shape != tuple(dims):\n", + " raise ValueError(\n", + " f'Mask {filename} has shape {temp.shape}; expected {tuple(dims)}. '\n", + " 'Export a single-channel mask with the same dimensions as the movie.'\n", + " )\n", " if expand_method == 'dilation':\n", - " temp = dilation(temp, selem=selem)\n", + " temp = dilation(temp, footprint=footprint)\n", " elif expand_method == 'closing':\n", - " temp = dilation(temp, selem=selem)\n", - "\n", - " # flatten the mask to a 1D array and add it to the csc_matrix\n", - " A[:, i] = temp.flatten('F')" + " temp = closing(temp, footprint=footprint)\n", + " A[:, i] = temp.flatten('F')\n" ] }, {