Skip to content

Commit 0ebea67

Browse files
Update LaVision processing
1 parent a33f265 commit 0ebea67

File tree

15 files changed

+433
-37
lines changed

15 files changed

+433
-37
lines changed

flamingo_tools/extract_block_util.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import imageio.v3 as imageio
55
import numpy as np
66
import zarr
7+
from skimage.transform import rescale
78

89
import flamingo_tools.s3_utils as s3_utils
910
from flamingo_tools.file_utils import read_image_data
@@ -22,7 +23,8 @@ def extract_block(
2223
s3_credentials: Optional[str] = None,
2324
s3_bucket_name: Optional[str] = None,
2425
s3_service_endpoint: Optional[str] = None,
25-
):
26+
scale_factor: Optional[Tuple[float, float, float]] = None,
27+
) -> None:
2628
"""Extract block around coordinate from input data according to a given halo.
2729
Either from a local file or from an S3 bucket.
2830
@@ -38,6 +40,7 @@ def extract_block(
3840
s3_bucket_name: S3 bucket name.
3941
s3_service_endpoint: S3 service endpoint.
4042
s3_credentials: File path to credentials for S3 bucket.
43+
scale_factor: Optional factor for rescaling the extracted data.
4144
"""
4245
coord_string = "-".join([str(int(round(c))).zfill(4) for c in coords])
4346

@@ -93,9 +96,15 @@ def extract_block(
9396

9497
data_ = read_image_data(input_path, input_key)
9598
data_roi = data_[roi]
99+
if scale_factor is not None:
100+
kwargs = {"preserve_range": True}
101+
# Check if this is a segmentation.
102+
if data_roi.dtype in (np.dtype("int32"), np.dtype("uint32"), np.dtype("int64"), np.dtype("uint64")):
103+
kwargs.update({"order": 0, "anti_aliasing": False})
104+
data_roi = rescale(data_roi, scale_factor, **kwargs).astype(data_roi.dtype)
96105

97106
if tif:
98107
imageio.imwrite(output_file, data_roi, compression="zlib")
99108
else:
100-
with zarr.open(output_file, mode="w") as f_out:
101-
f_out.create_dataset(output_key, data=data_roi, compression="gzip")
109+
f_out = zarr.open(output_file, mode="w")
110+
f_out.create_dataset(output_key, data=data_roi, compression="gzip")

reproducibility/label_components/repro_label_components.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ def repro_label_components(
4040
component_list = dic["component_list"] if "component_list" in dic else default_component_list
4141

4242
table_name = f"{cell_type.upper()}_{unet_version}"
43+
# table_name = "PV_SGN_V2_DA"
4344
s3_path = os.path.join(f"{cochlea}", "tables", table_name, "default.tsv")
4445
tsv_path, fs = get_s3_path(s3_path, bucket_name=s3_bucket_name,
4546
service_endpoint=s3_service_endpoint, credential_file=s3_credentials)

reproducibility/templates_processing/REAMDE.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ For IHC segmentation run:
1313
- segment_unet_IHC_template.sbatch
1414

1515
After this, run the following to add segmentation to MoBIE, create component labelings and upload to S3:
16-
- templates_transfer/mobie_segmentatio.sbatch
16+
- templates_transfer/mobie_segmentation_template.sbatch
1717
- templates_transfer/s3_seg_template.sh
1818
- repro_label_components.py
1919
- templates_transfer/s3_seg_template.sh

reproducibility/templates_processing/apply_unet_SGN_template.sbatch

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@
44

55
#SBATCH -p grete:shared # the partition
66
#SBATCH -G A100:1 # For requesting 1 A100 GPU.
7-
#SBATCH -c 1
8-
#SBATCH --mem 24G
7+
#SBATCH -c 4
8+
#SBATCH --mem 32G
99
#SBATCH -a 0-9
1010

1111
source ~/.bashrc
12-
micromamba activate micro-sam_gpu
12+
# micromamba activate micro-sam_gpu
13+
micromamba activate sam
1314

1415
# Print out some info.
1516
echo "Submitting job with sbatch from directory: ${SLURM_SUBMIT_DIR}"
@@ -19,7 +20,8 @@ echo "Current node: ${SLURM_NODELIST}"
1920

2021
# Run the script
2122

22-
SCRIPT_REPO=/user/schilling40/u15000/flamingo-tools
23+
# SCRIPT_REPO=/user/schilling40/u15000/flamingo-tools
24+
SCRIPT_REPO=/user/pape41/u12086/Work/my_projects/flamingo-tools
2325
cd "$SCRIPT_REPO"/flamingo_tools/segmentation/ || exit
2426

2527
export SCRIPT_DIR=$SCRIPT_REPO/scripts
@@ -37,9 +39,16 @@ export INPUT=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/"$COC
3739

3840
export OUTPUT_FOLDER=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/predictions/"$COCHLEA"/"$SEG_NAME"
3941

40-
export MODEL=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/trained_models/SGN/v2_cochlea_distance_unet_SGN_supervised_2025-05-27
42+
# The default v2 model
43+
# export MODEL=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/trained_models/SGN/v2_cochlea_distance_unet_SGN_supervised_2025-05-27
44+
45+
# Domain adapted model for MLR99L
46+
export MODEL=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/trained_models/SGN/v2_domain_adaptation_mlr99l/best.pt
47+
4148
export PREDICTION_INSTANCES=10
42-
export INPUT_KEY="setup$STAIN_CHANNEL/timepoint0/s0"
49+
50+
# export INPUT_KEY="setup$STAIN_CHANNEL/timepoint0/s0"
51+
export INPUT_KEY="s0"
4352

4453
echo "Input directory: ${INPUT}"
4554
echo "Output directory: ${OUTPUT_FOLDER}"

reproducibility/templates_processing/mean_std_SGN_template.sbatch

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
#SBATCH --mem 128G
99

1010
source ~/.bashrc
11-
micromamba activate flamingo13
11+
# micromamba activate flamingo13
12+
micromamba activate sam
1213

1314
# Run the script
1415

15-
SCRIPT_REPO=/user/schilling40/u15000/flamingo-tools
16+
# SCRIPT_REPO=/user/schilling40/u15000/flamingo-tools
17+
SCRIPT_REPO=/user/pape41/u12086/Work/my_projects/flamingo-tools
1618
cd "$SCRIPT_REPO"/flamingo_tools/segmentation/ || exit
1719

1820
export SCRIPT_DIR=$SCRIPT_REPO/scripts
@@ -26,15 +28,13 @@ STAIN_CHANNEL=$3
2628
# segmentation name, as it appears in MoBIE, e.g. SGN_v2 or Calb1_SGN_v2
2729
SEG_NAME=$4
2830

29-
# TODO update model to
30-
# /mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/trained_models/SGN/v2_domain_adaptation_mlr99l
31-
# and download the PV channel again
32-
3331
export INPUT=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/"$COCHLEA"/"$DATA"
3432

3533
export OUTPUT_FOLDER=/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/predictions/"$COCHLEA"/"$SEG_NAME"
3634
export SEG_CLASS="sgn"
37-
export INPUT_KEY="setup$STAIN_CHANNEL/timepoint0/s0"
35+
36+
# export INPUT_KEY="setup$STAIN_CHANNEL/timepoint0/s0"
37+
export INPUT_KEY="s0"
3838

3939
if ! [[ -f $OUTPUT_FOLDER ]] ; then
4040
mkdir -p "$OUTPUT_FOLDER"

reproducibility/templates_processing/segment_unet_SGN_template.sbatch

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,17 @@
88
#SBATCH --mem 400G
99

1010
source ~/.bashrc
11-
micromamba activate micro-sam_gpu
11+
# micromamba activate micro-sam_gpu
12+
micromamba activate sam
1213

1314
# Print out some info.
1415
echo "Submitting job with sbatch from directory: ${SLURM_SUBMIT_DIR}"
1516
echo "Home directory: ${HOME}"
1617
echo "Working directory: $PWD"
1718
echo "Current node: ${SLURM_NODELIST}"
1819

19-
# Run the script
20-
#python myprogram.py $SLURM_ARRAY_TASK_ID
21-
22-
SCRIPT_REPO=/user/schilling40/u15000/flamingo-tools
20+
# SCRIPT_REPO=/user/schilling40/u15000/flamingo-tools
21+
SCRIPT_REPO=/user/pape41/u12086/Work/my_projects/flamingo-tools
2322
cd "$SCRIPT_REPO"/flamingo_tools/segmentation/ || exit
2423

2524
# name of cochlea, as it appears in MoBIE and the NHR

scripts/figures/segmentation_comparison.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ def _eval_seg(seg, eval_path):
2929

3030

3131
def sgn_comparison():
32+
scale = (0.38,) * 2
3233
z = 10
3334

3435
cochlea_dir = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet"
@@ -57,22 +58,29 @@ def sgn_comparison():
5758
eval_im[seg_name] = eva
5859

5960
v = napari.Viewer()
60-
v.add_image(image)
61+
v.add_image(image, scale=scale)
6162
for seg_name, bd in boundaries.items():
62-
v.add_labels(bd, name=seg_name, colormap={1: "cyan"})
63-
v.add_labels(eval_im[seg_name], name=f"{seg_name}_eval", colormap={1: "green", 2: "red"})
63+
v.add_labels(bd, name=seg_name, colormap={1: "cyan"}, scale=scale)
64+
v.add_labels(eval_im[seg_name], name=f"{seg_name}_eval", colormap={1: "green", 2: "red"}, scale=scale)
65+
66+
v.scale_bar.visible = True
67+
v.scale_bar.unit = "μm"
68+
v.scale_bar.font_size = 16
6469
v.title = Path(path).stem
70+
6571
napari.run()
6672

6773

6874
def ihc_comparison():
75+
scale = (0.38,) * 2
6976
z = 10
7077

7178
cochlea_dir = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet"
7279
val_sgn_dir = f"{cochlea_dir}/predictions/val_ihc"
7380
image_dir = f"{cochlea_dir}/AnnotatedImageCrops/F1ValidationIHCs"
7481

7582
image_paths = sorted(glob(os.path.join(image_dir, "*.tif")))
83+
scale = (0.38,) * 2
7684

7785
for path in image_paths:
7886
image = imageio.imread(path)[z]
@@ -96,11 +104,16 @@ def ihc_comparison():
96104
eval_im[seg_name] = eva
97105

98106
v = napari.Viewer()
99-
v.add_image(image)
107+
v.add_image(image, scale=scale)
100108
for seg_name, bd in boundaries.items():
101-
v.add_labels(bd, name=seg_name, colormap={1: "cyan"})
102-
v.add_labels(eval_im[seg_name], name=f"{seg_name}_eval", colormap={1: "green", 2: "red"})
109+
v.add_labels(bd, name=seg_name, colormap={1: "cyan"}, scale=scale)
110+
v.add_labels(eval_im[seg_name], name=f"{seg_name}_eval", colormap={1: "green", 2: "red"}, scale=scale)
111+
112+
v.scale_bar.visible = True
113+
v.scale_bar.unit = "μm"
114+
v.scale_bar.font_size = 16
103115
v.title = Path(path).stem
116+
104117
napari.run()
105118

106119

scripts/figures/supp_fig2.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import json
2+
import os
3+
4+
from glob import glob
5+
from pathlib import Path
6+
7+
import numpy as np
8+
9+
10+
# FIXME something is off with cellpose-sam runtimes
11+
def runtimes_sgn():
12+
for_comparison = ["distance_unet", "micro-sam", "cellpose3", "cellpose-sam", "stardist"]
13+
14+
cochlea_dir = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet"
15+
val_sgn_dir = f"{cochlea_dir}/predictions/val_sgn"
16+
image_dir = f"{cochlea_dir}/AnnotatedImageCrops/F1ValidationSGNs/for_consensus_annotation"
17+
18+
image_paths = sorted(glob(os.path.join(image_dir, "*.tif")))
19+
20+
runtimes = {name: [] for name in for_comparison}
21+
22+
for path in image_paths:
23+
eval_fname = Path(path).stem + "_dic.json"
24+
for seg_name in for_comparison:
25+
eval_path = os.path.join(val_sgn_dir, seg_name, eval_fname)
26+
with open(eval_path, "r") as f:
27+
result = json.load(f)
28+
rt = result["time"]
29+
runtimes[seg_name].append(rt)
30+
31+
for name, rts in runtimes.items():
32+
print(name, ":", np.mean(rts), "+-", np.std(rts))
33+
34+
35+
def runtimes_ihc():
36+
for_comparison = ["distance_unet_v3", "micro-sam", "cellpose3", "cellpose-sam"]
37+
38+
cochlea_dir = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet"
39+
val_sgn_dir = f"{cochlea_dir}/predictions/val_ihc"
40+
image_dir = f"{cochlea_dir}/AnnotatedImageCrops/F1ValidationIHCs"
41+
42+
image_paths = sorted(glob(os.path.join(image_dir, "*.tif")))
43+
44+
runtimes = {name: [] for name in for_comparison}
45+
46+
for path in image_paths:
47+
eval_fname = Path(path).stem + "_dic.json"
48+
for seg_name in for_comparison:
49+
eval_path = os.path.join(val_sgn_dir, seg_name, eval_fname)
50+
if not os.path.exists(eval_path):
51+
continue
52+
with open(eval_path, "r") as f:
53+
result = json.load(f)
54+
rt = result["time"]
55+
runtimes[seg_name].append(rt)
56+
57+
for name, rts in runtimes.items():
58+
print(name, ":", np.mean(rts), "+-", np.std(rts))
59+
60+
61+
def main():
62+
print("SGNs:")
63+
runtimes_sgn()
64+
print()
65+
print("IHCs:")
66+
runtimes_ihc()
67+
68+
69+
if __name__ == "__main__":
70+
main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import os
2+
3+
import imageio.v3 as imageio
4+
from mobie import add_image
5+
6+
INPUT_ROOT = "/mnt/ceph-hdd/cold/nim00007/cochlea-lightsheet/keppeler-et-al/marmoset"
7+
MOBIE_ROOT = "/mnt/vast-nhr/projects/nim00007/data/moser/cochlea-lightsheet/mobie_project/cochlea-lightsheet"
8+
DS_NAME = "LaVision-Mar05"
9+
RESOLUTION = (3.0, 1.887779, 1.887779)
10+
11+
12+
# Marmoset_cochlea_05_LSFM_ch1_raw.tif
13+
def add_marmoset_05():
14+
channel_names = ("PV", "7-AAD", "MYO")
15+
16+
scale_factors = 4 * [[2, 2, 2]]
17+
chunks = (96, 96, 96)
18+
19+
for channel_id, channel_name in enumerate(channel_names, 1):
20+
input_path = os.path.join(INPUT_ROOT, f"Marmoset_cochlea_05_LSFM_ch{channel_id}_raw.tif")
21+
print("Load image data ...")
22+
input_data = imageio.imread(input_path)
23+
print(input_data.shape)
24+
add_image(
25+
input_path=input_data, input_key=None, root=MOBIE_ROOT,
26+
dataset_name=DS_NAME, image_name=channel_name, resolution=RESOLUTION,
27+
scale_factors=scale_factors, chunks=chunks, unit="micrometer", use_memmap=False,
28+
)
29+
30+
31+
def main():
32+
add_marmoset_05()
33+
34+
35+
if __name__ == "__main__":
36+
main()

0 commit comments

Comments
 (0)