Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions caiman/source_extraction/volpy/mrcnn/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this

"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
Expand All @@ -26,23 +38,36 @@ 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],
'TEG': [21],
'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")
print("\n")
71 changes: 55 additions & 16 deletions caiman/source_extraction/volpy/mrcnn/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +13 to +16

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we keep these alphabetical?

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.
Expand All @@ -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
Expand All @@ -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
"""
Expand All @@ -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
keep = pred['scores'] >= threshold
masks = pred['masks'][keep, 0]
boxes = pred['boxes'][keep]
scores = pred['scores'][keep]

return masks, boxes, scores
Loading
Loading