Spaces:
Sleeping
Sleeping
RootScope Gradio app (ZeroGPU)
Browse files- .gitattributes +2 -0
- README.md +40 -7
- app.py +411 -0
- examples/Acorulea_RootTip_Maturation.tif +3 -0
- examples/Spennellii_RootTip_EarlyMaturation.tif +3 -0
- requirements.txt +26 -0
- rootscope/__init__.py +23 -0
- rootscope/__pycache__/__init__.cpython-310.pyc +0 -0
- rootscope/__pycache__/api.cpython-310.pyc +0 -0
- rootscope/__pycache__/cli.cpython-310.pyc +0 -0
- rootscope/__pycache__/extract_features.cpython-310.pyc +0 -0
- rootscope/__pycache__/overlay.cpython-310.pyc +0 -0
- rootscope/__pycache__/predict.cpython-310.pyc +0 -0
- rootscope/__pycache__/weights.cpython-310.pyc +0 -0
- rootscope/api.py +89 -0
- rootscope/cli.py +102 -0
- rootscope/cnn_embeddings.py +208 -0
- rootscope/extract_features.py +1724 -0
- rootscope/overlay.py +320 -0
- rootscope/predict.py +955 -0
- rootscope/weights.py +249 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
examples/Acorulea_RootTip_Maturation.tif filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
examples/Spennellii_RootTip_EarlyMaturation.tif filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,13 +1,46 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: RootScope
|
| 3 |
+
emoji: π±
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.1
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
short_description: Segment and classify root cell types from a confocal TIFF
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# RootScope
|
| 15 |
+
|
| 16 |
+
Upload a confocal root-tip cross-section (TIFF) and get every cell segmented
|
| 17 |
+
and classified.
|
| 18 |
+
|
| 19 |
+
RootScope segments with **Cellpose-SAM**, extracts shape / size / intensity /
|
| 20 |
+
tissue-layer features together with fine-tuned **DINOv2** embeddings, and
|
| 21 |
+
predicts each cell's type using an iterative **RandomForest + XGBoost +
|
| 22 |
+
LightGBM** ensemble. You get a labeled overlay and a per-cell CSV.
|
| 23 |
+
|
| 24 |
+
**Nine cell types:** root cap, epidermis, exodermis, cortex, endodermis,
|
| 25 |
+
pericycle, xylem, phloem, stele.
|
| 26 |
+
|
| 27 |
+
## Using it
|
| 28 |
+
|
| 29 |
+
1. Upload a TIFF (or click one of the examples).
|
| 30 |
+
2. Check the **microns per pixel** box β it is read from the file's OME
|
| 31 |
+
metadata when present. This matters: the 1.0 default distorts every
|
| 32 |
+
size-derived feature.
|
| 33 |
+
3. Press **Run RootScope**.
|
| 34 |
+
4. Download the per-cell CSV, or the ZIP with all four models' outputs.
|
| 35 |
+
|
| 36 |
+
One image takes a couple of minutes. Batches are better done locally with
|
| 37 |
+
`rootscope --tif-dir my_tifs/`.
|
| 38 |
+
|
| 39 |
+
## Links
|
| 40 |
+
|
| 41 |
+
- Code: https://github.com/ct-tranchau/Rootscope
|
| 42 |
+
- Model weights: https://huggingface.co/ct-tranchau/Rootscope
|
| 43 |
+
- Model card: https://github.com/ct-tranchau/Rootscope/blob/main/MODEL_CARD.md
|
| 44 |
+
|
| 45 |
+
Research use only. See the model card for the species and growth stages the
|
| 46 |
+
model was trained on.
|
app.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
RootScope on Hugging Face Spaces β upload a root-tip TIFF, get segmented and
|
| 3 |
+
classified cells back.
|
| 4 |
+
|
| 5 |
+
Modelled on the Cellpose-SAM Space (huggingface.co/spaces/mouseland/cellpose),
|
| 6 |
+
with one important difference: only two steps of the RootScope pipeline touch
|
| 7 |
+
the GPU (Cellpose-SAM segmentation and the DINOv2 embeddings). Those are the
|
| 8 |
+
only ones wrapped in @spaces.GPU. Feature extraction, the iterative
|
| 9 |
+
RandomForest/XGBoost/LightGBM refinement, anatomical post-processing and
|
| 10 |
+
overlay drawing all run on the CPU worker, off the GPU clock.
|
| 11 |
+
|
| 12 |
+
Run locally with: python webapp/app.py
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import functools
|
| 16 |
+
import re
|
| 17 |
+
import tempfile
|
| 18 |
+
import zipfile
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import gradio as gr
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import tifffile
|
| 25 |
+
from PIL import Image
|
| 26 |
+
|
| 27 |
+
from rootscope import predict as rs
|
| 28 |
+
from rootscope.cnn_embeddings import load_dinov2
|
| 29 |
+
from rootscope.extract_features import load_cellpose_model
|
| 30 |
+
from rootscope.weights import resolve_cnn_weights, resolve_model_dir
|
| 31 |
+
|
| 32 |
+
# ββ ZeroGPU shim βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 33 |
+
# `spaces` only exists on Hugging Face. Locally the decorator becomes a no-op
|
| 34 |
+
# so the same file runs on a workstation or a lab GPU node.
|
| 35 |
+
try:
|
| 36 |
+
import spaces
|
| 37 |
+
except ImportError: # noqa: BLE001
|
| 38 |
+
class _NoSpaces:
|
| 39 |
+
@staticmethod
|
| 40 |
+
def GPU(*args, **kwargs):
|
| 41 |
+
def wrap(fn):
|
| 42 |
+
return fn
|
| 43 |
+
return wrap
|
| 44 |
+
|
| 45 |
+
spaces = _NoSpaces() # type: ignore[assignment]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
print = functools.partial(print, flush=True) # noqa: A001 β Spaces log stdout
|
| 49 |
+
|
| 50 |
+
# Everything the UI serves back (previews, overlays, CSVs, ZIPs) is written
|
| 51 |
+
# under here, and this one directory is handed to launch(allowed_paths=...).
|
| 52 |
+
# Gradio refuses to serve files from arbitrary locations on disk, so results
|
| 53 |
+
# must live somewhere it has been told about.
|
| 54 |
+
TMP_ROOT = Path(tempfile.gettempdir()) / "rootscope_runs"
|
| 55 |
+
TMP_ROOT.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
|
| 57 |
+
MAX_PIXELS = 40_000_000 # ~6300x6300; refuse anything larger
|
| 58 |
+
MODEL_CHOICES = ["Ensemble", "RandomForest", "LightGBM", "XGBoost"]
|
| 59 |
+
|
| 60 |
+
# ββ load everything once, at startup βββββββββββββββββββββββββββββββββββββββββ
|
| 61 |
+
# On a Space this happens at boot, not per request. Loading the ~460 MB of
|
| 62 |
+
# classifiers on every upload would dominate the runtime.
|
| 63 |
+
print("[rootscope-web] loading models...")
|
| 64 |
+
MODEL_DIR = resolve_model_dir()
|
| 65 |
+
CNN_WEIGHTS = resolve_cnn_weights()
|
| 66 |
+
MODELS, SCALERS, FEATURE_COLS, LE = rs.load_models(str(MODEL_DIR))
|
| 67 |
+
if not MODELS:
|
| 68 |
+
raise RuntimeError(f"No usable models found in {MODEL_DIR}")
|
| 69 |
+
|
| 70 |
+
CELLPOSE_MODEL = load_cellpose_model(use_gpu=True)
|
| 71 |
+
DINOV2_MODEL = load_dinov2(weights_path=str(CNN_WEIGHTS) if CNN_WEIGHTS else None,
|
| 72 |
+
use_gpu=True)
|
| 73 |
+
print(f"[rootscope-web] ready β {len(MODELS)} classifiers, "
|
| 74 |
+
f"{len(FEATURE_COLS)} features, classes: {list(LE.classes_)}")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ββ the two GPU stages βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 78 |
+
# Duration is tiered by image size, as the Cellpose-SAM Space does, so a small
|
| 79 |
+
# image does not reserve a long slot against the user's daily GPU quota.
|
| 80 |
+
|
| 81 |
+
# ZeroGPU bills the wall-clock of each @spaces.GPU call against the visitor's
|
| 82 |
+
# daily quota, and a call that overruns its reservation is killed. Rather than
|
| 83 |
+
# bucket into fixed tiers, ask for a duration computed from the actual input β
|
| 84 |
+
# ZeroGPU accepts a callable taking the same arguments as the function.
|
| 85 |
+
#
|
| 86 |
+
# Calibrated from CPU measurements (segmentation 95 s at 700x700 / 148 s at
|
| 87 |
+
# 910x910; embeddings 43 s for 215 cells / 80 s for 448 cells) then floored
|
| 88 |
+
# generously, since a GPU should be far quicker but an overrun is fatal while
|
| 89 |
+
# over-reserving only costs queue priority.
|
| 90 |
+
|
| 91 |
+
def _segment_duration(img_rgb):
|
| 92 |
+
px = max(img_rgb.shape[:2])
|
| 93 |
+
return int(min(300, max(60, px / 1200 * 60)))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _embed_duration(masks, img_rgb, df_base):
|
| 97 |
+
n = int(masks.max())
|
| 98 |
+
return int(min(300, max(60, n / 500 * 60)))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@spaces.GPU(duration=_segment_duration)
|
| 102 |
+
def _segment(img_rgb):
|
| 103 |
+
return rs.stage_segment(img_rgb, gpu=True, cellpose_model=CELLPOSE_MODEL)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@spaces.GPU(duration=_embed_duration)
|
| 107 |
+
def _embed(masks, img_rgb, df_base):
|
| 108 |
+
return rs.stage_embed(masks, img_rgb, df_base, gpu=True,
|
| 109 |
+
dinov2_model=DINOV2_MODEL)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
+
|
| 114 |
+
def read_um_per_px(tif_path):
|
| 115 |
+
"""Pull the pixel size out of the TIFF metadata, if it has any.
|
| 116 |
+
|
| 117 |
+
RootScope does not read the scale from the file, and the 1.0 default
|
| 118 |
+
silently distorts every size-derived feature β so prefill the box rather
|
| 119 |
+
than let the user forget.
|
| 120 |
+
"""
|
| 121 |
+
try:
|
| 122 |
+
with tifffile.TiffFile(tif_path) as tf:
|
| 123 |
+
if tf.ome_metadata:
|
| 124 |
+
m = re.search(r'PhysicalSizeX="([0-9.eE+-]+)"', tf.ome_metadata)
|
| 125 |
+
if m:
|
| 126 |
+
return round(float(m.group(1)), 6)
|
| 127 |
+
tags = tf.pages[0].tags
|
| 128 |
+
if "XResolution" in tags and "ResolutionUnit" in tags:
|
| 129 |
+
num, den = tags["XResolution"].value
|
| 130 |
+
if num:
|
| 131 |
+
px_per_unit = num / den
|
| 132 |
+
unit = int(tags["ResolutionUnit"].value)
|
| 133 |
+
if unit == 3: # centimetre
|
| 134 |
+
return round(10_000.0 / px_per_unit, 6)
|
| 135 |
+
if unit == 2: # inch
|
| 136 |
+
return round(25_400.0 / px_per_unit, 6)
|
| 137 |
+
except Exception as e: # noqa: BLE001
|
| 138 |
+
print(f"[rootscope-web] could not read pixel size: {e}")
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _preview_png(img_rgb):
|
| 143 |
+
"""Write a display-only PNG of the (max-projected) image.
|
| 144 |
+
|
| 145 |
+
The gr.Image component is filepath-typed, so whatever we show becomes its
|
| 146 |
+
value. That displayed PNG must never become the thing we segment β the
|
| 147 |
+
original TIFF path is kept in a State instead.
|
| 148 |
+
"""
|
| 149 |
+
tmp = tempfile.NamedTemporaryFile(suffix="_preview.png", delete=False,
|
| 150 |
+
dir=TMP_ROOT)
|
| 151 |
+
Image.fromarray(img_rgb.astype(np.uint8)).save(tmp.name)
|
| 152 |
+
return tmp.name
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def on_upload(filepath):
|
| 156 |
+
"""Show the uploaded image and prefill um/px from its metadata."""
|
| 157 |
+
if not filepath:
|
| 158 |
+
return None, gr.update(), "Upload a root-tip TIFF to begin.", None
|
| 159 |
+
try:
|
| 160 |
+
img_rgb = rs.load_image(filepath)
|
| 161 |
+
except Exception as e: # noqa: BLE001
|
| 162 |
+
return None, gr.update(), f"Could not read that file: {e}", None
|
| 163 |
+
|
| 164 |
+
preview = _preview_png(img_rgb)
|
| 165 |
+
h, w = img_rgb.shape[:2]
|
| 166 |
+
scale = read_um_per_px(filepath)
|
| 167 |
+
if scale is None:
|
| 168 |
+
note = (f"Loaded {w}Γ{h}. **No pixel size in the metadata** β set "
|
| 169 |
+
f"microns/pixel yourself; leaving it at 1.0 distorts every "
|
| 170 |
+
f"size-derived feature.")
|
| 171 |
+
return preview, gr.update(), note, filepath
|
| 172 |
+
note = f"Loaded {w}Γ{h}. Pixel size from metadata: **{scale} Β΅m/px**."
|
| 173 |
+
return preview, gr.update(value=scale), note, filepath
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _summarize(df, model_name):
|
| 177 |
+
sub = df[df["model"] == model_name]
|
| 178 |
+
counts = sub["predicted_cell_type"].value_counts()
|
| 179 |
+
summary = pd.DataFrame({
|
| 180 |
+
"cell type": counts.index,
|
| 181 |
+
"cells": counts.values,
|
| 182 |
+
"% of cells": (100 * counts.values / counts.values.sum()).round(1),
|
| 183 |
+
"mean confidence": [
|
| 184 |
+
round(float(sub.loc[sub["predicted_cell_type"] == ct,
|
| 185 |
+
"prediction_confidence"].mean()), 3)
|
| 186 |
+
for ct in counts.index
|
| 187 |
+
],
|
| 188 |
+
})
|
| 189 |
+
return sub, summary
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _render(results, model_name):
|
| 193 |
+
"""Build the display for one model from an already-computed run."""
|
| 194 |
+
workdir = Path(results["workdir"])
|
| 195 |
+
stem = results["stem"]
|
| 196 |
+
overlay_path = workdir / f"{stem}_{model_name}_overlay.png"
|
| 197 |
+
csv_path = workdir / f"{stem}_{model_name}_predictions.csv"
|
| 198 |
+
|
| 199 |
+
sub, summary = _summarize(results["df"], model_name)
|
| 200 |
+
stats = (f"**{model_name}** Β· {len(sub)} cells Β· {results['n_layers']} "
|
| 201 |
+
f"tissue layers Β· {results['um_per_px']} Β΅m/px")
|
| 202 |
+
if len(sub) and "n_xylem_poles" in sub.columns:
|
| 203 |
+
row = sub.iloc[0]
|
| 204 |
+
stats += (f" Β· xylem poles: {int(row['n_xylem_poles'])} Β· "
|
| 205 |
+
f"phloem poles: {int(row['n_phloem_poles'])}")
|
| 206 |
+
|
| 207 |
+
return (str(overlay_path), summary, stats,
|
| 208 |
+
gr.DownloadButton(value=str(csv_path), visible=True))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def run_rootscope(tif_path, um_per_px, which_model, label_cells,
|
| 212 |
+
max_rounds, progress=gr.Progress()):
|
| 213 |
+
if not tif_path:
|
| 214 |
+
raise gr.Error("Upload a TIFF first.")
|
| 215 |
+
if not um_per_px or float(um_per_px) <= 0:
|
| 216 |
+
raise gr.Error("Microns per pixel must be greater than 0.")
|
| 217 |
+
|
| 218 |
+
progress(0.02, desc="Reading image")
|
| 219 |
+
img_rgb = rs.load_image(tif_path)
|
| 220 |
+
h, w = img_rgb.shape[:2]
|
| 221 |
+
if h * w > MAX_PIXELS:
|
| 222 |
+
raise gr.Error(
|
| 223 |
+
f"Image is {w}Γ{h} ({h * w / 1e6:.0f} MP), over this demo's "
|
| 224 |
+
f"{MAX_PIXELS / 1e6:.0f} MP limit. Crop it, or run RootScope locally."
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Not cleaned up: Gradio serves the downloads straight out of this
|
| 228 |
+
# directory, so it has to outlive the request. Spaces are ephemeral, but on
|
| 229 |
+
# a long-lived server add a reaper for old TMP_ROOT/run_* directories.
|
| 230 |
+
workdir = Path(tempfile.mkdtemp(prefix="run_", dir=TMP_ROOT))
|
| 231 |
+
stem = Path(tif_path).stem.replace(".aivia", "")
|
| 232 |
+
|
| 233 |
+
# ---- GPU: segmentation ----
|
| 234 |
+
progress(0.10, desc="Segmenting with Cellpose-SAM (GPU)")
|
| 235 |
+
masks = _segment(img_rgb)
|
| 236 |
+
n_cells = int(masks.max())
|
| 237 |
+
if n_cells == 0:
|
| 238 |
+
raise gr.Error("Cellpose-SAM found no cells in this image.")
|
| 239 |
+
|
| 240 |
+
# ---- CPU: tissue layers + handcrafted features ----
|
| 241 |
+
progress(0.35, desc=f"{n_cells} cells β layer index and features")
|
| 242 |
+
masks, df_base, layer_lookup, adjacency, n_layers = rs.stage_features(
|
| 243 |
+
masks, img_rgb, um_per_px=float(um_per_px))
|
| 244 |
+
if df_base is None:
|
| 245 |
+
raise gr.Error("Every detected object was filtered out as debris "
|
| 246 |
+
"outside the tissue body.")
|
| 247 |
+
|
| 248 |
+
# ---- GPU: DINOv2 embeddings ----
|
| 249 |
+
progress(0.50, desc="DINOv2 embeddings (GPU)")
|
| 250 |
+
df_base = _embed(masks, img_rgb, df_base)
|
| 251 |
+
|
| 252 |
+
# ---- CPU: iterative classification, post-processing, overlays ----
|
| 253 |
+
progress(0.65, desc="Classifying cells (iterative ensemble)")
|
| 254 |
+
df = rs.stage_classify(
|
| 255 |
+
df_base, masks, img_rgb, layer_lookup, adjacency,
|
| 256 |
+
MODELS, SCALERS, FEATURE_COLS, LE,
|
| 257 |
+
out_dir=workdir, stem=stem, source_name=Path(tif_path).name,
|
| 258 |
+
um_per_px=float(um_per_px), max_rounds=int(max_rounds),
|
| 259 |
+
label_cells=bool(label_cells),
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
progress(0.95, desc="Packaging results")
|
| 263 |
+
zip_path = workdir / f"{stem}_rootscope_results.zip"
|
| 264 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as z:
|
| 265 |
+
for f in sorted(workdir.iterdir()):
|
| 266 |
+
if f.suffix in (".png", ".csv"):
|
| 267 |
+
z.write(f, arcname=f.name)
|
| 268 |
+
|
| 269 |
+
available = [m for m in MODEL_CHOICES
|
| 270 |
+
if (workdir / f"{stem}_{m}_overlay.png").exists()]
|
| 271 |
+
chosen = which_model if which_model in available else available[0]
|
| 272 |
+
|
| 273 |
+
results = {"workdir": str(workdir), "stem": stem, "df": df,
|
| 274 |
+
"n_layers": n_layers, "um_per_px": float(um_per_px),
|
| 275 |
+
"available": available}
|
| 276 |
+
overlay_path, summary, stats, csv_button = _render(results, chosen)
|
| 277 |
+
return (overlay_path, summary, stats, csv_button,
|
| 278 |
+
gr.DownloadButton(value=str(zip_path), visible=True),
|
| 279 |
+
gr.update(choices=available, value=chosen),
|
| 280 |
+
results)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def switch_model(results, model_name):
|
| 284 |
+
"""Swap the displayed model without recomputing β every model's overlay and
|
| 285 |
+
CSV was already written to the run's temp dir."""
|
| 286 |
+
if not results or model_name not in results.get("available", []):
|
| 287 |
+
return gr.update(), gr.update(), gr.update(), gr.update()
|
| 288 |
+
return _render(results, model_name)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
LEGEND = """
|
| 292 |
+
<div style="display:flex;flex-wrap:wrap;gap:12px;font-size:13px;margin-top:6px">
|
| 293 |
+
<span><b style="color:#FF69B4">β </b> root cap</span>
|
| 294 |
+
<span><b style="color:#0000FF">β </b> epidermis</span>
|
| 295 |
+
<span><b style="color:#CCCC00">β </b> exodermis</span>
|
| 296 |
+
<span><b style="color:#00C800">β </b> cortex</span>
|
| 297 |
+
<span><b style="color:#FFA500">β </b> endodermis</span>
|
| 298 |
+
<span><b style="color:#800080">β </b> pericycle</span>
|
| 299 |
+
<span><b style="color:#FF0000">β </b> xylem</span>
|
| 300 |
+
<span><b style="color:#888888">β </b> phloem</span>
|
| 301 |
+
<span><b style="color:#00BFBF">β </b> stele</span>
|
| 302 |
+
</div>
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
# Gradio 6 moved `theme` from the Blocks constructor to launch(); Gradio 5
|
| 306 |
+
# only accepts it on Blocks. Pass it wherever this version wants it.
|
| 307 |
+
_THEME = gr.themes.Soft()
|
| 308 |
+
_THEME_ON_LAUNCH = int(gr.__version__.split(".")[0]) >= 6
|
| 309 |
+
_blocks_kwargs = {} if _THEME_ON_LAUNCH else {"theme": _THEME}
|
| 310 |
+
|
| 311 |
+
with gr.Blocks(title="RootScope", **_blocks_kwargs) as demo:
|
| 312 |
+
gr.Markdown(
|
| 313 |
+
"# RootScope β root cell-type classification\n"
|
| 314 |
+
"Upload a confocal root-tip cross-section (TIFF). RootScope segments "
|
| 315 |
+
"every cell with **Cellpose-SAM**, then predicts each cell's type with "
|
| 316 |
+
"an iterative **RandomForest + XGBoost + LightGBM** ensemble over "
|
| 317 |
+
"shape / size / intensity / tissue-layer features and fine-tuned "
|
| 318 |
+
"**DINOv2** embeddings.\n\n"
|
| 319 |
+
"[github](https://github.com/ct-tranchau/Rootscope) Β· "
|
| 320 |
+
"[model weights](https://huggingface.co/ct-tranchau/Rootscope)"
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
tif_state = gr.State(None) # the real TIFF; never the displayed preview
|
| 324 |
+
results_state = gr.State(None) # last completed run, for switching models
|
| 325 |
+
|
| 326 |
+
with gr.Row():
|
| 327 |
+
with gr.Column(scale=1):
|
| 328 |
+
input_image = gr.Image(label="Input TIFF", type="filepath",
|
| 329 |
+
sources=["upload"], height=340)
|
| 330 |
+
status = gr.Markdown("Upload a root-tip TIFF to begin.")
|
| 331 |
+
|
| 332 |
+
um_per_px = gr.Number(
|
| 333 |
+
label="Microns per pixel",
|
| 334 |
+
value=1.0,
|
| 335 |
+
info="Read from the file's metadata when present. This is not "
|
| 336 |
+
"optional β the 1.0 default distorts every size-derived "
|
| 337 |
+
"feature.",
|
| 338 |
+
)
|
| 339 |
+
model_pick = gr.Dropdown(
|
| 340 |
+
MODEL_CHOICES, value="Ensemble", label="Model to display",
|
| 341 |
+
info="All four are computed in one run; this only picks which "
|
| 342 |
+
"one you see. Ensemble is the published result.",
|
| 343 |
+
)
|
| 344 |
+
with gr.Accordion("Advanced", open=False):
|
| 345 |
+
label_cells = gr.Checkbox(
|
| 346 |
+
label="Write cell-type names on the overlay", value=False,
|
| 347 |
+
info="Readable when zoomed into one region; on a dense "
|
| 348 |
+
"section the text overlaps and hides the image.",
|
| 349 |
+
)
|
| 350 |
+
max_rounds = gr.Slider(
|
| 351 |
+
1, 20, value=10, step=1, label="Max refinement rounds",
|
| 352 |
+
info="The classifier re-predicts using neighbours' types "
|
| 353 |
+
"until predictions stop changing.",
|
| 354 |
+
)
|
| 355 |
+
run_btn = gr.Button("Run RootScope", variant="primary")
|
| 356 |
+
|
| 357 |
+
with gr.Column(scale=1):
|
| 358 |
+
overlay = gr.Image(label="Predicted cell types", type="filepath",
|
| 359 |
+
height=420)
|
| 360 |
+
gr.HTML(LEGEND)
|
| 361 |
+
stats_md = gr.Markdown()
|
| 362 |
+
summary = gr.Dataframe(label="Cells per type", interactive=False,
|
| 363 |
+
wrap=True)
|
| 364 |
+
with gr.Row():
|
| 365 |
+
csv_btn = gr.DownloadButton("Download predictions (CSV)",
|
| 366 |
+
visible=False)
|
| 367 |
+
zip_btn = gr.DownloadButton("Download everything (ZIP)",
|
| 368 |
+
visible=False)
|
| 369 |
+
|
| 370 |
+
# On a Space the TIFFs sit next to app.py; in a git checkout they are one
|
| 371 |
+
# level up in examples/.
|
| 372 |
+
here = Path(__file__).parent
|
| 373 |
+
examples_dir = next((d for d in (here / "examples", here.parent / "examples")
|
| 374 |
+
if (d / "Acorulea_RootTip_Maturation.tif").exists()), None)
|
| 375 |
+
if examples_dir is not None:
|
| 376 |
+
gr.Examples(
|
| 377 |
+
examples=[
|
| 378 |
+
[str(examples_dir / "Acorulea_RootTip_Maturation.tif")],
|
| 379 |
+
[str(examples_dir / "Spennellii_RootTip_EarlyMaturation.tif")],
|
| 380 |
+
],
|
| 381 |
+
fn=on_upload,
|
| 382 |
+
inputs=[input_image],
|
| 383 |
+
outputs=[input_image, um_per_px, status, tif_state],
|
| 384 |
+
run_on_click=True,
|
| 385 |
+
label="Example images (click one, then press Run)",
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
gr.Markdown(
|
| 389 |
+
"**Notes**\n"
|
| 390 |
+
"- One image at a time. For batches, install RootScope locally and use "
|
| 391 |
+
"`rootscope --tif-dir my_tifs/`.\n"
|
| 392 |
+
"- Z-stacks are max-projected before segmentation.\n"
|
| 393 |
+
"- The ZIP holds overlays and per-cell CSVs for all four models.\n"
|
| 394 |
+
"- Research use only β see the "
|
| 395 |
+
"[model card](https://github.com/ct-tranchau/Rootscope/blob/main/MODEL_CARD.md) "
|
| 396 |
+
"for the species and growth stages the model was trained on."
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
input_image.upload(on_upload, input_image,
|
| 400 |
+
[input_image, um_per_px, status, tif_state])
|
| 401 |
+
run_btn.click(
|
| 402 |
+
run_rootscope,
|
| 403 |
+
[tif_state, um_per_px, model_pick, label_cells, max_rounds],
|
| 404 |
+
[overlay, summary, stats_md, csv_btn, zip_btn, model_pick, results_state],
|
| 405 |
+
)
|
| 406 |
+
model_pick.change(switch_model, [results_state, model_pick],
|
| 407 |
+
[overlay, summary, stats_md, csv_btn])
|
| 408 |
+
|
| 409 |
+
if __name__ == "__main__":
|
| 410 |
+
launch_kwargs = {"theme": _THEME} if _THEME_ON_LAUNCH else {}
|
| 411 |
+
demo.queue(max_size=20).launch(allowed_paths=[str(TMP_ROOT)], **launch_kwargs)
|
examples/Acorulea_RootTip_Maturation.tif
ADDED
|
|
Git LFS Details
|
examples/Spennellii_RootTip_EarlyMaturation.tif
ADDED
|
|
Git LFS Details
|
requirements.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# torch / torchvision are deliberately absent: ZeroGPU supplies its own CUDA
|
| 2 |
+
# build (2.8+) and pinning them here would fight it. Same pattern the
|
| 3 |
+
# Cellpose-SAM Space uses.
|
| 4 |
+
gradio
|
| 5 |
+
|
| 6 |
+
numpy
|
| 7 |
+
pandas
|
| 8 |
+
scipy
|
| 9 |
+
scikit-image
|
| 10 |
+
# Hard pin: the released .joblib models were pickled with 1.7.2 and other
|
| 11 |
+
# versions can fail to unpickle or silently change behaviour.
|
| 12 |
+
scikit-learn==1.7.2
|
| 13 |
+
opencv-python-headless
|
| 14 |
+
Pillow
|
| 15 |
+
tifffile
|
| 16 |
+
imagecodecs
|
| 17 |
+
matplotlib
|
| 18 |
+
seaborn
|
| 19 |
+
tqdm
|
| 20 |
+
joblib
|
| 21 |
+
|
| 22 |
+
xgboost
|
| 23 |
+
lightgbm
|
| 24 |
+
cellpose>=4.0
|
| 25 |
+
|
| 26 |
+
huggingface_hub>=0.24
|
rootscope/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Rootscope β cell-type prediction for confocal root-tip cross-section images.
|
| 3 |
+
|
| 4 |
+
Give it a TIFF, it segments the cells (Cellpose-SAM), extracts shape / size /
|
| 5 |
+
intensity / layer features plus fine-tuned DINOv2 embeddings, and predicts the
|
| 6 |
+
cell type of every cell with an iterative ensemble (RandomForest / XGBoost /
|
| 7 |
+
LightGBM).
|
| 8 |
+
|
| 9 |
+
Typical use (command line):
|
| 10 |
+
|
| 11 |
+
rootscope --tif my_image.tif --out results/
|
| 12 |
+
|
| 13 |
+
Typical use (Python):
|
| 14 |
+
|
| 15 |
+
from rootscope import predict_tif
|
| 16 |
+
df = predict_tif("my_image.tif", out_dir="results/", gpu=True)
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
__version__ = "0.1.0"
|
| 20 |
+
|
| 21 |
+
from .api import predict_tif, predict_folder # noqa: E402,F401
|
| 22 |
+
|
| 23 |
+
__all__ = ["predict_tif", "predict_folder", "__version__"]
|
rootscope/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (936 Bytes). View file
|
|
|
rootscope/__pycache__/api.cpython-310.pyc
ADDED
|
Binary file (2.62 kB). View file
|
|
|
rootscope/__pycache__/cli.cpython-310.pyc
ADDED
|
Binary file (3.64 kB). View file
|
|
|
rootscope/__pycache__/extract_features.cpython-310.pyc
ADDED
|
Binary file (41.9 kB). View file
|
|
|
rootscope/__pycache__/overlay.cpython-310.pyc
ADDED
|
Binary file (9.19 kB). View file
|
|
|
rootscope/__pycache__/predict.cpython-310.pyc
ADDED
|
Binary file (25.8 kB). View file
|
|
|
rootscope/__pycache__/weights.cpython-310.pyc
ADDED
|
Binary file (7.47 kB). View file
|
|
|
rootscope/api.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
High-level Python API for Rootscope.
|
| 3 |
+
|
| 4 |
+
from rootscope import predict_tif, predict_folder
|
| 5 |
+
|
| 6 |
+
df = predict_tif("image.tif", out_dir="results/", gpu=True)
|
| 7 |
+
df = predict_folder("my_tifs/", out_dir="results/", gpu=True)
|
| 8 |
+
|
| 9 |
+
Both return a pandas DataFrame of per-cell predictions and also write
|
| 10 |
+
per-image CSVs + labeled overlay PNGs into ``out_dir``.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from . import predict as _predict
|
| 18 |
+
from .weights import resolve_cnn_weights, resolve_model_dir
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _load(model_dir=None, cnn_weights=None):
|
| 22 |
+
mdir = resolve_model_dir(model_dir)
|
| 23 |
+
cnn = resolve_cnn_weights(cnn_weights)
|
| 24 |
+
models_dict, scalers, feature_cols, le = _predict.load_models(str(mdir))
|
| 25 |
+
if not models_dict:
|
| 26 |
+
raise RuntimeError(f"No usable models found in {mdir}.")
|
| 27 |
+
return models_dict, scalers, feature_cols, le, cnn
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def predict_tif(
|
| 31 |
+
tif,
|
| 32 |
+
out_dir="results",
|
| 33 |
+
gpu=True,
|
| 34 |
+
model_dir=None,
|
| 35 |
+
cnn_weights=None,
|
| 36 |
+
um_per_px=1.0,
|
| 37 |
+
max_rounds=10,
|
| 38 |
+
label_cells=False,
|
| 39 |
+
):
|
| 40 |
+
"""Segment + predict cell types for a single TIFF. Returns a DataFrame."""
|
| 41 |
+
models_dict, scalers, feature_cols, le, cnn = _load(model_dir, cnn_weights)
|
| 42 |
+
df = _predict.predict_single_tif(
|
| 43 |
+
str(tif), models_dict, scalers, feature_cols, le,
|
| 44 |
+
um_per_px=um_per_px, gpu=gpu, out_dir=str(out_dir),
|
| 45 |
+
max_rounds=max_rounds, cnn_weights=str(cnn) if cnn else None,
|
| 46 |
+
label_cells=label_cells,
|
| 47 |
+
)
|
| 48 |
+
return df
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def predict_folder(
|
| 52 |
+
tif_dir,
|
| 53 |
+
out_dir="results",
|
| 54 |
+
gpu=True,
|
| 55 |
+
model_dir=None,
|
| 56 |
+
cnn_weights=None,
|
| 57 |
+
um_per_px=1.0,
|
| 58 |
+
max_rounds=10,
|
| 59 |
+
label_cells=False,
|
| 60 |
+
pattern="*.tif",
|
| 61 |
+
):
|
| 62 |
+
"""Segment + predict for every TIFF in a folder. Returns a combined
|
| 63 |
+
DataFrame and writes ``all_predictions.csv`` into ``out_dir``."""
|
| 64 |
+
models_dict, scalers, feature_cols, le, cnn = _load(model_dir, cnn_weights)
|
| 65 |
+
tif_paths = sorted(Path(tif_dir).glob(pattern))
|
| 66 |
+
if not tif_paths:
|
| 67 |
+
raise FileNotFoundError(f"No files matching {pattern} in {tif_dir}")
|
| 68 |
+
|
| 69 |
+
tables = []
|
| 70 |
+
for tp in tif_paths:
|
| 71 |
+
try:
|
| 72 |
+
df = _predict.predict_single_tif(
|
| 73 |
+
str(tp), models_dict, scalers, feature_cols, le,
|
| 74 |
+
um_per_px=um_per_px, gpu=gpu, out_dir=str(out_dir),
|
| 75 |
+
max_rounds=max_rounds, cnn_weights=str(cnn) if cnn else None,
|
| 76 |
+
label_cells=label_cells,
|
| 77 |
+
)
|
| 78 |
+
if df is not None:
|
| 79 |
+
tables.append(df)
|
| 80 |
+
except Exception as e: # noqa: BLE001
|
| 81 |
+
print(f" FAILED on {tp.name}: {e}")
|
| 82 |
+
|
| 83 |
+
if not tables:
|
| 84 |
+
return None
|
| 85 |
+
combined = pd.concat(tables, ignore_index=True)
|
| 86 |
+
out = Path(out_dir)
|
| 87 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 88 |
+
combined.to_csv(out / "all_predictions.csv", index=False)
|
| 89 |
+
return combined
|
rootscope/cli.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Command-line entry point for Rootscope: `rootscope ...`
|
| 3 |
+
|
| 4 |
+
Examples
|
| 5 |
+
--------
|
| 6 |
+
# one image (GPU auto-detected)
|
| 7 |
+
rootscope --tif image.tif --out results/
|
| 8 |
+
|
| 9 |
+
# a whole folder of TIFFs
|
| 10 |
+
rootscope --tif-dir my_tifs/ --out results/
|
| 11 |
+
|
| 12 |
+
# force CPU (slow), or point at your own weights
|
| 13 |
+
rootscope --tif image.tif --cpu
|
| 14 |
+
rootscope --tif image.tif --model-dir /path/to/models --cnn-weights /path/to/backbone.pt
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
from . import __version__, api
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _gpu_available() -> bool:
|
| 24 |
+
try:
|
| 25 |
+
import torch
|
| 26 |
+
return torch.cuda.is_available()
|
| 27 |
+
except Exception: # noqa: BLE001
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 32 |
+
p = argparse.ArgumentParser(
|
| 33 |
+
prog="rootscope",
|
| 34 |
+
description="Predict cell types in confocal root-tip TIFF images "
|
| 35 |
+
"(segmentation + prediction in one step).",
|
| 36 |
+
)
|
| 37 |
+
src = p.add_mutually_exclusive_group(required=True)
|
| 38 |
+
src.add_argument("--tif", help="Path to a single TIFF image.")
|
| 39 |
+
src.add_argument("--tif-dir", help="Folder of TIFF images (batch mode).")
|
| 40 |
+
|
| 41 |
+
p.add_argument("--out", "--out-dir", dest="out_dir", default="results",
|
| 42 |
+
help="Output folder for CSVs + overlays (default: results/).")
|
| 43 |
+
p.add_argument("--um-per-px", type=float, default=1.0,
|
| 44 |
+
help="Microns per pixel (default: 1.0).")
|
| 45 |
+
p.add_argument("--max-rounds", type=int, default=10,
|
| 46 |
+
help="Max iterative refinement rounds (default: 10).")
|
| 47 |
+
p.add_argument("--label-cells", action="store_true",
|
| 48 |
+
help="Write the cell-type name inside each cell on the "
|
| 49 |
+
"overlay. Off by default (the text overlaps on dense "
|
| 50 |
+
"sections); the color legend already shows the types.")
|
| 51 |
+
|
| 52 |
+
g = p.add_mutually_exclusive_group()
|
| 53 |
+
g.add_argument("--gpu", dest="gpu", action="store_true", default=None,
|
| 54 |
+
help="Force GPU (default: auto-detect).")
|
| 55 |
+
g.add_argument("--cpu", dest="gpu", action="store_false",
|
| 56 |
+
help="Force CPU (slow).")
|
| 57 |
+
|
| 58 |
+
p.add_argument("--model-dir", default=None,
|
| 59 |
+
help="Folder with trained model weights (default: "
|
| 60 |
+
"auto-download/cache).")
|
| 61 |
+
p.add_argument("--cnn-weights", default=None,
|
| 62 |
+
help="Fine-tuned DINOv2 backbone.pt (default: "
|
| 63 |
+
"auto-download/cache).")
|
| 64 |
+
p.add_argument("--pattern", default="*.tif",
|
| 65 |
+
help="Glob for --tif-dir mode (default: *.tif).")
|
| 66 |
+
p.add_argument("--version", action="version",
|
| 67 |
+
version=f"rootscope {__version__}")
|
| 68 |
+
return p
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def main(argv=None):
|
| 72 |
+
args = build_parser().parse_args(argv)
|
| 73 |
+
use_gpu = _gpu_available() if args.gpu is None else args.gpu
|
| 74 |
+
if args.gpu is None:
|
| 75 |
+
print(f"[rootscope] GPU {'detected' if use_gpu else 'not found (using CPU)'}.")
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
if args.tif:
|
| 79 |
+
df = api.predict_tif(
|
| 80 |
+
args.tif, out_dir=args.out_dir, gpu=use_gpu,
|
| 81 |
+
model_dir=args.model_dir, cnn_weights=args.cnn_weights,
|
| 82 |
+
um_per_px=args.um_per_px, max_rounds=args.max_rounds,
|
| 83 |
+
label_cells=args.label_cells,
|
| 84 |
+
)
|
| 85 |
+
n = 0 if df is None else len(df)
|
| 86 |
+
print(f"\n[rootscope] Done β {n} cell predictions written to {args.out_dir}/")
|
| 87 |
+
else:
|
| 88 |
+
df = api.predict_folder(
|
| 89 |
+
args.tif_dir, out_dir=args.out_dir, gpu=use_gpu,
|
| 90 |
+
model_dir=args.model_dir, cnn_weights=args.cnn_weights,
|
| 91 |
+
um_per_px=args.um_per_px, max_rounds=args.max_rounds,
|
| 92 |
+
label_cells=args.label_cells, pattern=args.pattern,
|
| 93 |
+
)
|
| 94 |
+
n = 0 if df is None else len(df)
|
| 95 |
+
print(f"\n[rootscope] Done β {n} total predictions written to {args.out_dir}/")
|
| 96 |
+
except (FileNotFoundError, RuntimeError) as e:
|
| 97 |
+
print(f"\n[rootscope] ERROR: {e}", file=sys.stderr)
|
| 98 |
+
sys.exit(1)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|
rootscope/cnn_embeddings.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Extract DINOv2 ViT-S/14 embeddings for each cell in a segmentation mask.
|
| 3 |
+
|
| 4 |
+
For each cell, crops a patch around the cell's bounding box (with padding),
|
| 5 |
+
resizes to 224x224, and passes through DINOv2 to get a 384-dim embedding.
|
| 6 |
+
|
| 7 |
+
Returns a DataFrame with columns cnn_emb_0 ... cnn_emb_383 indexed by cell_id.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import warnings
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from skimage.measure import regionprops
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_dinov2(weights_path=None, use_gpu=True):
|
| 17 |
+
"""Load the DINOv2 backbone (optionally with fine-tuned weights) onto the
|
| 18 |
+
right device and put it in eval mode.
|
| 19 |
+
|
| 20 |
+
Building this hits ``torch.hub`` and reads an ~85 MB state dict, so a
|
| 21 |
+
long-running caller (a web server) should call this once at startup and
|
| 22 |
+
pass the result to ``extract_cnn_embeddings(model=...)``. Returns None if
|
| 23 |
+
the backbone cannot be loaded.
|
| 24 |
+
"""
|
| 25 |
+
try:
|
| 26 |
+
import torch
|
| 27 |
+
except ImportError:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"PyTorch not available - skipping CNN embedding extraction. "
|
| 30 |
+
"Install torch + torchvision to enable DINOv2 features."
|
| 31 |
+
)
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
device = torch.device("cpu")
|
| 35 |
+
if use_gpu and torch.cuda.is_available():
|
| 36 |
+
device = torch.device("cuda")
|
| 37 |
+
try:
|
| 38 |
+
print(f" CNN embeddings: using GPU ({torch.cuda.get_device_name(0)})")
|
| 39 |
+
except Exception: # noqa: BLE001
|
| 40 |
+
# ZeroGPU and similar lazy-allocation setups report cuda as
|
| 41 |
+
# available before a device is actually attached.
|
| 42 |
+
print(" CNN embeddings: using GPU")
|
| 43 |
+
else:
|
| 44 |
+
if use_gpu:
|
| 45 |
+
print(" CNN embeddings: GPU requested but not available, using CPU")
|
| 46 |
+
else:
|
| 47 |
+
print(" CNN embeddings: using CPU")
|
| 48 |
+
|
| 49 |
+
# Determine which architecture to load. If weights_path is provided and
|
| 50 |
+
# a sibling meta.json exists (written by finetune_dinov2.py), honor the
|
| 51 |
+
# `arch` / `hub_name` recorded there. Otherwise default to ViT-S/14.
|
| 52 |
+
hub_name = "dinov2_vits14_reg"
|
| 53 |
+
if weights_path is not None:
|
| 54 |
+
from pathlib import Path as _P
|
| 55 |
+
import json as _json
|
| 56 |
+
meta_path = _P(weights_path).parent / "meta.json"
|
| 57 |
+
if meta_path.exists():
|
| 58 |
+
try:
|
| 59 |
+
with open(meta_path) as _f:
|
| 60 |
+
_meta = _json.load(_f)
|
| 61 |
+
hub_name = _meta.get("hub_name", hub_name)
|
| 62 |
+
except Exception:
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
print(f" CNN embeddings: loading {hub_name}...")
|
| 66 |
+
try:
|
| 67 |
+
model = torch.hub.load(
|
| 68 |
+
'facebookresearch/dinov2', hub_name, verbose=False
|
| 69 |
+
)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
warnings.warn(
|
| 72 |
+
f"Failed to load DINOv2 model: {e}. "
|
| 73 |
+
"Skipping CNN embedding extraction."
|
| 74 |
+
)
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
if weights_path is not None:
|
| 78 |
+
try:
|
| 79 |
+
state = torch.load(weights_path, map_location="cpu")
|
| 80 |
+
missing, unexpected = model.load_state_dict(state, strict=False)
|
| 81 |
+
print(f" CNN embeddings: loaded fine-tuned weights from "
|
| 82 |
+
f"{weights_path} (missing={len(missing)}, unexpected={len(unexpected)})")
|
| 83 |
+
except Exception as e:
|
| 84 |
+
warnings.warn(f"Failed to load fine-tuned weights ({e}); using pretrained.")
|
| 85 |
+
|
| 86 |
+
model = model.to(device)
|
| 87 |
+
model.eval()
|
| 88 |
+
return model
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def extract_cnn_embeddings(masks, img_rgb, batch_size=64, use_gpu=True,
|
| 92 |
+
padding=16, weights_path=None, model=None):
|
| 93 |
+
"""
|
| 94 |
+
Extract DINOv2 ViT-S/14 embeddings for each cell in the segmentation mask.
|
| 95 |
+
|
| 96 |
+
Parameters
|
| 97 |
+
----------
|
| 98 |
+
masks : np.ndarray (H, W) int32
|
| 99 |
+
Cell segmentation mask (0 = background, >0 = cell IDs).
|
| 100 |
+
img_rgb : np.ndarray (H, W, 3) uint8
|
| 101 |
+
Original RGB image.
|
| 102 |
+
batch_size : int
|
| 103 |
+
Number of cells to process at once.
|
| 104 |
+
use_gpu : bool
|
| 105 |
+
Move model to CUDA if available.
|
| 106 |
+
padding : int
|
| 107 |
+
Extra pixels around each cell's bounding box for context.
|
| 108 |
+
|
| 109 |
+
Returns
|
| 110 |
+
-------
|
| 111 |
+
pd.DataFrame
|
| 112 |
+
Columns: cell_id, cnn_emb_0, cnn_emb_1, ..., cnn_emb_383
|
| 113 |
+
"""
|
| 114 |
+
try:
|
| 115 |
+
import torch
|
| 116 |
+
import torchvision.transforms as T
|
| 117 |
+
except ImportError:
|
| 118 |
+
warnings.warn(
|
| 119 |
+
"PyTorch not available - skipping CNN embedding extraction. "
|
| 120 |
+
"Install torch + torchvision to enable DINOv2 features."
|
| 121 |
+
)
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
if model is None:
|
| 125 |
+
model = load_dinov2(weights_path=weights_path, use_gpu=use_gpu)
|
| 126 |
+
if model is None:
|
| 127 |
+
return None
|
| 128 |
+
device = next(model.parameters()).device
|
| 129 |
+
|
| 130 |
+
# DINOv2 preprocessing: resize to 224x224, normalize with ImageNet stats
|
| 131 |
+
transform = T.Compose([
|
| 132 |
+
T.ToPILImage(),
|
| 133 |
+
T.Resize((224, 224)),
|
| 134 |
+
T.ToTensor(),
|
| 135 |
+
T.Normalize(mean=[0.485, 0.456, 0.406],
|
| 136 |
+
std=[0.229, 0.224, 0.225]),
|
| 137 |
+
])
|
| 138 |
+
|
| 139 |
+
H, W = masks.shape
|
| 140 |
+
props = regionprops(masks)
|
| 141 |
+
|
| 142 |
+
if not props:
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
# Handle grayscale: if all channels are identical, it's grayscale
|
| 146 |
+
# DINOv2 expects 3-channel input; grayscale is already repeated to RGB
|
| 147 |
+
# by ensure_rgb_uint8, but double-check
|
| 148 |
+
if img_rgb.ndim == 2:
|
| 149 |
+
img_rgb = np.stack([img_rgb, img_rgb, img_rgb], axis=-1)
|
| 150 |
+
elif img_rgb.shape[-1] == 1:
|
| 151 |
+
img_rgb = np.concatenate([img_rgb, img_rgb, img_rgb], axis=-1)
|
| 152 |
+
|
| 153 |
+
# Collect cell patches
|
| 154 |
+
cell_ids = []
|
| 155 |
+
patches = []
|
| 156 |
+
|
| 157 |
+
for p in props:
|
| 158 |
+
cid = p.label
|
| 159 |
+
# Bounding box: (min_row, min_col, max_row, max_col)
|
| 160 |
+
r0, c0, r1, c1 = p.bbox
|
| 161 |
+
|
| 162 |
+
# Add padding for context
|
| 163 |
+
r0_pad = max(0, r0 - padding)
|
| 164 |
+
c0_pad = max(0, c0 - padding)
|
| 165 |
+
r1_pad = min(H, r1 + padding)
|
| 166 |
+
c1_pad = min(W, c1 + padding)
|
| 167 |
+
|
| 168 |
+
patch = img_rgb[r0_pad:r1_pad, c0_pad:c1_pad].copy()
|
| 169 |
+
|
| 170 |
+
# Ensure patch is not empty
|
| 171 |
+
if patch.shape[0] == 0 or patch.shape[1] == 0:
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
cell_ids.append(cid)
|
| 175 |
+
patches.append(patch)
|
| 176 |
+
|
| 177 |
+
if not patches:
|
| 178 |
+
return None
|
| 179 |
+
|
| 180 |
+
# Process in batches
|
| 181 |
+
all_embeddings = []
|
| 182 |
+
n_cells = len(patches)
|
| 183 |
+
|
| 184 |
+
with torch.no_grad():
|
| 185 |
+
for start in range(0, n_cells, batch_size):
|
| 186 |
+
end = min(start + batch_size, n_cells)
|
| 187 |
+
batch_tensors = []
|
| 188 |
+
|
| 189 |
+
for patch in patches[start:end]:
|
| 190 |
+
tensor = transform(patch)
|
| 191 |
+
batch_tensors.append(tensor)
|
| 192 |
+
|
| 193 |
+
batch = torch.stack(batch_tensors).to(device)
|
| 194 |
+
embeddings = model(batch) # (batch_size, 384)
|
| 195 |
+
all_embeddings.append(embeddings.cpu().numpy())
|
| 196 |
+
|
| 197 |
+
all_embeddings = np.vstack(all_embeddings) # (n_cells, 384)
|
| 198 |
+
emb_dim = all_embeddings.shape[1]
|
| 199 |
+
|
| 200 |
+
# Build DataFrame
|
| 201 |
+
emb_cols = [f"cnn_emb_{i}" for i in range(emb_dim)]
|
| 202 |
+
df = pd.DataFrame(all_embeddings, columns=emb_cols)
|
| 203 |
+
df.insert(0, "cell_id", cell_ids)
|
| 204 |
+
|
| 205 |
+
print(f" CNN embeddings: extracted {emb_dim}-dim embeddings for "
|
| 206 |
+
f"{len(cell_ids)} cells")
|
| 207 |
+
|
| 208 |
+
return df
|
rootscope/extract_features.py
ADDED
|
@@ -0,0 +1,1724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Extract cell features from TIF/BMP pairs into a single table.
|
| 3 |
+
Segments cells with Cellpose-SAM, computes BFS layer index,
|
| 4 |
+
extracts shape/size/intensity features from TIF, and assigns
|
| 5 |
+
cell type from BMP color overlay.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
# Full pipeline (all pairs)
|
| 9 |
+
python extract_features.py \
|
| 10 |
+
--metadata metadata_with_tif_sizes3.csv \
|
| 11 |
+
--tif-dir ./tif --bmp-dir ./bmp --gpu
|
| 12 |
+
|
| 13 |
+
# Single species/stage
|
| 14 |
+
python extract_features.py \
|
| 15 |
+
--metadata metadata_with_tif_sizes3.csv \
|
| 16 |
+
--tif-dir ./tif --bmp-dir ./bmp \
|
| 17 |
+
--species Cannum --stage Maturation --gpu
|
| 18 |
+
|
| 19 |
+
# Quick layer-index check on a single TIF (no BMP needed)
|
| 20 |
+
python extract_features.py --single tif/Sarcanum_Meristem1.aivia.tif --gpu
|
| 21 |
+
|
| 22 |
+
Output:
|
| 23 |
+
- all_cell_features.csv (all pairs combined)
|
| 24 |
+
- features_{species}_{stage}.csv (per group)
|
| 25 |
+
- layers_*.png (layer overlay per image)
|
| 26 |
+
- debug_classmask_*.png (BMP class overlay per image)
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import os
|
| 31 |
+
import re
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pandas as pd
|
| 34 |
+
import cv2
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 37 |
+
from scipy import ndimage
|
| 38 |
+
from scipy.ndimage import binary_fill_holes, label as ndlabel
|
| 39 |
+
from skimage.io import imread
|
| 40 |
+
from skimage.measure import regionprops
|
| 41 |
+
from skimage.morphology import (
|
| 42 |
+
binary_closing, binary_opening, remove_small_objects, disk, binary_erosion,
|
| 43 |
+
)
|
| 44 |
+
from skimage.segmentation import find_boundaries
|
| 45 |
+
from collections import deque, defaultdict
|
| 46 |
+
from cellpose import models
|
| 47 |
+
from tqdm import tqdm
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
# CONFIG
|
| 52 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
|
| 54 |
+
CELL_CLASSES = {
|
| 55 |
+
"root_cap": 0,
|
| 56 |
+
"epidermis": 1,
|
| 57 |
+
"exodermis": 2,
|
| 58 |
+
"cortex": 3,
|
| 59 |
+
"endodermis": 4,
|
| 60 |
+
"pericycle": 5,
|
| 61 |
+
"xylem": 6,
|
| 62 |
+
"phloem": 7,
|
| 63 |
+
"stele": 8,
|
| 64 |
+
}
|
| 65 |
+
LABEL_TO_NAME = {v: k for k, v in CELL_CLASSES.items()}
|
| 66 |
+
|
| 67 |
+
# HSV ranges in OpenCV scale (H:0-180, S:0-255, V:0-255)
|
| 68 |
+
COLOR_RANGES = {
|
| 69 |
+
"phloem": [(0, 180, 0, 30, 210, 255)],
|
| 70 |
+
"cortex": [(35, 85, 50, 255, 40, 255)],
|
| 71 |
+
"epidermis": [(100, 130, 50, 255, 80, 255)],
|
| 72 |
+
"stele": [(80, 100, 50, 255, 100, 255)],
|
| 73 |
+
"exodermis": [(20, 38, 40, 255, 50, 255)],
|
| 74 |
+
"endodermis": [(5, 22, 80, 255, 60, 255)],
|
| 75 |
+
"pericycle": [(125, 155, 20, 255, 30, 255)],
|
| 76 |
+
"root_cap": [(150, 175, 40, 255, 80, 255)],
|
| 77 |
+
"xylem": [(0, 8, 150, 255, 120, 255),
|
| 78 |
+
(175, 180, 150, 255, 120, 255)],
|
| 79 |
+
}
|
| 80 |
+
COLOR_PROCESS_ORDER = [
|
| 81 |
+
"phloem", "cortex", "epidermis", "stele", "exodermis",
|
| 82 |
+
"endodermis", "pericycle", "root_cap", "xylem",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
+
# IMAGE LOADING
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
|
| 90 |
+
def _normalize_to_uint8(img):
|
| 91 |
+
if img.dtype == np.uint8:
|
| 92 |
+
return img
|
| 93 |
+
img_f = img.astype(np.float32)
|
| 94 |
+
lo = float(np.percentile(img_f, 1))
|
| 95 |
+
hi = float(np.percentile(img_f, 99))
|
| 96 |
+
img_f = (img_f - lo) / (hi - lo + 1e-8)
|
| 97 |
+
return (np.clip(img_f, 0.0, 1.0) * 255.0).astype(np.uint8)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def to_2d(img, mode="max"):
|
| 101 |
+
if img.ndim == 2:
|
| 102 |
+
return img
|
| 103 |
+
if img.ndim == 3:
|
| 104 |
+
if img.shape[-1] in (3, 4):
|
| 105 |
+
return img
|
| 106 |
+
return img[img.shape[0] // 2] if mode == "mid" else img.max(axis=0)
|
| 107 |
+
if img.ndim == 4:
|
| 108 |
+
return img[img.shape[0] // 2] if mode == "mid" else img.max(axis=0)
|
| 109 |
+
raise ValueError(f"Unsupported ndim={img.ndim}, shape={img.shape}")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def ensure_rgb_uint8(img, stack_mode="max"):
|
| 113 |
+
img2 = to_2d(img, mode=stack_mode)
|
| 114 |
+
if img2.ndim == 2:
|
| 115 |
+
g = _normalize_to_uint8(img2)
|
| 116 |
+
return np.stack([g, g, g], axis=-1)
|
| 117 |
+
if img2.ndim == 3:
|
| 118 |
+
if img2.shape[-1] == 1:
|
| 119 |
+
g = _normalize_to_uint8(img2[..., 0])
|
| 120 |
+
return np.stack([g, g, g], axis=-1)
|
| 121 |
+
return _normalize_to_uint8(img2[..., :3])
|
| 122 |
+
raise ValueError(f"Unsupported shape after reduction: {img2.shape}")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def to_grayscale_float(img_rgb_uint8):
|
| 126 |
+
return (0.299 * img_rgb_uint8[..., 0].astype(np.float32) +
|
| 127 |
+
0.587 * img_rgb_uint8[..., 1].astype(np.float32) +
|
| 128 |
+
0.114 * img_rgb_uint8[..., 2].astype(np.float32))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 132 |
+
# METADATA PARSER
|
| 133 |
+
# βββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββ
|
| 134 |
+
|
| 135 |
+
def _parse_size(s):
|
| 136 |
+
m = re.match(r"(\d+)\s*x\s*(\d+)", str(s).strip())
|
| 137 |
+
return (int(m.group(1)), int(m.group(2))) if m else (None, None)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _parse_scale(s):
|
| 141 |
+
# Match Β΅ (micro sign U+00B5), ΞΌ (Greek mu U+03BC), and u
|
| 142 |
+
m = re.match(r"([\d.]+)\s*[uΞΌΒ΅\u00b5\u03bc]m/px", str(s).strip())
|
| 143 |
+
return float(m.group(1)) if m else None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def parse_metadata(csv_path, tif_dir, bmp_dir):
|
| 147 |
+
tif_dir = Path(tif_dir)
|
| 148 |
+
bmp_dir = Path(bmp_dir)
|
| 149 |
+
df = pd.read_csv(csv_path)
|
| 150 |
+
df.columns = df.columns.str.strip().str.lower()
|
| 151 |
+
df["bmp_w"], df["bmp_h"] = zip(*df["bmp_size"].apply(_parse_size))
|
| 152 |
+
df["tif_w"], df["tif_h"] = zip(*df["tif_size"].apply(_parse_size))
|
| 153 |
+
df["um_per_px"] = df["scale_ratio"].apply(_parse_scale)
|
| 154 |
+
df["bmp_path"] = df["bmp_filename"].apply(lambda f: str(bmp_dir / f))
|
| 155 |
+
df["tif_path"] = df["tif_matched"].apply(lambda f: str(tif_dir / f))
|
| 156 |
+
print(f" Loaded {len(df)} pairs from {csv_path}")
|
| 157 |
+
return df
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def get_pairs(df, species=None, stage=None):
|
| 161 |
+
subset = df.copy()
|
| 162 |
+
if species:
|
| 163 |
+
subset = subset[subset["species"].str.lower() == species.lower()]
|
| 164 |
+
if stage:
|
| 165 |
+
subset = subset[subset["stage"].str.lower() == stage.lower()]
|
| 166 |
+
return subset.to_dict("records")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 170 |
+
# CELLPOSE-SAM SEGMENTATION
|
| 171 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 172 |
+
|
| 173 |
+
def load_cellpose_model(use_gpu=True):
|
| 174 |
+
"""Build the Cellpose-SAM model. Expensive (downloads/loads weights), so
|
| 175 |
+
long-running callers such as a web server should build it once and pass it
|
| 176 |
+
to ``segment_cellpose_sam(model=...)``."""
|
| 177 |
+
return models.CellposeModel(gpu=use_gpu, pretrained_model="cpsam")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def segment_cellpose_sam(img_rgb_uint8, use_gpu=True, diameter=None,
|
| 181 |
+
cellprob_threshold=0.0, flow_threshold=0.4,
|
| 182 |
+
min_size=30, model=None):
|
| 183 |
+
if model is None:
|
| 184 |
+
model = load_cellpose_model(use_gpu=use_gpu)
|
| 185 |
+
masks, _, _ = model.eval(
|
| 186 |
+
img_rgb_uint8,
|
| 187 |
+
channels=[0, 0],
|
| 188 |
+
diameter=diameter,
|
| 189 |
+
cellprob_threshold=cellprob_threshold,
|
| 190 |
+
flow_threshold=flow_threshold,
|
| 191 |
+
min_size=min_size,
|
| 192 |
+
)
|
| 193 |
+
return masks.astype(np.int32)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
+
# TISSUE MASK & BFS LAYER INDEX
|
| 198 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
+
|
| 200 |
+
def build_tissue_mask(masks, close_radius=5, open_radius=1,
|
| 201 |
+
min_tissue_obj=500):
|
| 202 |
+
"""
|
| 203 |
+
Build a clean tissue mask with NO internal holes.
|
| 204 |
+
Only the outer boundary should exist so BFS assigns layers correctly.
|
| 205 |
+
"""
|
| 206 |
+
tissue = masks > 0
|
| 207 |
+
|
| 208 |
+
if min_tissue_obj > 0:
|
| 209 |
+
tissue = remove_small_objects(tissue, min_size=min_tissue_obj)
|
| 210 |
+
if open_radius > 0:
|
| 211 |
+
tissue = binary_opening(tissue, footprint=disk(open_radius))
|
| 212 |
+
if close_radius > 0:
|
| 213 |
+
tissue = binary_closing(tissue, footprint=disk(close_radius))
|
| 214 |
+
|
| 215 |
+
# Keep only the largest connected component
|
| 216 |
+
labeled, n_components = ndlabel(tissue)
|
| 217 |
+
if n_components > 1:
|
| 218 |
+
sizes = np.bincount(labeled.ravel())
|
| 219 |
+
sizes[0] = 0
|
| 220 |
+
largest = sizes.argmax()
|
| 221 |
+
tissue = labeled == largest
|
| 222 |
+
|
| 223 |
+
# Fill ALL internal holes
|
| 224 |
+
tissue = binary_fill_holes(tissue)
|
| 225 |
+
tissue = binary_closing(tissue, footprint=disk(close_radius))
|
| 226 |
+
tissue = binary_fill_holes(tissue)
|
| 227 |
+
|
| 228 |
+
return tissue.astype(bool)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def build_cell_adjacency(masks):
|
| 232 |
+
"""Build adjacency graph: which cells touch which."""
|
| 233 |
+
H, W = masks.shape
|
| 234 |
+
adjacency = defaultdict(set)
|
| 235 |
+
ys, xs = np.nonzero(find_boundaries(masks, mode="inner"))
|
| 236 |
+
for y, x in zip(ys, xs):
|
| 237 |
+
a = int(masks[y, x])
|
| 238 |
+
if a == 0:
|
| 239 |
+
continue
|
| 240 |
+
for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
| 241 |
+
ny, nx = y + dy, x + dx
|
| 242 |
+
if 0 <= ny < H and 0 <= nx < W:
|
| 243 |
+
b = int(masks[ny, nx])
|
| 244 |
+
if b != 0 and b != a:
|
| 245 |
+
adjacency[a].add(b)
|
| 246 |
+
adjacency[b].add(a)
|
| 247 |
+
return adjacency
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _normalized_radial_position(centroids_y, centroids_x, tissue_mask):
|
| 251 |
+
"""
|
| 252 |
+
Compute normalized radial position for each cell: 0 = outermost, 1 = center.
|
| 253 |
+
|
| 254 |
+
For each cell, find its angle from the tissue center, then find the
|
| 255 |
+
boundary distance at that angle. Normalize cell distance by that
|
| 256 |
+
local boundary distance.
|
| 257 |
+
|
| 258 |
+
This corrects for irregular (non-circular) root shapes so that cells
|
| 259 |
+
in the same concentric ring get the same normalized depth regardless
|
| 260 |
+
of which side of the root they're on.
|
| 261 |
+
"""
|
| 262 |
+
from scipy.ndimage import gaussian_filter1d as gf1d
|
| 263 |
+
|
| 264 |
+
# Tissue center of mass
|
| 265 |
+
ys, xs = np.where(tissue_mask)
|
| 266 |
+
center_y = ys.mean()
|
| 267 |
+
center_x = xs.mean()
|
| 268 |
+
|
| 269 |
+
# Compute angle and distance from center for all cells
|
| 270 |
+
dy = centroids_y - center_y
|
| 271 |
+
dx = centroids_x - center_x
|
| 272 |
+
angles = np.arctan2(dy, dx)
|
| 273 |
+
dists = np.sqrt(dy**2 + dx**2)
|
| 274 |
+
|
| 275 |
+
# Build boundary profile: 95th-pctl cell distance at each angle
|
| 276 |
+
n_angle_bins = 72 # 5Β° per bin
|
| 277 |
+
angle_bins = np.linspace(-np.pi, np.pi, n_angle_bins + 1)
|
| 278 |
+
max_dist_per_angle = np.full(n_angle_bins, np.median(dists))
|
| 279 |
+
|
| 280 |
+
for i in range(n_angle_bins):
|
| 281 |
+
mask = (angles >= angle_bins[i]) & (angles < angle_bins[i+1])
|
| 282 |
+
if mask.sum() > 0:
|
| 283 |
+
max_dist_per_angle[i] = np.percentile(dists[mask], 95)
|
| 284 |
+
|
| 285 |
+
# Circular smoothing of boundary profile
|
| 286 |
+
ext = np.concatenate([max_dist_per_angle[-5:],
|
| 287 |
+
max_dist_per_angle,
|
| 288 |
+
max_dist_per_angle[:5]])
|
| 289 |
+
max_dist_per_angle = gf1d(ext, sigma=2.0)[5:-5]
|
| 290 |
+
|
| 291 |
+
# Normalize each cell's distance
|
| 292 |
+
norm = np.zeros(len(centroids_y))
|
| 293 |
+
for i in range(len(centroids_y)):
|
| 294 |
+
bin_idx = np.clip(
|
| 295 |
+
np.searchsorted(angle_bins, angles[i]) - 1, 0, n_angle_bins - 1
|
| 296 |
+
)
|
| 297 |
+
boundary_r = max_dist_per_angle[bin_idx]
|
| 298 |
+
if boundary_r > 1.0:
|
| 299 |
+
norm[i] = 1.0 - dists[i] / boundary_r
|
| 300 |
+
else:
|
| 301 |
+
norm[i] = 0.0
|
| 302 |
+
|
| 303 |
+
return np.clip(norm, 0, 1)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def compute_layer_index_edt(masks, tissue_mask):
|
| 307 |
+
"""
|
| 308 |
+
Assign layer index using EDT (Euclidean Distance Transform) directly.
|
| 309 |
+
|
| 310 |
+
Layer 0 = outermost cells (touching tissue boundary).
|
| 311 |
+
Each successive ring inward increments by 1.
|
| 312 |
+
|
| 313 |
+
Strategy:
|
| 314 |
+
1. Compute EDT from the tissue boundary (distance of each pixel
|
| 315 |
+
from the nearest background pixel).
|
| 316 |
+
2. For each cell, compute its median EDT distance.
|
| 317 |
+
3. Estimate ring width from the median cell diameter.
|
| 318 |
+
4. Bin cells into layers by dividing their EDT distance by ring width.
|
| 319 |
+
|
| 320 |
+
This avoids BFS spiraling by assigning layers purely from geometry.
|
| 321 |
+
"""
|
| 322 |
+
adjacency = build_cell_adjacency(masks)
|
| 323 |
+
|
| 324 |
+
props = regionprops(masks)
|
| 325 |
+
if not props:
|
| 326 |
+
return {}, 0, adjacency
|
| 327 |
+
|
| 328 |
+
# EDT: distance from tissue boundary (0 at edge, increases inward)
|
| 329 |
+
edt = ndimage.distance_transform_edt(tissue_mask)
|
| 330 |
+
|
| 331 |
+
# For each cell, compute median EDT distance of its pixels
|
| 332 |
+
cids = []
|
| 333 |
+
edt_dists = []
|
| 334 |
+
areas = []
|
| 335 |
+
for p in props:
|
| 336 |
+
cid = p.label
|
| 337 |
+
cell_pixels = masks == cid
|
| 338 |
+
med_dist = float(np.median(edt[cell_pixels]))
|
| 339 |
+
cids.append(int(cid))
|
| 340 |
+
edt_dists.append(med_dist)
|
| 341 |
+
areas.append(p.area)
|
| 342 |
+
|
| 343 |
+
cids = np.array(cids)
|
| 344 |
+
edt_dists = np.array(edt_dists)
|
| 345 |
+
areas = np.array(areas)
|
| 346 |
+
|
| 347 |
+
# Estimate ring width = median cell diameter (equivalent circle)
|
| 348 |
+
med_diam = float(np.median(np.sqrt(areas / np.pi) * 2))
|
| 349 |
+
# Use 0.8x diameter as ring step (cells overlap slightly between rings)
|
| 350 |
+
ring_width = max(med_diam * 0.8, 3.0)
|
| 351 |
+
|
| 352 |
+
# Assign layer = floor(edt_distance / ring_width)
|
| 353 |
+
layer_lookup = {}
|
| 354 |
+
for i in range(len(cids)):
|
| 355 |
+
layer_lookup[int(cids[i])] = int(edt_dists[i] / ring_width)
|
| 356 |
+
|
| 357 |
+
n_layers = max(layer_lookup.values()) + 1 if layer_lookup else 0
|
| 358 |
+
return layer_lookup, n_layers, adjacency
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 362 |
+
# BMP COLOR TO CLASS LABEL
|
| 363 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 364 |
+
|
| 365 |
+
def create_class_mask_from_bmp(bmp_path):
|
| 366 |
+
bmp_rgb = np.array(Image.open(str(bmp_path)).convert("RGB"))
|
| 367 |
+
bmp_hsv = cv2.cvtColor(bmp_rgb, cv2.COLOR_RGB2HSV)
|
| 368 |
+
|
| 369 |
+
h, w = bmp_hsv.shape[:2]
|
| 370 |
+
class_mask = np.full((h, w), -1, dtype=np.int8)
|
| 371 |
+
confidence = np.zeros((h, w), dtype=np.float32)
|
| 372 |
+
sat = bmp_hsv[:, :, 1].astype(np.float32) / 255.0
|
| 373 |
+
val = bmp_hsv[:, :, 2].astype(np.float32) / 255.0
|
| 374 |
+
|
| 375 |
+
for class_name in COLOR_PROCESS_ORDER:
|
| 376 |
+
ranges = COLOR_RANGES[class_name]
|
| 377 |
+
label = CELL_CLASSES[class_name]
|
| 378 |
+
combined = np.zeros((h, w), dtype=bool)
|
| 379 |
+
for (h_lo, h_hi, s_lo, s_hi, v_lo, v_hi) in ranges:
|
| 380 |
+
lower = np.array([h_lo, s_lo, v_lo])
|
| 381 |
+
upper = np.array([h_hi, s_hi, v_hi])
|
| 382 |
+
combined |= cv2.inRange(bmp_hsv, lower, upper) > 0
|
| 383 |
+
|
| 384 |
+
conf = val * (1.0 - sat) if class_name == "phloem" else sat * val
|
| 385 |
+
update = combined & (conf >= confidence)
|
| 386 |
+
class_mask[update] = label
|
| 387 |
+
confidence[update] = conf[update]
|
| 388 |
+
|
| 389 |
+
return class_mask
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def resize_class_mask_to_tif(class_mask, tif_h, tif_w):
|
| 393 |
+
return cv2.resize(
|
| 394 |
+
class_mask.astype(np.float32), (tif_w, tif_h),
|
| 395 |
+
interpolation=cv2.INTER_NEAREST
|
| 396 |
+
).astype(np.int8)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def assign_cell_type(cell_masks, class_mask_resized):
|
| 400 |
+
cell_ids = np.unique(cell_masks)
|
| 401 |
+
cell_ids = cell_ids[cell_ids > 0]
|
| 402 |
+
labels = {}
|
| 403 |
+
confidences = {}
|
| 404 |
+
for cid in cell_ids:
|
| 405 |
+
pixels = class_mask_resized[cell_masks == cid]
|
| 406 |
+
valid = pixels[pixels >= 0]
|
| 407 |
+
if len(valid) == 0:
|
| 408 |
+
labels[cid] = -1
|
| 409 |
+
confidences[cid] = 0.0
|
| 410 |
+
continue
|
| 411 |
+
counts = np.bincount(valid.astype(int), minlength=9)
|
| 412 |
+
best = counts.argmax()
|
| 413 |
+
labels[cid] = int(best)
|
| 414 |
+
confidences[cid] = float(counts[best]) / len(valid)
|
| 415 |
+
return labels, confidences
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 419 |
+
# VASCULAR POLE COUNTING
|
| 420 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 421 |
+
|
| 422 |
+
def count_vascular_poles(cell_type_labels, adjacency, masks):
|
| 423 |
+
"""
|
| 424 |
+
Count phloem and xylem poles (spatially connected clusters).
|
| 425 |
+
A pole is a group of adjacent cells of the same vascular type.
|
| 426 |
+
|
| 427 |
+
Returns:
|
| 428 |
+
n_phloem_poles, n_xylem_poles,
|
| 429 |
+
phloem_pole_map (cell_id -> pole_id),
|
| 430 |
+
xylem_pole_map (cell_id -> pole_id),
|
| 431 |
+
phloem_pole_centroids [(cy, cx), ...],
|
| 432 |
+
xylem_pole_centroids [(cy, cx), ...]
|
| 433 |
+
"""
|
| 434 |
+
props_lookup = {p.label: p for p in regionprops(masks)}
|
| 435 |
+
|
| 436 |
+
results = {}
|
| 437 |
+
for vtype, vlabel in [("phloem", CELL_CLASSES["phloem"]),
|
| 438 |
+
("xylem", CELL_CLASSES["xylem"])]:
|
| 439 |
+
# Find cells of this type
|
| 440 |
+
type_cells = {cid for cid, lbl in cell_type_labels.items()
|
| 441 |
+
if lbl == vlabel}
|
| 442 |
+
|
| 443 |
+
# BFS to find connected clusters via adjacency
|
| 444 |
+
visited = set()
|
| 445 |
+
pole_map = {}
|
| 446 |
+
pole_centroids = []
|
| 447 |
+
pole_id = 0
|
| 448 |
+
|
| 449 |
+
for start in type_cells:
|
| 450 |
+
if start in visited:
|
| 451 |
+
continue
|
| 452 |
+
# BFS from this cell
|
| 453 |
+
cluster = []
|
| 454 |
+
queue = deque([start])
|
| 455 |
+
visited.add(start)
|
| 456 |
+
while queue:
|
| 457 |
+
cid = queue.popleft()
|
| 458 |
+
cluster.append(cid)
|
| 459 |
+
pole_map[cid] = pole_id
|
| 460 |
+
for nbr in adjacency.get(cid, set()):
|
| 461 |
+
if nbr in type_cells and nbr not in visited:
|
| 462 |
+
visited.add(nbr)
|
| 463 |
+
queue.append(nbr)
|
| 464 |
+
|
| 465 |
+
# Compute centroid of this pole
|
| 466 |
+
cys, cxs = [], []
|
| 467 |
+
for cid in cluster:
|
| 468 |
+
if cid in props_lookup:
|
| 469 |
+
cy, cx = props_lookup[cid].centroid
|
| 470 |
+
cys.append(cy)
|
| 471 |
+
cxs.append(cx)
|
| 472 |
+
if cys:
|
| 473 |
+
pole_centroids.append((np.mean(cys), np.mean(cxs)))
|
| 474 |
+
pole_id += 1
|
| 475 |
+
|
| 476 |
+
results[vtype] = {
|
| 477 |
+
"n_poles": pole_id,
|
| 478 |
+
"pole_map": pole_map,
|
| 479 |
+
"pole_centroids": pole_centroids,
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
return results
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def compute_pole_features(cell_id, centroid_y, centroid_x, pole_info):
|
| 486 |
+
"""Compute per-cell features related to vascular poles."""
|
| 487 |
+
phloem_info = pole_info.get("phloem", {})
|
| 488 |
+
xylem_info = pole_info.get("xylem", {})
|
| 489 |
+
|
| 490 |
+
n_phloem_poles = phloem_info.get("n_poles", 0)
|
| 491 |
+
n_xylem_poles = xylem_info.get("n_poles", 0)
|
| 492 |
+
|
| 493 |
+
# Distance to nearest phloem pole centroid
|
| 494 |
+
phloem_centroids = phloem_info.get("pole_centroids", [])
|
| 495 |
+
if phloem_centroids:
|
| 496 |
+
dists = [np.sqrt((centroid_y - cy)**2 + (centroid_x - cx)**2)
|
| 497 |
+
for cy, cx in phloem_centroids]
|
| 498 |
+
dist_to_nearest_phloem = round(float(min(dists)), 2)
|
| 499 |
+
else:
|
| 500 |
+
dist_to_nearest_phloem = -1.0
|
| 501 |
+
|
| 502 |
+
# Distance to nearest xylem pole centroid
|
| 503 |
+
xylem_centroids = xylem_info.get("pole_centroids", [])
|
| 504 |
+
if xylem_centroids:
|
| 505 |
+
dists = [np.sqrt((centroid_y - cy)**2 + (centroid_x - cx)**2)
|
| 506 |
+
for cy, cx in xylem_centroids]
|
| 507 |
+
dist_to_nearest_xylem = round(float(min(dists)), 2)
|
| 508 |
+
else:
|
| 509 |
+
dist_to_nearest_xylem = -1.0
|
| 510 |
+
|
| 511 |
+
return {
|
| 512 |
+
"n_phloem_poles": n_phloem_poles,
|
| 513 |
+
"n_xylem_poles": n_xylem_poles,
|
| 514 |
+
"dist_to_nearest_phloem_pole": dist_to_nearest_phloem,
|
| 515 |
+
"dist_to_nearest_xylem_pole": dist_to_nearest_xylem,
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 520 |
+
# FEATURE EXTRACTION
|
| 521 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 522 |
+
|
| 523 |
+
def extract_all_features(masks, img_rgb, um_per_px, layer_lookup, adjacency,
|
| 524 |
+
tissue_mask=None, pole_info=None):
|
| 525 |
+
from scipy.stats import skew, kurtosis
|
| 526 |
+
|
| 527 |
+
gray = to_grayscale_float(img_rgb)
|
| 528 |
+
|
| 529 |
+
# Root center = center-of-mass of all cells
|
| 530 |
+
all_cells = masks > 0
|
| 531 |
+
if all_cells.any():
|
| 532 |
+
img_cy, img_cx = ndimage.center_of_mass(all_cells)
|
| 533 |
+
else:
|
| 534 |
+
img_cy, img_cx = masks.shape[0] / 2, masks.shape[1] / 2
|
| 535 |
+
|
| 536 |
+
ys, xs = np.where(all_cells)
|
| 537 |
+
max_radius = np.sqrt((ys - img_cy)**2 + (xs - img_cx)**2).max() if len(ys) > 0 else 1.0
|
| 538 |
+
|
| 539 |
+
# EDT from tissue boundary (continuous distance, better than layer_index for ML)
|
| 540 |
+
if tissue_mask is not None:
|
| 541 |
+
edt = ndimage.distance_transform_edt(tissue_mask)
|
| 542 |
+
edt_max = float(edt.max()) if edt.max() > 0 else 1.0
|
| 543 |
+
else:
|
| 544 |
+
edt = None
|
| 545 |
+
edt_max = 1.0
|
| 546 |
+
|
| 547 |
+
props = regionprops(masks, intensity_image=gray)
|
| 548 |
+
|
| 549 |
+
# Pre-compute per-cell areas, layers, intensities, and centroids for neighbor features
|
| 550 |
+
cell_areas = {}
|
| 551 |
+
cell_intensities = {}
|
| 552 |
+
cell_centroids = {} # {cid: (cy, cx)}
|
| 553 |
+
for p in props:
|
| 554 |
+
cell_areas[p.label] = p.area
|
| 555 |
+
cell_px = masks == p.label
|
| 556 |
+
cell_intensities[p.label] = float(gray[cell_px].mean())
|
| 557 |
+
cell_centroids[p.label] = p.centroid # (row, col) = (y, x)
|
| 558 |
+
|
| 559 |
+
# Check if image is truly multi-channel (not grayscale duplicated to RGB)
|
| 560 |
+
is_color = not np.array_equal(img_rgb[..., 0], img_rgb[..., 1])
|
| 561 |
+
r_ch = img_rgb[..., 0].astype(np.float32)
|
| 562 |
+
g_ch = img_rgb[..., 1].astype(np.float32)
|
| 563 |
+
b_ch = img_rgb[..., 2].astype(np.float32)
|
| 564 |
+
|
| 565 |
+
# Pre-compute n_layers for layer_fraction
|
| 566 |
+
n_layers = max(layer_lookup.values()) + 1 if layer_lookup else 1
|
| 567 |
+
|
| 568 |
+
# Pre-compute per-layer cell counts and areas (thin ring vs thick cortex)
|
| 569 |
+
layer_cell_counts = defaultdict(int)
|
| 570 |
+
layer_cell_areas = defaultdict(list)
|
| 571 |
+
for cid, lv in layer_lookup.items():
|
| 572 |
+
if lv >= 0:
|
| 573 |
+
layer_cell_counts[lv] += 1
|
| 574 |
+
if cid in cell_areas:
|
| 575 |
+
layer_cell_areas[lv].append(cell_areas[cid])
|
| 576 |
+
|
| 577 |
+
# Pre-compute max cells in any layer (for thin-ring detection)
|
| 578 |
+
max_layer_cell_count = max(layer_cell_counts.values()) if layer_cell_counts else 1
|
| 579 |
+
|
| 580 |
+
# Global area stats for relative size features
|
| 581 |
+
all_areas = np.array([p.area for p in props])
|
| 582 |
+
global_median_area = float(np.median(all_areas)) if len(all_areas) > 0 else 1.0
|
| 583 |
+
global_mean_area = float(np.mean(all_areas)) if len(all_areas) > 0 else 1.0
|
| 584 |
+
global_std_area = float(np.std(all_areas)) if len(all_areas) > 0 else 1.0
|
| 585 |
+
|
| 586 |
+
# Pre-compute which cells touch background (no cell = masks==0)
|
| 587 |
+
# This directly checks each cell's border pixels for adjacency to empty space.
|
| 588 |
+
# Epidermis cells always touch background; exodermis/endodermis do NOT.
|
| 589 |
+
H, W = masks.shape
|
| 590 |
+
touches_bg = set()
|
| 591 |
+
|
| 592 |
+
# For each cell, check if any pixel at its inner boundary is adjacent to masks==0
|
| 593 |
+
inner_boundary = find_boundaries(masks, mode="inner")
|
| 594 |
+
bys, bxs = np.nonzero(inner_boundary)
|
| 595 |
+
for by, bx in zip(bys, bxs):
|
| 596 |
+
cid_here = int(masks[by, bx])
|
| 597 |
+
if cid_here == 0 or cid_here in touches_bg:
|
| 598 |
+
continue
|
| 599 |
+
for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
| 600 |
+
ny, nx = by + dy, bx + dx
|
| 601 |
+
if 0 <= ny < H and 0 <= nx < W:
|
| 602 |
+
if masks[ny, nx] == 0:
|
| 603 |
+
touches_bg.add(cid_here)
|
| 604 |
+
break
|
| 605 |
+
else:
|
| 606 |
+
# Cell is at image edge = touches background
|
| 607 |
+
touches_bg.add(cid_here)
|
| 608 |
+
break
|
| 609 |
+
|
| 610 |
+
# Pre-compute which cells neighbor a boundary cell (= exodermis signal)
|
| 611 |
+
# Exodermis is always adjacent to epidermis (which touches background)
|
| 612 |
+
neighbors_boundary = set()
|
| 613 |
+
for cid in touches_bg:
|
| 614 |
+
for nbr in adjacency.get(cid, set()):
|
| 615 |
+
if nbr not in touches_bg:
|
| 616 |
+
neighbors_boundary.add(nbr)
|
| 617 |
+
|
| 618 |
+
# Pre-compute Sobel gradient magnitude for cell wall contrast feature
|
| 619 |
+
_sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
|
| 620 |
+
_sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
|
| 621 |
+
sobel_mag = np.sqrt(_sobel_x**2 + _sobel_y**2)
|
| 622 |
+
|
| 623 |
+
records = []
|
| 624 |
+
for p in props:
|
| 625 |
+
cid = p.label
|
| 626 |
+
cy, cx = p.centroid
|
| 627 |
+
dist_px = np.sqrt((cy - img_cy)**2 + (cx - img_cx)**2)
|
| 628 |
+
|
| 629 |
+
area = p.area
|
| 630 |
+
perim = p.perimeter if p.perimeter > 0 else 1.0
|
| 631 |
+
compactness = (4.0 * np.pi * area) / (perim ** 2)
|
| 632 |
+
|
| 633 |
+
major = p.major_axis_length if p.major_axis_length > 0 else 1.0
|
| 634 |
+
minor = p.minor_axis_length if p.minor_axis_length > 0 else 1.0
|
| 635 |
+
|
| 636 |
+
cell_px = masks == cid
|
| 637 |
+
gray_vals = gray[cell_px]
|
| 638 |
+
|
| 639 |
+
# EDT-based depth features
|
| 640 |
+
if edt is not None:
|
| 641 |
+
edt_vals = edt[cell_px]
|
| 642 |
+
edt_median = float(np.median(edt_vals))
|
| 643 |
+
edt_normalized = round(edt_median / edt_max, 4)
|
| 644 |
+
else:
|
| 645 |
+
edt_median = 0.0
|
| 646 |
+
edt_normalized = 0.0
|
| 647 |
+
|
| 648 |
+
# --- Neighbor context features ---
|
| 649 |
+
neighbors = adjacency.get(cid, set())
|
| 650 |
+
n_neighbors = len(neighbors)
|
| 651 |
+
neighbor_layers = [layer_lookup.get(n, -1) for n in neighbors if layer_lookup.get(n, -1) >= 0]
|
| 652 |
+
neighbor_areas = [cell_areas.get(n, 0) for n in neighbors if n in cell_areas]
|
| 653 |
+
|
| 654 |
+
mean_neighbor_layer = float(np.mean(neighbor_layers)) if neighbor_layers else -1.0
|
| 655 |
+
std_neighbor_layer = float(np.std(neighbor_layers)) if len(neighbor_layers) > 1 else 0.0
|
| 656 |
+
mean_neighbor_area = float(np.mean(neighbor_areas)) if neighbor_areas else 0.0
|
| 657 |
+
|
| 658 |
+
my_layer = layer_lookup.get(cid, -1)
|
| 659 |
+
layer_fraction = round(my_layer / max(n_layers - 1, 1), 4) if my_layer >= 0 else 0.0
|
| 660 |
+
is_boundary_cell = 1 if my_layer == 0 else 0
|
| 661 |
+
|
| 662 |
+
# Layer difference from neighbors (helps distinguish tissue boundaries)
|
| 663 |
+
layer_diff_from_neighbors = float(np.mean([abs(my_layer - nl) for nl in neighbor_layers])) if neighbor_layers and my_layer >= 0 else 0.0
|
| 664 |
+
|
| 665 |
+
# Area ratio vs neighbors (tissue types have characteristic size differences)
|
| 666 |
+
area_ratio_to_neighbors = round(area / mean_neighbor_area, 4) if mean_neighbor_area > 0 else 1.0
|
| 667 |
+
|
| 668 |
+
# --- Ring topology features (epidermis/exodermis/endodermis) ---
|
| 669 |
+
|
| 670 |
+
# 1. Does this cell touch the tissue background?
|
| 671 |
+
# Epidermis = YES, exodermis/endodermis = NO
|
| 672 |
+
cell_touches_background = 1 if cid in touches_bg else 0
|
| 673 |
+
|
| 674 |
+
# 2. How many cells share this layer? Thin rings (epi/exo/endo)
|
| 675 |
+
# have fewer cells than thick cortex
|
| 676 |
+
cells_in_same_layer = layer_cell_counts.get(my_layer, 0) if my_layer >= 0 else 0
|
| 677 |
+
|
| 678 |
+
# 3. Neighbors inward vs outward β ring cells have neighbors
|
| 679 |
+
# on both sides; cortex cells mostly have same-layer neighbors
|
| 680 |
+
inner_neighbor_count = 0
|
| 681 |
+
outer_neighbor_count = 0
|
| 682 |
+
same_layer_neighbor_count = 0
|
| 683 |
+
if my_layer >= 0:
|
| 684 |
+
for nl in neighbor_layers:
|
| 685 |
+
if nl > my_layer:
|
| 686 |
+
inner_neighbor_count += 1
|
| 687 |
+
elif nl < my_layer:
|
| 688 |
+
outer_neighbor_count += 1
|
| 689 |
+
else:
|
| 690 |
+
same_layer_neighbor_count += 1
|
| 691 |
+
|
| 692 |
+
frac_neighbors_same_layer = round(
|
| 693 |
+
same_layer_neighbor_count / max(n_neighbors, 1), 4
|
| 694 |
+
)
|
| 695 |
+
frac_neighbors_inner = round(
|
| 696 |
+
inner_neighbor_count / max(n_neighbors, 1), 4
|
| 697 |
+
)
|
| 698 |
+
frac_neighbors_outer = round(
|
| 699 |
+
outer_neighbor_count / max(n_neighbors, 1), 4
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
# 4. Layer from inside (endodermis is always close to center)
|
| 703 |
+
layer_from_inside = (n_layers - 1 - my_layer) if my_layer >= 0 else -1
|
| 704 |
+
|
| 705 |
+
# 5. Intensity gradient: difference between this cell and
|
| 706 |
+
# inner/outer neighbors (structural tissue differences)
|
| 707 |
+
my_intensity = cell_intensities.get(cid, 0.0)
|
| 708 |
+
inner_nbr_intensities = [cell_intensities.get(n, 0) for n in neighbors
|
| 709 |
+
if layer_lookup.get(n, -1) > my_layer and n in cell_intensities]
|
| 710 |
+
outer_nbr_intensities = [cell_intensities.get(n, 0) for n in neighbors
|
| 711 |
+
if layer_lookup.get(n, -1) < my_layer and n in cell_intensities]
|
| 712 |
+
radial_intensity_gradient = 0.0
|
| 713 |
+
if inner_nbr_intensities and outer_nbr_intensities:
|
| 714 |
+
radial_intensity_gradient = float(np.mean(inner_nbr_intensities)) - float(np.mean(outer_nbr_intensities))
|
| 715 |
+
elif inner_nbr_intensities:
|
| 716 |
+
radial_intensity_gradient = float(np.mean(inner_nbr_intensities)) - my_intensity
|
| 717 |
+
elif outer_nbr_intensities:
|
| 718 |
+
radial_intensity_gradient = my_intensity - float(np.mean(outer_nbr_intensities))
|
| 719 |
+
|
| 720 |
+
# 6. Neighbor layer range (ring cells span exactly 2 adjacent layers,
|
| 721 |
+
# cortex cells often have neighbors all at the same layer)
|
| 722 |
+
neighbor_layer_range = (max(neighbor_layers) - min(neighbor_layers)) if neighbor_layers else 0
|
| 723 |
+
|
| 724 |
+
# 7. Is this cell adjacent to a boundary cell?
|
| 725 |
+
# Exodermis = YES (neighbors epidermis), cortex/endodermis = NO
|
| 726 |
+
cell_neighbors_boundary = 1 if cid in neighbors_boundary else 0
|
| 727 |
+
|
| 728 |
+
# 8. Min layer among neighbors β exodermis neighbors include
|
| 729 |
+
# epidermis (layer 0-1), cortex neighbors are all mid-layers
|
| 730 |
+
min_neighbor_layer = min(neighbor_layers) if neighbor_layers else -1
|
| 731 |
+
max_neighbor_layer = max(neighbor_layers) if neighbor_layers else -1
|
| 732 |
+
|
| 733 |
+
# 9. How many of this cell's neighbors touch background?
|
| 734 |
+
# Epidermis: many neighbors also touch bg; exodermis: some do;
|
| 735 |
+
# deeper cells: none do
|
| 736 |
+
n_neighbors_touching_bg = sum(1 for n in neighbors if n in touches_bg)
|
| 737 |
+
|
| 738 |
+
# --- Texture features ---
|
| 739 |
+
intensity_cv = round(float(gray_vals.std() / (gray_vals.mean() + 1e-8)), 4)
|
| 740 |
+
intensity_skewness = round(float(skew(gray_vals)), 4) if len(gray_vals) > 2 else 0.0
|
| 741 |
+
intensity_kurtosis = round(float(kurtosis(gray_vals)), 4) if len(gray_vals) > 2 else 0.0
|
| 742 |
+
|
| 743 |
+
# Intensity percentiles (more robust than min/max)
|
| 744 |
+
intensity_p10 = round(float(np.percentile(gray_vals, 10)), 2)
|
| 745 |
+
intensity_p90 = round(float(np.percentile(gray_vals, 90)), 2)
|
| 746 |
+
|
| 747 |
+
# --- Shape features ---
|
| 748 |
+
area_perimeter_ratio = round(area / perim, 4)
|
| 749 |
+
equivalent_diameter = round(float(p.equivalent_diameter), 2)
|
| 750 |
+
|
| 751 |
+
# Angular position around root center (helps distinguish radially asymmetric tissues)
|
| 752 |
+
angular_position = round(float(np.arctan2(cy - img_cy, cx - img_cx)), 4)
|
| 753 |
+
|
| 754 |
+
# --- Enhanced polar coordinate features ---
|
| 755 |
+
# Cyclical encoding of angle (avoids discontinuity at -pi/+pi)
|
| 756 |
+
sin_angular = round(float(np.sin(angular_position)), 4)
|
| 757 |
+
cos_angular = round(float(np.cos(angular_position)), 4)
|
| 758 |
+
norm_r = dist_px / max_radius if max_radius > 0 else 0
|
| 759 |
+
radial_x_sin = round(norm_r * sin_angular, 4)
|
| 760 |
+
radial_x_cos = round(norm_r * cos_angular, 4)
|
| 761 |
+
|
| 762 |
+
# --- Directional neighbor features (polar-based) ---
|
| 763 |
+
# Classify neighbors as inward/outward (radially) or CW/CCW (tangentially)
|
| 764 |
+
# relative to root center, then summarize their morphology
|
| 765 |
+
inward_nbr_areas = []
|
| 766 |
+
outward_nbr_areas = []
|
| 767 |
+
cw_nbr_areas = []
|
| 768 |
+
ccw_nbr_areas = []
|
| 769 |
+
inward_nbr_intensities = []
|
| 770 |
+
outward_nbr_intensities = []
|
| 771 |
+
cw_nbr_intensities = []
|
| 772 |
+
ccw_nbr_intensities = []
|
| 773 |
+
|
| 774 |
+
my_angle = np.arctan2(cy - img_cy, cx - img_cx)
|
| 775 |
+
my_dist = dist_px
|
| 776 |
+
|
| 777 |
+
for nbr in neighbors:
|
| 778 |
+
if nbr not in cell_centroids:
|
| 779 |
+
continue
|
| 780 |
+
ny, nx = cell_centroids[nbr]
|
| 781 |
+
nbr_dist = np.sqrt((ny - img_cy)**2 + (nx - img_cx)**2)
|
| 782 |
+
nbr_angle = np.arctan2(ny - img_cy, nx - img_cx)
|
| 783 |
+
nbr_area = cell_areas.get(nbr, 0)
|
| 784 |
+
nbr_intens = cell_intensities.get(nbr, 0.0)
|
| 785 |
+
|
| 786 |
+
# Radial classification: inward (closer to center) vs outward
|
| 787 |
+
if nbr_dist < my_dist - 1.0:
|
| 788 |
+
inward_nbr_areas.append(nbr_area)
|
| 789 |
+
inward_nbr_intensities.append(nbr_intens)
|
| 790 |
+
elif nbr_dist > my_dist + 1.0:
|
| 791 |
+
outward_nbr_areas.append(nbr_area)
|
| 792 |
+
outward_nbr_intensities.append(nbr_intens)
|
| 793 |
+
|
| 794 |
+
# Tangential classification: clockwise vs counter-clockwise
|
| 795 |
+
angle_diff = nbr_angle - my_angle
|
| 796 |
+
# Normalize to [-pi, pi]
|
| 797 |
+
if angle_diff > np.pi:
|
| 798 |
+
angle_diff -= 2 * np.pi
|
| 799 |
+
elif angle_diff < -np.pi:
|
| 800 |
+
angle_diff += 2 * np.pi
|
| 801 |
+
|
| 802 |
+
if angle_diff > 0.01: # CCW
|
| 803 |
+
ccw_nbr_areas.append(nbr_area)
|
| 804 |
+
ccw_nbr_intensities.append(nbr_intens)
|
| 805 |
+
elif angle_diff < -0.01: # CW
|
| 806 |
+
cw_nbr_areas.append(nbr_area)
|
| 807 |
+
cw_nbr_intensities.append(nbr_intens)
|
| 808 |
+
|
| 809 |
+
radial_inward_nbr_area = round(float(np.mean(inward_nbr_areas)), 2) if inward_nbr_areas else 0.0
|
| 810 |
+
radial_outward_nbr_area = round(float(np.mean(outward_nbr_areas)), 2) if outward_nbr_areas else 0.0
|
| 811 |
+
cw_nbr_area = round(float(np.mean(cw_nbr_areas)), 2) if cw_nbr_areas else 0.0
|
| 812 |
+
ccw_nbr_area = round(float(np.mean(ccw_nbr_areas)), 2) if ccw_nbr_areas else 0.0
|
| 813 |
+
radial_inward_nbr_intensity = round(float(np.mean(inward_nbr_intensities)), 4) if inward_nbr_intensities else 0.0
|
| 814 |
+
radial_outward_nbr_intensity = round(float(np.mean(outward_nbr_intensities)), 4) if outward_nbr_intensities else 0.0
|
| 815 |
+
cw_nbr_intensity = round(float(np.mean(cw_nbr_intensities)), 4) if cw_nbr_intensities else 0.0
|
| 816 |
+
ccw_nbr_intensity = round(float(np.mean(ccw_nbr_intensities)), 4) if ccw_nbr_intensities else 0.0
|
| 817 |
+
|
| 818 |
+
# (Polar-direction neighbor cell types are computed as a
|
| 819 |
+
# post-processing step via compute_neighbor_celltypes(), not here.)
|
| 820 |
+
|
| 821 |
+
# --- Exodermis-specific features ---
|
| 822 |
+
# Exodermis cells are: large, hexagonal, single-layer ring
|
| 823 |
+
|
| 824 |
+
# 1. Relative size: exodermis cells are BIGGER than other cell types
|
| 825 |
+
area_zscore = round((area - global_mean_area) / max(global_std_area, 1.0), 4)
|
| 826 |
+
area_ratio_to_global_median = round(area / max(global_median_area, 1.0), 4)
|
| 827 |
+
|
| 828 |
+
# 2. Size rank within same layer (exodermis cells are among the largest)
|
| 829 |
+
layer_areas = layer_cell_areas.get(my_layer, [])
|
| 830 |
+
if layer_areas and len(layer_areas) > 1:
|
| 831 |
+
area_percentile_in_layer = round(
|
| 832 |
+
float(np.searchsorted(np.sort(layer_areas), area)) / len(layer_areas), 4
|
| 833 |
+
)
|
| 834 |
+
else:
|
| 835 |
+
area_percentile_in_layer = 0.5
|
| 836 |
+
|
| 837 |
+
# 3. Size ratio to inner/outer neighbor cells
|
| 838 |
+
inner_nbr_areas = [cell_areas.get(n, 0) for n in neighbors
|
| 839 |
+
if layer_lookup.get(n, -1) > my_layer and n in cell_areas]
|
| 840 |
+
outer_nbr_areas = [cell_areas.get(n, 0) for n in neighbors
|
| 841 |
+
if layer_lookup.get(n, -1) < my_layer and n in cell_areas]
|
| 842 |
+
area_ratio_to_inner = round(
|
| 843 |
+
area / max(float(np.mean(inner_nbr_areas)), 1.0), 4
|
| 844 |
+
) if inner_nbr_areas else 1.0
|
| 845 |
+
area_ratio_to_outer = round(
|
| 846 |
+
area / max(float(np.mean(outer_nbr_areas)), 1.0), 4
|
| 847 |
+
) if outer_nbr_areas else 1.0
|
| 848 |
+
|
| 849 |
+
# 4. Hexagonality: regular hexagon has compactness β 0.9069
|
| 850 |
+
# and ~6 neighbors, low eccentricity, high solidity
|
| 851 |
+
HEXAGON_COMPACTNESS = 0.9069
|
| 852 |
+
hexagonality = round(1.0 - abs(compactness - HEXAGON_COMPACTNESS), 4)
|
| 853 |
+
|
| 854 |
+
# 5. Convex hull vertex count β hexagons have ~6 vertices
|
| 855 |
+
try:
|
| 856 |
+
from skimage.measure import approximate_polygon
|
| 857 |
+
coords = p.coords # (N, 2) array of pixel coordinates
|
| 858 |
+
hull = p.convex_image
|
| 859 |
+
# Count corners of convex hull
|
| 860 |
+
from skimage.measure import find_contours
|
| 861 |
+
contours = find_contours(hull.astype(float), 0.5)
|
| 862 |
+
if contours:
|
| 863 |
+
approx = approximate_polygon(contours[0], tolerance=2.0)
|
| 864 |
+
n_vertices = len(approx) - 1 # -1 because first==last
|
| 865 |
+
else:
|
| 866 |
+
n_vertices = 0
|
| 867 |
+
except Exception:
|
| 868 |
+
n_vertices = 0
|
| 869 |
+
|
| 870 |
+
# --- Thin-ring / boundary features (endodermis & exodermis) ---
|
| 871 |
+
|
| 872 |
+
# 1. Ratio of cells in this layer to the thickest layer
|
| 873 |
+
# Endodermis/exodermis rings are thin β low ratio; cortex is thick β high ratio
|
| 874 |
+
layer_cell_count_ratio = round(
|
| 875 |
+
cells_in_same_layer / max(max_layer_cell_count, 1), 4
|
| 876 |
+
) if my_layer >= 0 else 0.0
|
| 877 |
+
|
| 878 |
+
# 2. Cell counts in adjacent inner/outer layers
|
| 879 |
+
# At endodermis: outer layer (cortex) has MANY cells, inner (pericycle) has FEW
|
| 880 |
+
# At exodermis: outer layer (epidermis) has fewer, inner (cortex) has MANY
|
| 881 |
+
inner_layer = my_layer + 1 if my_layer >= 0 else -1
|
| 882 |
+
outer_layer = my_layer - 1 if my_layer >= 0 else -1
|
| 883 |
+
inner_layer_cell_count = layer_cell_counts.get(inner_layer, 0) if inner_layer >= 0 else 0
|
| 884 |
+
outer_layer_cell_count = layer_cell_counts.get(outer_layer, 0) if outer_layer >= 0 else 0
|
| 885 |
+
|
| 886 |
+
# 3. Gradient in cell count: big jump means tissue boundary
|
| 887 |
+
# Endodermis: outer has many cortex cells, inner has few pericycle β large positive
|
| 888 |
+
# Exodermis: outer has fewer epidermis, inner has many cortex β large negative
|
| 889 |
+
layer_count_gradient = outer_layer_cell_count - inner_layer_cell_count
|
| 890 |
+
|
| 891 |
+
# 4. Am I between layers of very different cell counts?
|
| 892 |
+
# Ring cells sit between a thick layer and a thin layer
|
| 893 |
+
layer_count_asymmetry = round(
|
| 894 |
+
abs(outer_layer_cell_count - inner_layer_cell_count) /
|
| 895 |
+
max(outer_layer_cell_count + inner_layer_cell_count, 1), 4
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
# 5. Mean area in adjacent layers (endodermis neighbors large cortex + small pericycle)
|
| 899 |
+
inner_layer_mean_area = float(np.mean(layer_cell_areas.get(inner_layer, [0]))) if inner_layer >= 0 and inner_layer in layer_cell_areas else 0.0
|
| 900 |
+
outer_layer_mean_area = float(np.mean(layer_cell_areas.get(outer_layer, [0]))) if outer_layer >= 0 and outer_layer in layer_cell_areas else 0.0
|
| 901 |
+
adjacent_layer_area_ratio = round(
|
| 902 |
+
outer_layer_mean_area / max(inner_layer_mean_area, 1.0), 4
|
| 903 |
+
) if inner_layer_mean_area > 0 else 1.0
|
| 904 |
+
|
| 905 |
+
# --- Vascular distinction features (xylem vs stele) ---
|
| 906 |
+
|
| 907 |
+
# 1. Wall thickness proxy: mean intensity of boundary pixels (2px inner ring)
|
| 908 |
+
cell_mask = (masks == cid)
|
| 909 |
+
eroded_mask = binary_erosion(cell_mask, disk(2))
|
| 910 |
+
wall_ring = cell_mask & ~eroded_mask
|
| 911 |
+
wall_pixels = gray[wall_ring]
|
| 912 |
+
wall_thickness_proxy = round(float(wall_pixels.mean()), 2) if wall_pixels.size > 0 else 0.0
|
| 913 |
+
|
| 914 |
+
# 2. Wall-to-lumen ratio: wall mean intensity / interior mean intensity
|
| 915 |
+
interior_pixels = gray[eroded_mask]
|
| 916 |
+
if interior_pixels.size > 0:
|
| 917 |
+
wall_to_lumen_ratio = round(
|
| 918 |
+
float(wall_pixels.mean()) / max(float(interior_pixels.mean()), 1e-8), 4
|
| 919 |
+
) if wall_pixels.size > 0 else 1.0
|
| 920 |
+
else:
|
| 921 |
+
wall_to_lumen_ratio = 1.0
|
| 922 |
+
|
| 923 |
+
# 3. Local area rank in stele: percentile of area among inner 40% of layers
|
| 924 |
+
if n_layers > 0 and layer_from_inside >= 0 and (layer_from_inside / n_layers) < 0.4:
|
| 925 |
+
inner_cell_areas = []
|
| 926 |
+
for lv, areas_list in layer_cell_areas.items():
|
| 927 |
+
lfi = (n_layers - 1 - lv) if lv >= 0 else -1
|
| 928 |
+
if lfi >= 0 and (lfi / n_layers) < 0.4:
|
| 929 |
+
inner_cell_areas.extend(areas_list)
|
| 930 |
+
if len(inner_cell_areas) > 1:
|
| 931 |
+
local_area_rank_in_stele = round(
|
| 932 |
+
float(np.searchsorted(np.sort(inner_cell_areas), area)) / len(inner_cell_areas), 4
|
| 933 |
+
)
|
| 934 |
+
else:
|
| 935 |
+
local_area_rank_in_stele = 0.5
|
| 936 |
+
else:
|
| 937 |
+
local_area_rank_in_stele = 0.5
|
| 938 |
+
|
| 939 |
+
# 4. Neighbor area std: heterogeneous neighbors suggest phloem
|
| 940 |
+
neighbor_area_std = round(float(np.std(neighbor_areas)), 2) if len(neighbor_areas) > 1 else 0.0
|
| 941 |
+
|
| 942 |
+
# 5. Cell wall contrast: mean Sobel gradient magnitude at cell boundary
|
| 943 |
+
wall_sobel = sobel_mag[wall_ring]
|
| 944 |
+
cell_wall_contrast = round(float(wall_sobel.mean()), 2) if wall_sobel.size > 0 else 0.0
|
| 945 |
+
|
| 946 |
+
# --- Enhanced xylem vs stele features ---
|
| 947 |
+
|
| 948 |
+
# 6. Lumen darkness: mean intensity of deep interior (erode 3px)
|
| 949 |
+
# Xylem vessels have large dark lumens; stele parenchyma is more uniform
|
| 950 |
+
eroded_mask_3 = binary_erosion(cell_mask, disk(3))
|
| 951 |
+
deep_interior = gray[eroded_mask_3]
|
| 952 |
+
lumen_darkness = round(float(deep_interior.mean()), 2) if deep_interior.size > 0 else float(gray_vals.mean())
|
| 953 |
+
|
| 954 |
+
# 7. Wall-lumen intensity gap: difference between wall and deep interior
|
| 955 |
+
# Xylem has high gap (bright wall, dark lumen); stele has low gap
|
| 956 |
+
wall_lumen_gap = round(float(wall_pixels.mean()) - lumen_darkness, 2) if wall_pixels.size > 0 else 0.0
|
| 957 |
+
|
| 958 |
+
# 8. Interior intensity std: variation inside the cell
|
| 959 |
+
# Xylem vessels may have heterogeneous interiors (secondary wall patterns)
|
| 960 |
+
interior_intensity_std = round(float(interior_pixels.std()), 2) if interior_pixels.size > 1 else 0.0
|
| 961 |
+
|
| 962 |
+
# 9. Fraction of dark interior pixels: fraction below 25th percentile of image
|
| 963 |
+
# Xylem lumens are often the darkest structures
|
| 964 |
+
if deep_interior.size > 0:
|
| 965 |
+
dark_threshold = float(np.percentile(gray, 25))
|
| 966 |
+
frac_dark_interior = round(float((deep_interior < dark_threshold).sum()) / deep_interior.size, 4)
|
| 967 |
+
else:
|
| 968 |
+
frac_dark_interior = 0.0
|
| 969 |
+
|
| 970 |
+
# 10. Wall ring intensity at multiple erosion depths (profile)
|
| 971 |
+
# Xylem: intensity drops sharply from wall β interior (thick wall, empty lumen)
|
| 972 |
+
# Stele: intensity is relatively uniform across rings
|
| 973 |
+
eroded_1 = binary_erosion(cell_mask, disk(1))
|
| 974 |
+
ring_1 = cell_mask & ~eroded_1 # outermost 1px ring
|
| 975 |
+
ring_2 = eroded_1 & ~eroded_mask # 1-2px ring
|
| 976 |
+
ring1_intensity = round(float(gray[ring_1].mean()), 2) if gray[ring_1].size > 0 else 0.0
|
| 977 |
+
ring2_intensity = round(float(gray[ring_2].mean()), 2) if gray[ring_2].size > 0 else 0.0
|
| 978 |
+
# Radial intensity drop from wall to interior
|
| 979 |
+
wall_interior_gradient = round(ring1_intensity - lumen_darkness, 2)
|
| 980 |
+
|
| 981 |
+
# 11. Neighbor wall thickness similarity: mean wall_thickness of neighbors
|
| 982 |
+
# Xylem cells cluster with other thick-walled cells
|
| 983 |
+
nbr_wall_vals = []
|
| 984 |
+
for nbr in adjacency.get(cid, set()):
|
| 985 |
+
nbr_mask = (masks == nbr)
|
| 986 |
+
nbr_eroded = binary_erosion(nbr_mask, disk(2))
|
| 987 |
+
nbr_wall = nbr_mask & ~nbr_eroded
|
| 988 |
+
nbr_wall_px = gray[nbr_wall]
|
| 989 |
+
if nbr_wall_px.size > 0:
|
| 990 |
+
nbr_wall_vals.append(float(nbr_wall_px.mean()))
|
| 991 |
+
mean_neighbor_wall_thickness = round(float(np.mean(nbr_wall_vals)), 2) if nbr_wall_vals else 0.0
|
| 992 |
+
wall_thickness_vs_neighbors = round(wall_thickness_proxy - mean_neighbor_wall_thickness, 2)
|
| 993 |
+
|
| 994 |
+
# 12. Stele-relative area: ratio of this cell's area to mean area
|
| 995 |
+
# of cells in the inner 40% of layers (xylem vessels are often larger)
|
| 996 |
+
if n_layers > 0 and layer_from_inside >= 0 and (layer_from_inside / n_layers) < 0.4:
|
| 997 |
+
inner_cell_areas_all = []
|
| 998 |
+
for lv, areas_list in layer_cell_areas.items():
|
| 999 |
+
lfi = (n_layers - 1 - lv) if lv >= 0 else -1
|
| 1000 |
+
if lfi >= 0 and (lfi / n_layers) < 0.4:
|
| 1001 |
+
inner_cell_areas_all.extend(areas_list)
|
| 1002 |
+
stele_mean_area = float(np.mean(inner_cell_areas_all)) if inner_cell_areas_all else float(area)
|
| 1003 |
+
area_ratio_to_stele_mean = round(float(area) / max(stele_mean_area, 1.0), 4)
|
| 1004 |
+
else:
|
| 1005 |
+
area_ratio_to_stele_mean = 1.0
|
| 1006 |
+
|
| 1007 |
+
rec = {
|
| 1008 |
+
"cell_id": int(cid),
|
| 1009 |
+
"layer_index": my_layer,
|
| 1010 |
+
"centroid_y": round(cy, 2),
|
| 1011 |
+
"centroid_x": round(cx, 2),
|
| 1012 |
+
"dist_from_centroid_px": round(dist_px, 2),
|
| 1013 |
+
"dist_from_centroid_um": round(dist_px * um_per_px, 2),
|
| 1014 |
+
"normalized_radius": round(dist_px / max_radius, 4) if max_radius > 0 else 0,
|
| 1015 |
+
"edt_distance_px": round(edt_median, 2),
|
| 1016 |
+
"edt_normalized": edt_normalized,
|
| 1017 |
+
"area_px": int(area),
|
| 1018 |
+
"area_um2": round(area * um_per_px ** 2, 2),
|
| 1019 |
+
"perimeter_px": round(perim, 2),
|
| 1020 |
+
"perimeter_um": round(perim * um_per_px, 2),
|
| 1021 |
+
"eccentricity": round(p.eccentricity, 4),
|
| 1022 |
+
"solidity": round(p.solidity, 4),
|
| 1023 |
+
"aspect_ratio": round(major / minor, 4),
|
| 1024 |
+
"compactness": round(compactness, 4),
|
| 1025 |
+
"major_axis_px": round(major, 2),
|
| 1026 |
+
"minor_axis_px": round(minor, 2),
|
| 1027 |
+
"orientation_rad": round(p.orientation, 4),
|
| 1028 |
+
"extent": round(p.extent, 4),
|
| 1029 |
+
"mean_intensity": round(float(gray_vals.mean()), 2),
|
| 1030 |
+
"std_intensity": round(float(gray_vals.std()), 2),
|
| 1031 |
+
"min_intensity": round(float(gray_vals.min()), 2),
|
| 1032 |
+
"max_intensity": round(float(gray_vals.max()), 2),
|
| 1033 |
+
"median_intensity": round(float(np.median(gray_vals)), 2),
|
| 1034 |
+
"intensity_range": round(float(gray_vals.max() - gray_vals.min()), 2),
|
| 1035 |
+
"neighbors_count": n_neighbors,
|
| 1036 |
+
# --- New features ---
|
| 1037 |
+
"layer_fraction": layer_fraction,
|
| 1038 |
+
"is_boundary_cell": is_boundary_cell,
|
| 1039 |
+
"mean_neighbor_layer": round(mean_neighbor_layer, 2),
|
| 1040 |
+
"std_neighbor_layer": round(std_neighbor_layer, 2),
|
| 1041 |
+
"mean_neighbor_area": round(mean_neighbor_area, 2),
|
| 1042 |
+
"layer_diff_from_neighbors": round(layer_diff_from_neighbors, 4),
|
| 1043 |
+
"area_ratio_to_neighbors": area_ratio_to_neighbors,
|
| 1044 |
+
"intensity_cv": intensity_cv,
|
| 1045 |
+
"intensity_skewness": intensity_skewness,
|
| 1046 |
+
"intensity_kurtosis": intensity_kurtosis,
|
| 1047 |
+
"intensity_p10": intensity_p10,
|
| 1048 |
+
"intensity_p90": intensity_p90,
|
| 1049 |
+
"area_perimeter_ratio": area_perimeter_ratio,
|
| 1050 |
+
"equivalent_diameter": equivalent_diameter,
|
| 1051 |
+
"angular_position": angular_position,
|
| 1052 |
+
# Enhanced polar features
|
| 1053 |
+
"sin_angular_position": sin_angular,
|
| 1054 |
+
"cos_angular_position": cos_angular,
|
| 1055 |
+
"radial_x_sin": radial_x_sin,
|
| 1056 |
+
"radial_x_cos": radial_x_cos,
|
| 1057 |
+
# Directional neighbor features (polar-based)
|
| 1058 |
+
"radial_inward_neighbor_area": radial_inward_nbr_area,
|
| 1059 |
+
"radial_outward_neighbor_area": radial_outward_nbr_area,
|
| 1060 |
+
"cw_neighbor_area": cw_nbr_area,
|
| 1061 |
+
"ccw_neighbor_area": ccw_nbr_area,
|
| 1062 |
+
"radial_inward_neighbor_intensity": radial_inward_nbr_intensity,
|
| 1063 |
+
"radial_outward_neighbor_intensity": radial_outward_nbr_intensity,
|
| 1064 |
+
"cw_neighbor_intensity": cw_nbr_intensity,
|
| 1065 |
+
"ccw_neighbor_intensity": ccw_nbr_intensity,
|
| 1066 |
+
# --- Ring topology features (epi/exo/endo) ---
|
| 1067 |
+
"touches_background": cell_touches_background,
|
| 1068 |
+
"cells_in_same_layer": cells_in_same_layer,
|
| 1069 |
+
"frac_neighbors_same_layer": frac_neighbors_same_layer,
|
| 1070 |
+
"frac_neighbors_inner": frac_neighbors_inner,
|
| 1071 |
+
"frac_neighbors_outer": frac_neighbors_outer,
|
| 1072 |
+
"inner_neighbor_count": inner_neighbor_count,
|
| 1073 |
+
"outer_neighbor_count": outer_neighbor_count,
|
| 1074 |
+
"layer_from_inside": layer_from_inside,
|
| 1075 |
+
"radial_intensity_gradient": round(radial_intensity_gradient, 4),
|
| 1076 |
+
"neighbor_layer_range": neighbor_layer_range,
|
| 1077 |
+
"neighbors_boundary_cell": cell_neighbors_boundary,
|
| 1078 |
+
"min_neighbor_layer": min_neighbor_layer,
|
| 1079 |
+
"max_neighbor_layer": max_neighbor_layer,
|
| 1080 |
+
"n_neighbors_touching_bg": n_neighbors_touching_bg,
|
| 1081 |
+
# Exodermis-specific: large, hexagonal, single-layer
|
| 1082 |
+
"area_zscore": area_zscore,
|
| 1083 |
+
"area_ratio_to_global_median": area_ratio_to_global_median,
|
| 1084 |
+
"area_percentile_in_layer": area_percentile_in_layer,
|
| 1085 |
+
"area_ratio_to_inner": area_ratio_to_inner,
|
| 1086 |
+
"area_ratio_to_outer": area_ratio_to_outer,
|
| 1087 |
+
"hexagonality": hexagonality,
|
| 1088 |
+
"n_vertices": n_vertices,
|
| 1089 |
+
# Thin-ring / boundary features (endodermis & exodermis)
|
| 1090 |
+
"layer_cell_count_ratio": layer_cell_count_ratio,
|
| 1091 |
+
"inner_layer_cell_count": inner_layer_cell_count,
|
| 1092 |
+
"outer_layer_cell_count": outer_layer_cell_count,
|
| 1093 |
+
"layer_count_gradient": layer_count_gradient,
|
| 1094 |
+
"layer_count_asymmetry": layer_count_asymmetry,
|
| 1095 |
+
"adjacent_layer_area_ratio": adjacent_layer_area_ratio,
|
| 1096 |
+
# Vascular distinction features
|
| 1097 |
+
"wall_thickness_proxy": wall_thickness_proxy,
|
| 1098 |
+
"wall_to_lumen_ratio": wall_to_lumen_ratio,
|
| 1099 |
+
"local_area_rank_in_stele": local_area_rank_in_stele,
|
| 1100 |
+
"neighbor_area_std": neighbor_area_std,
|
| 1101 |
+
"cell_wall_contrast": cell_wall_contrast,
|
| 1102 |
+
# Enhanced xylem features
|
| 1103 |
+
"lumen_darkness": lumen_darkness,
|
| 1104 |
+
"wall_lumen_gap": wall_lumen_gap,
|
| 1105 |
+
"interior_intensity_std": interior_intensity_std,
|
| 1106 |
+
"frac_dark_interior": frac_dark_interior,
|
| 1107 |
+
"ring1_intensity": ring1_intensity,
|
| 1108 |
+
"ring2_intensity": ring2_intensity,
|
| 1109 |
+
"wall_interior_gradient": wall_interior_gradient,
|
| 1110 |
+
"mean_neighbor_wall_thickness": mean_neighbor_wall_thickness,
|
| 1111 |
+
"wall_thickness_vs_neighbors": wall_thickness_vs_neighbors,
|
| 1112 |
+
"area_ratio_to_stele_mean": area_ratio_to_stele_mean,
|
| 1113 |
+
# (neighbor celltypes added separately via compute_neighbor_celltypes)
|
| 1114 |
+
}
|
| 1115 |
+
|
| 1116 |
+
# Add vascular pole features if available
|
| 1117 |
+
if pole_info:
|
| 1118 |
+
rec.update(compute_pole_features(cid, cy, cx, pole_info))
|
| 1119 |
+
|
| 1120 |
+
# Only add per-channel features if image is actually color
|
| 1121 |
+
if is_color:
|
| 1122 |
+
r_vals = r_ch[cell_px]
|
| 1123 |
+
g_vals = g_ch[cell_px]
|
| 1124 |
+
b_vals = b_ch[cell_px]
|
| 1125 |
+
rec["mean_intensity_r"] = round(float(r_vals.mean()), 2)
|
| 1126 |
+
rec["mean_intensity_g"] = round(float(g_vals.mean()), 2)
|
| 1127 |
+
rec["mean_intensity_b"] = round(float(b_vals.mean()), 2)
|
| 1128 |
+
|
| 1129 |
+
records.append(rec)
|
| 1130 |
+
|
| 1131 |
+
return pd.DataFrame(records)
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
def compute_neighbor_celltypes(df, adjacency, cell_type_labels=None,
|
| 1135 |
+
center=None):
|
| 1136 |
+
"""
|
| 1137 |
+
For each cell, find the nearest adjacent neighbor in each polar
|
| 1138 |
+
direction (radial inward, radial outward, tangential CW, tangential CCW)
|
| 1139 |
+
relative to the tissue center, and look up that neighbor's cell type.
|
| 1140 |
+
|
| 1141 |
+
This is rotation-invariant and biologically meaningful for cross-sections.
|
| 1142 |
+
|
| 1143 |
+
Parameters
|
| 1144 |
+
----------
|
| 1145 |
+
df : pd.DataFrame
|
| 1146 |
+
Must have columns: cell_id, centroid_y, centroid_x.
|
| 1147 |
+
adjacency : dict
|
| 1148 |
+
{cell_id: set of neighbor cell_ids}.
|
| 1149 |
+
cell_type_labels : dict or None
|
| 1150 |
+
{cell_id: int_label} mapping. If None, all set to -1.
|
| 1151 |
+
center : tuple (cy, cx) or None
|
| 1152 |
+
Tissue center coordinates. If None, computed as mean of all centroids.
|
| 1153 |
+
|
| 1154 |
+
Returns
|
| 1155 |
+
-------
|
| 1156 |
+
pd.DataFrame
|
| 1157 |
+
The input df with 4 new columns added:
|
| 1158 |
+
radial_inward_neighbor_celltype, radial_outward_neighbor_celltype,
|
| 1159 |
+
tangential_cw_neighbor_celltype, tangential_ccw_neighbor_celltype.
|
| 1160 |
+
Values are integer-encoded cell types (-1 = no neighbor/background).
|
| 1161 |
+
"""
|
| 1162 |
+
if cell_type_labels is None:
|
| 1163 |
+
cell_type_labels = {}
|
| 1164 |
+
|
| 1165 |
+
# Build centroid lookup
|
| 1166 |
+
centroid_lookup = {}
|
| 1167 |
+
for _, row in df.iterrows():
|
| 1168 |
+
cid = int(row["cell_id"])
|
| 1169 |
+
centroid_lookup[cid] = (row["centroid_y"], row["centroid_x"])
|
| 1170 |
+
|
| 1171 |
+
# Compute tissue center from centroids if not provided
|
| 1172 |
+
if center is None:
|
| 1173 |
+
all_cy = [v[0] for v in centroid_lookup.values()]
|
| 1174 |
+
all_cx = [v[1] for v in centroid_lookup.values()]
|
| 1175 |
+
center_y = float(np.mean(all_cy))
|
| 1176 |
+
center_x = float(np.mean(all_cx))
|
| 1177 |
+
else:
|
| 1178 |
+
center_y, center_x = center
|
| 1179 |
+
|
| 1180 |
+
inward_ct = []
|
| 1181 |
+
outward_ct = []
|
| 1182 |
+
cw_ct = []
|
| 1183 |
+
ccw_ct = []
|
| 1184 |
+
|
| 1185 |
+
for _, row in df.iterrows():
|
| 1186 |
+
cid = int(row["cell_id"])
|
| 1187 |
+
cy, cx = row["centroid_y"], row["centroid_x"]
|
| 1188 |
+
neighbors = adjacency.get(cid, set())
|
| 1189 |
+
|
| 1190 |
+
my_dist = np.sqrt((cy - center_y)**2 + (cx - center_x)**2)
|
| 1191 |
+
my_angle = np.arctan2(cy - center_y, cx - center_x)
|
| 1192 |
+
|
| 1193 |
+
inward_nbr_ct = -1
|
| 1194 |
+
outward_nbr_ct = -1
|
| 1195 |
+
cw_nbr_ct = -1
|
| 1196 |
+
ccw_nbr_ct = -1
|
| 1197 |
+
# Track the most extreme neighbor in each direction
|
| 1198 |
+
best_inward_dr = 0.0 # most negative radial delta (closest to center)
|
| 1199 |
+
best_outward_dr = 0.0 # most positive radial delta (farthest from center)
|
| 1200 |
+
best_cw_angle = 0.0 # most negative angle delta (clockwise)
|
| 1201 |
+
best_ccw_angle = 0.0 # most positive angle delta (counter-clockwise)
|
| 1202 |
+
|
| 1203 |
+
for nbr in neighbors:
|
| 1204 |
+
if nbr not in centroid_lookup:
|
| 1205 |
+
continue
|
| 1206 |
+
ny, nx = centroid_lookup[nbr]
|
| 1207 |
+
nbr_dist = np.sqrt((ny - center_y)**2 + (nx - center_x)**2)
|
| 1208 |
+
nbr_angle = np.arctan2(ny - center_y, nx - center_x)
|
| 1209 |
+
nbr_ct = cell_type_labels.get(nbr, -1)
|
| 1210 |
+
|
| 1211 |
+
# Radial delta: positive = outward, negative = inward
|
| 1212 |
+
dr = nbr_dist - my_dist
|
| 1213 |
+
# Angular delta, normalized to [-pi, pi]
|
| 1214 |
+
dangle = nbr_angle - my_angle
|
| 1215 |
+
if dangle > np.pi:
|
| 1216 |
+
dangle -= 2 * np.pi
|
| 1217 |
+
elif dangle < -np.pi:
|
| 1218 |
+
dangle += 2 * np.pi
|
| 1219 |
+
|
| 1220 |
+
# Classify: radial if |dr| dominates, tangential if |dangle * dist| dominates
|
| 1221 |
+
# Use angular arc length vs radial displacement for fair comparison
|
| 1222 |
+
arc_length = abs(dangle) * my_dist if my_dist > 1.0 else abs(dangle)
|
| 1223 |
+
is_radial = abs(dr) >= arc_length
|
| 1224 |
+
|
| 1225 |
+
if is_radial:
|
| 1226 |
+
if dr < best_inward_dr:
|
| 1227 |
+
best_inward_dr = dr
|
| 1228 |
+
inward_nbr_ct = nbr_ct
|
| 1229 |
+
if dr > best_outward_dr:
|
| 1230 |
+
best_outward_dr = dr
|
| 1231 |
+
outward_nbr_ct = nbr_ct
|
| 1232 |
+
else:
|
| 1233 |
+
if dangle < best_cw_angle:
|
| 1234 |
+
best_cw_angle = dangle
|
| 1235 |
+
cw_nbr_ct = nbr_ct
|
| 1236 |
+
if dangle > best_ccw_angle:
|
| 1237 |
+
best_ccw_angle = dangle
|
| 1238 |
+
ccw_nbr_ct = nbr_ct
|
| 1239 |
+
|
| 1240 |
+
inward_ct.append(inward_nbr_ct)
|
| 1241 |
+
outward_ct.append(outward_nbr_ct)
|
| 1242 |
+
cw_ct.append(cw_nbr_ct)
|
| 1243 |
+
ccw_ct.append(ccw_nbr_ct)
|
| 1244 |
+
|
| 1245 |
+
df = df.copy()
|
| 1246 |
+
df["radial_inward_neighbor_celltype"] = inward_ct
|
| 1247 |
+
df["radial_outward_neighbor_celltype"] = outward_ct
|
| 1248 |
+
df["tangential_cw_neighbor_celltype"] = cw_ct
|
| 1249 |
+
df["tangential_ccw_neighbor_celltype"] = ccw_ct
|
| 1250 |
+
return df
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
def extract_cnn_embedding_features(masks, img_rgb, use_gpu=True, weights_path=None,
|
| 1254 |
+
model=None):
|
| 1255 |
+
"""
|
| 1256 |
+
Extract DINOv2 CNN embeddings for all cells. Returns a DataFrame
|
| 1257 |
+
with cell_id and cnn_emb_* columns, or None if not available.
|
| 1258 |
+
|
| 1259 |
+
If `weights_path` is given, loads a fine-tuned backbone state_dict
|
| 1260 |
+
produced by finetune_dinov2.py (expects a sibling meta.json that
|
| 1261 |
+
records the architecture).
|
| 1262 |
+
"""
|
| 1263 |
+
try:
|
| 1264 |
+
from .cnn_embeddings import extract_cnn_embeddings
|
| 1265 |
+
return extract_cnn_embeddings(masks, img_rgb, use_gpu=use_gpu,
|
| 1266 |
+
weights_path=weights_path, model=model)
|
| 1267 |
+
except ImportError:
|
| 1268 |
+
import warnings
|
| 1269 |
+
warnings.warn("cnn_embeddings module not found β skipping CNN features.")
|
| 1270 |
+
return None
|
| 1271 |
+
except Exception as e:
|
| 1272 |
+
import warnings
|
| 1273 |
+
warnings.warn(f"CNN embedding extraction failed: {e}")
|
| 1274 |
+
return None
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1278 |
+
# VISUALIZATION
|
| 1279 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1280 |
+
|
| 1281 |
+
def _load_font(font_size):
|
| 1282 |
+
for path in [
|
| 1283 |
+
"/usr/share/fonts/liberation/LiberationMono-Regular.ttf",
|
| 1284 |
+
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
| 1285 |
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
| 1286 |
+
]:
|
| 1287 |
+
try:
|
| 1288 |
+
return ImageFont.truetype(path, font_size)
|
| 1289 |
+
except (OSError, IOError):
|
| 1290 |
+
pass
|
| 1291 |
+
return ImageFont.load_default()
|
| 1292 |
+
|
| 1293 |
+
|
| 1294 |
+
def make_layer_colormap(n_layers):
|
| 1295 |
+
base_colors = [
|
| 1296 |
+
(255, 0, 0), # red
|
| 1297 |
+
( 0, 0, 255), # blue
|
| 1298 |
+
(255, 255, 0), # yellow
|
| 1299 |
+
(128, 0, 128), # purple
|
| 1300 |
+
( 0, 180, 0), # green
|
| 1301 |
+
(255, 165, 0), # orange
|
| 1302 |
+
( 0, 255, 255), # cyan
|
| 1303 |
+
(255, 105, 180), # pink
|
| 1304 |
+
( 0, 255, 0), # lime
|
| 1305 |
+
(180, 0, 0), # dark red
|
| 1306 |
+
( 0, 100, 255), # light blue
|
| 1307 |
+
(200, 200, 0), # olive
|
| 1308 |
+
]
|
| 1309 |
+
if n_layers <= 0:
|
| 1310 |
+
return [base_colors[0]]
|
| 1311 |
+
if n_layers <= len(base_colors):
|
| 1312 |
+
return base_colors[:n_layers]
|
| 1313 |
+
# Tile if more layers than base colors
|
| 1314 |
+
repeats = (n_layers // len(base_colors)) + 1
|
| 1315 |
+
tiled = (base_colors * repeats)[:n_layers]
|
| 1316 |
+
return tiled
|
| 1317 |
+
|
| 1318 |
+
|
| 1319 |
+
def save_layer_overlay_png(img_rgb, masks, layer_lookup, n_layers,
|
| 1320 |
+
out_path, alpha=0.45):
|
| 1321 |
+
"""
|
| 1322 |
+
Overlay layer colors on grayscale image with layer number on every cell.
|
| 1323 |
+
"""
|
| 1324 |
+
if n_layers == 0:
|
| 1325 |
+
Image.fromarray(img_rgb).save(str(out_path))
|
| 1326 |
+
return
|
| 1327 |
+
|
| 1328 |
+
H, W = masks.shape
|
| 1329 |
+
colors = make_layer_colormap(n_layers)
|
| 1330 |
+
|
| 1331 |
+
# Build per-pixel layer image
|
| 1332 |
+
layer_img = np.zeros((H, W), dtype=np.int32)
|
| 1333 |
+
for cid, lv in layer_lookup.items():
|
| 1334 |
+
if lv >= 0:
|
| 1335 |
+
layer_img[masks == cid] = lv + 1 # 0=background
|
| 1336 |
+
|
| 1337 |
+
# Colorize layers
|
| 1338 |
+
color_rgb = np.zeros((H, W, 3), dtype=np.uint8)
|
| 1339 |
+
for lv in range(1, n_layers + 1):
|
| 1340 |
+
m = layer_img == lv
|
| 1341 |
+
if m.any():
|
| 1342 |
+
color_rgb[m] = colors[lv - 1]
|
| 1343 |
+
|
| 1344 |
+
# Blend onto grayscale base
|
| 1345 |
+
gray = to_grayscale_float(img_rgb)
|
| 1346 |
+
base = np.stack([gray, gray, gray], axis=-1)
|
| 1347 |
+
mask_f = (layer_img > 0)[..., None].astype(np.float32)
|
| 1348 |
+
blended = base * (1.0 - alpha * mask_f) + color_rgb.astype(np.float32) * (alpha * mask_f)
|
| 1349 |
+
|
| 1350 |
+
# Draw cell boundaries
|
| 1351 |
+
boundaries = find_boundaries(masks, mode='outer')
|
| 1352 |
+
blended[boundaries] = [255, 255, 255]
|
| 1353 |
+
|
| 1354 |
+
im = Image.fromarray(np.clip(blended, 0, 255).astype(np.uint8))
|
| 1355 |
+
draw = ImageDraw.Draw(im)
|
| 1356 |
+
|
| 1357 |
+
# Adaptive font size based on median cell size
|
| 1358 |
+
props = regionprops(masks)
|
| 1359 |
+
med_area = float(np.median([p.area for p in props])) if props else 100.0
|
| 1360 |
+
base_font_size = max(8, min(18, int(np.sqrt(med_area) * 0.35)))
|
| 1361 |
+
font_cache = {}
|
| 1362 |
+
|
| 1363 |
+
for p in props:
|
| 1364 |
+
cid = p.label
|
| 1365 |
+
lv = layer_lookup.get(cid, -1)
|
| 1366 |
+
if lv < 0:
|
| 1367 |
+
continue
|
| 1368 |
+
|
| 1369 |
+
cy, cx = p.centroid
|
| 1370 |
+
ratio = float(p.area) / max(med_area, 1.0)
|
| 1371 |
+
fs = max(8, min(base_font_size, int(round(base_font_size * np.sqrt(ratio)))))
|
| 1372 |
+
if fs not in font_cache:
|
| 1373 |
+
font_cache[fs] = _load_font(fs)
|
| 1374 |
+
font = font_cache[fs]
|
| 1375 |
+
|
| 1376 |
+
x, y = int(round(cx)), int(round(cy))
|
| 1377 |
+
text = str(lv)
|
| 1378 |
+
|
| 1379 |
+
# Black outline then white text
|
| 1380 |
+
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)]:
|
| 1381 |
+
draw.text((x+dx, y+dy), text, fill=(0,0,0), font=font, anchor="mm")
|
| 1382 |
+
draw.text((x, y), text, fill=(255,255,255), font=font, anchor="mm")
|
| 1383 |
+
|
| 1384 |
+
# Legend
|
| 1385 |
+
legend_font = _load_font(12)
|
| 1386 |
+
legend_x, legend_y = 10, max(10, H - (n_layers + 1) * 16 - 10)
|
| 1387 |
+
draw.rectangle(
|
| 1388 |
+
[legend_x - 2, legend_y - 2, legend_x + 110, legend_y + n_layers * 16 + 2],
|
| 1389 |
+
fill=(0, 0, 0)
|
| 1390 |
+
)
|
| 1391 |
+
for i in range(n_layers):
|
| 1392 |
+
color = colors[i]
|
| 1393 |
+
ly = legend_y + i * 16
|
| 1394 |
+
draw.rectangle([legend_x, ly, legend_x + 12, ly + 12], fill=color)
|
| 1395 |
+
draw.text((legend_x + 16, ly), f"Layer {i}", fill=(255,255,255), font=legend_font)
|
| 1396 |
+
|
| 1397 |
+
# Root center marker
|
| 1398 |
+
all_cells = masks > 0
|
| 1399 |
+
if all_cells.any():
|
| 1400 |
+
ctr_y, ctr_x = ndimage.center_of_mass(all_cells)
|
| 1401 |
+
r = 5
|
| 1402 |
+
draw.ellipse([ctr_x-r, ctr_y-r, ctr_x+r, ctr_y+r],
|
| 1403 |
+
fill=(255, 0, 0), outline=(255, 255, 255))
|
| 1404 |
+
|
| 1405 |
+
im.save(str(out_path))
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
+
def save_debug_overlay(class_mask, out_path):
|
| 1409 |
+
palette = {
|
| 1410 |
+
0: (255, 105, 180), # root_cap - pink
|
| 1411 |
+
1: (0, 0, 255), # epidermis - blue
|
| 1412 |
+
2: (255, 255, 0), # exodermis - yellow
|
| 1413 |
+
3: (0, 200, 0), # cortex - green
|
| 1414 |
+
4: (255, 165, 0), # endodermis - orange
|
| 1415 |
+
5: (128, 0, 128), # pericycle - purple
|
| 1416 |
+
6: (255, 0, 0), # xylem - red
|
| 1417 |
+
7: (255, 255, 255), # phloem - white
|
| 1418 |
+
8: (0, 255, 255), # stele - cyan
|
| 1419 |
+
}
|
| 1420 |
+
h, w = class_mask.shape
|
| 1421 |
+
rgb = np.zeros((h, w, 3), dtype=np.uint8)
|
| 1422 |
+
for label, color in palette.items():
|
| 1423 |
+
rgb[class_mask == label] = color
|
| 1424 |
+
Image.fromarray(rgb).save(str(out_path))
|
| 1425 |
+
|
| 1426 |
+
|
| 1427 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1428 |
+
# SINGLE-TIF MODE (quick layer-index visualization)
|
| 1429 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1430 |
+
|
| 1431 |
+
def process_single_tif(tif_path, gpu=True, out_dir="output_layers",
|
| 1432 |
+
diameter=None):
|
| 1433 |
+
"""Segment one TIF and visualize BFS layer indices."""
|
| 1434 |
+
out_dir = Path(out_dir)
|
| 1435 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 1436 |
+
stem = Path(tif_path).stem
|
| 1437 |
+
|
| 1438 |
+
print(f"Processing: {tif_path}")
|
| 1439 |
+
|
| 1440 |
+
# Load
|
| 1441 |
+
img_raw = imread(str(tif_path))
|
| 1442 |
+
img_rgb = ensure_rgb_uint8(img_raw, stack_mode="max")
|
| 1443 |
+
print(f" Image shape: {img_rgb.shape}")
|
| 1444 |
+
|
| 1445 |
+
# Segment
|
| 1446 |
+
print(" Running Cellpose-SAM...")
|
| 1447 |
+
masks = segment_cellpose_sam(img_rgb, use_gpu=gpu, diameter=diameter)
|
| 1448 |
+
n_cells = int(masks.max())
|
| 1449 |
+
print(f" {n_cells} cells found")
|
| 1450 |
+
|
| 1451 |
+
if n_cells == 0:
|
| 1452 |
+
print(" No cells found, skipping.")
|
| 1453 |
+
return
|
| 1454 |
+
|
| 1455 |
+
# BFS layer index
|
| 1456 |
+
print(" Computing EDT layer index...")
|
| 1457 |
+
tissue = build_tissue_mask(masks)
|
| 1458 |
+
layer_lookup, n_layers, adjacency = compute_layer_index_edt(masks, tissue)
|
| 1459 |
+
print(f" {n_layers} layers")
|
| 1460 |
+
|
| 1461 |
+
# Layer overlay
|
| 1462 |
+
overlay_path = out_dir / f"{stem}_layers.png"
|
| 1463 |
+
save_layer_overlay_png(img_rgb, masks, layer_lookup, n_layers, overlay_path)
|
| 1464 |
+
print(f" Saved: {overlay_path}")
|
| 1465 |
+
|
| 1466 |
+
# Save masks
|
| 1467 |
+
masks_path = out_dir / f"{stem}_masks.npy"
|
| 1468 |
+
np.save(str(masks_path), masks)
|
| 1469 |
+
|
| 1470 |
+
# Save CSV
|
| 1471 |
+
csv_path = out_dir / f"{stem}_layers.csv"
|
| 1472 |
+
props = {p.label: p for p in regionprops(masks)}
|
| 1473 |
+
all_cells = masks > 0
|
| 1474 |
+
ctr_y, ctr_x = ndimage.center_of_mass(all_cells) if all_cells.any() else (0, 0)
|
| 1475 |
+
|
| 1476 |
+
with open(csv_path, 'w') as f:
|
| 1477 |
+
f.write("cell_id,layer_index,centroid_y,centroid_x,distance_from_center,area,neighbors\n")
|
| 1478 |
+
for cid in sorted(layer_lookup.keys()):
|
| 1479 |
+
if cid not in props:
|
| 1480 |
+
continue
|
| 1481 |
+
p = props[cid]
|
| 1482 |
+
cy, cx = p.centroid
|
| 1483 |
+
dist = np.sqrt((cy - ctr_y)**2 + (cx - ctr_x)**2)
|
| 1484 |
+
nbrs = len(adjacency.get(cid, set()))
|
| 1485 |
+
f.write(f"{cid},{layer_lookup[cid]},{cy:.1f},{cx:.1f},{dist:.1f},{p.area},{nbrs}\n")
|
| 1486 |
+
print(f" Saved: {csv_path}")
|
| 1487 |
+
print("Done!")
|
| 1488 |
+
|
| 1489 |
+
|
| 1490 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1491 |
+
# FULL PIPELINE (TIF+BMP pairs)
|
| 1492 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1493 |
+
|
| 1494 |
+
def process_pair(tif_path, bmp_path, tif_h, tif_w, um_per_px,
|
| 1495 |
+
species, stage, source_file, gpu=True, out_dir=None,
|
| 1496 |
+
cnn_weights=None):
|
| 1497 |
+
"""
|
| 1498 |
+
Process a single TIF/BMP pair:
|
| 1499 |
+
1. Segment cells with Cellpose-SAM
|
| 1500 |
+
2. Compute BFS layer index
|
| 1501 |
+
3. Extract all features from TIF
|
| 1502 |
+
4. Assign cell type from BMP color
|
| 1503 |
+
"""
|
| 1504 |
+
img_raw = imread(str(tif_path))
|
| 1505 |
+
img_rgb = ensure_rgb_uint8(img_raw, stack_mode="max")
|
| 1506 |
+
|
| 1507 |
+
# Segment
|
| 1508 |
+
print(f" Segmenting (Cellpose-SAM)...")
|
| 1509 |
+
masks = segment_cellpose_sam(img_rgb, use_gpu=gpu)
|
| 1510 |
+
n_cells = int(masks.max())
|
| 1511 |
+
print(f" {n_cells} cells found")
|
| 1512 |
+
|
| 1513 |
+
if n_cells == 0:
|
| 1514 |
+
return None
|
| 1515 |
+
|
| 1516 |
+
# BFS layer index
|
| 1517 |
+
print(f" Computing EDT layer index...")
|
| 1518 |
+
tissue = build_tissue_mask(masks)
|
| 1519 |
+
layer_lookup, n_layers, adjacency = compute_layer_index_edt(masks, tissue)
|
| 1520 |
+
print(f" {n_layers} layers")
|
| 1521 |
+
|
| 1522 |
+
# BMP class labels (extract BEFORE features so we can compute pole info)
|
| 1523 |
+
print(f" Extracting cell types from BMP...")
|
| 1524 |
+
class_mask_bmp = create_class_mask_from_bmp(bmp_path)
|
| 1525 |
+
|
| 1526 |
+
for cls_name, lbl in CELL_CLASSES.items():
|
| 1527 |
+
count = int((class_mask_bmp == lbl).sum())
|
| 1528 |
+
if count > 0:
|
| 1529 |
+
print(f" BMP '{cls_name}': {count} px")
|
| 1530 |
+
|
| 1531 |
+
# Resize BMP class mask to match actual mask dimensions
|
| 1532 |
+
class_mask_resized = resize_class_mask_to_tif(
|
| 1533 |
+
class_mask_bmp, masks.shape[0], masks.shape[1]
|
| 1534 |
+
)
|
| 1535 |
+
|
| 1536 |
+
# Assign cell type by majority vote
|
| 1537 |
+
cell_labels, cell_conf = assign_cell_type(masks, class_mask_resized)
|
| 1538 |
+
|
| 1539 |
+
# Count vascular poles (phloem and xylem clusters)
|
| 1540 |
+
print(f" Counting vascular poles...")
|
| 1541 |
+
pole_info = count_vascular_poles(cell_labels, adjacency, masks)
|
| 1542 |
+
n_ph = pole_info["phloem"]["n_poles"]
|
| 1543 |
+
n_xy = pole_info["xylem"]["n_poles"]
|
| 1544 |
+
print(f" Phloem poles: {n_ph}, Xylem poles: {n_xy}")
|
| 1545 |
+
|
| 1546 |
+
# Extract features (with pole info)
|
| 1547 |
+
print(f" Extracting features...")
|
| 1548 |
+
df = extract_all_features(masks, img_rgb, um_per_px, layer_lookup, adjacency,
|
| 1549 |
+
tissue_mask=tissue, pole_info=pole_info)
|
| 1550 |
+
|
| 1551 |
+
df["cell_type_label"] = df["cell_id"].map(cell_labels)
|
| 1552 |
+
df["cell_type_confidence"] = df["cell_id"].map(cell_conf).round(4)
|
| 1553 |
+
df["cell_type"] = df["cell_type_label"].map(LABEL_TO_NAME)
|
| 1554 |
+
|
| 1555 |
+
# Add neighbor cell type features (using BMP ground-truth labels)
|
| 1556 |
+
print(f" Computing neighbor cell type features...")
|
| 1557 |
+
df = compute_neighbor_celltypes(df, adjacency, cell_type_labels=cell_labels)
|
| 1558 |
+
|
| 1559 |
+
# Add CNN embedding features
|
| 1560 |
+
print(f" Extracting CNN embeddings...")
|
| 1561 |
+
cnn_df = extract_cnn_embedding_features(masks, img_rgb, use_gpu=gpu,
|
| 1562 |
+
weights_path=cnn_weights)
|
| 1563 |
+
if cnn_df is not None:
|
| 1564 |
+
df = df.merge(cnn_df, on="cell_id", how="left")
|
| 1565 |
+
# Fill NaN embeddings with 0 for cells that might have been skipped
|
| 1566 |
+
emb_cols = [c for c in df.columns if c.startswith("cnn_emb_")]
|
| 1567 |
+
df[emb_cols] = df[emb_cols].fillna(0.0)
|
| 1568 |
+
|
| 1569 |
+
# Metadata columns
|
| 1570 |
+
df["species"] = species
|
| 1571 |
+
df["stage"] = stage
|
| 1572 |
+
df["source_file"] = source_file
|
| 1573 |
+
df["n_layers_total"] = n_layers
|
| 1574 |
+
df["um_per_px"] = um_per_px
|
| 1575 |
+
|
| 1576 |
+
# Report
|
| 1577 |
+
typed = df[df["cell_type_label"] >= 0]
|
| 1578 |
+
untyped = df[df["cell_type_label"] < 0]
|
| 1579 |
+
print(f" Classified: {len(typed)}/{n_cells}, Unclassified: {len(untyped)}")
|
| 1580 |
+
if len(typed) > 0:
|
| 1581 |
+
for ct, cnt in typed["cell_type"].value_counts().items():
|
| 1582 |
+
print(f" {ct}: {cnt}")
|
| 1583 |
+
|
| 1584 |
+
# Save debug overlays
|
| 1585 |
+
if out_dir:
|
| 1586 |
+
stem = Path(tif_path).stem
|
| 1587 |
+
debug_path = Path(out_dir) / f"debug_classmask_{stem}.png"
|
| 1588 |
+
save_debug_overlay(class_mask_resized, debug_path)
|
| 1589 |
+
|
| 1590 |
+
layer_path = Path(out_dir) / f"layers_{stem}.png"
|
| 1591 |
+
save_layer_overlay_png(img_rgb, masks, layer_lookup, n_layers, layer_path)
|
| 1592 |
+
print(f" Saved layer overlay: {layer_path}")
|
| 1593 |
+
|
| 1594 |
+
return df
|
| 1595 |
+
|
| 1596 |
+
|
| 1597 |
+
def main():
|
| 1598 |
+
parser = argparse.ArgumentParser(
|
| 1599 |
+
description="Cell segmentation, BFS layer index, and feature extraction"
|
| 1600 |
+
)
|
| 1601 |
+
# Single-TIF mode
|
| 1602 |
+
parser.add_argument("--single", default=None,
|
| 1603 |
+
help="Single TIF path (quick layer-index check, no BMP needed)")
|
| 1604 |
+
# Full pipeline mode
|
| 1605 |
+
parser.add_argument("--metadata", default=None, help="Path to metadata CSV")
|
| 1606 |
+
parser.add_argument("--tif-dir", default=None, help="Directory with TIF files")
|
| 1607 |
+
parser.add_argument("--bmp-dir", default=None, help="Directory with BMP files")
|
| 1608 |
+
parser.add_argument("--species", default=None, help="Filter by species")
|
| 1609 |
+
parser.add_argument("--stage", default=None, help="Filter by stage")
|
| 1610 |
+
# Common options
|
| 1611 |
+
parser.add_argument("--gpu", action="store_true", help="Use GPU for Cellpose")
|
| 1612 |
+
parser.add_argument("--diameter", type=float, default=None,
|
| 1613 |
+
help="Cell diameter in pixels (auto if not set)")
|
| 1614 |
+
parser.add_argument("--out-dir", default="feature_outputs", help="Output directory")
|
| 1615 |
+
parser.add_argument("--cnn-weights", default=None,
|
| 1616 |
+
help="Path to fine-tuned DINOv2 backbone .pt "
|
| 1617 |
+
"(produced by finetune_dinov2.py). If omitted, "
|
| 1618 |
+
"uses pretrained DINOv2 ViT-S/14.")
|
| 1619 |
+
args = parser.parse_args()
|
| 1620 |
+
|
| 1621 |
+
# ββ Single-TIF mode ββ
|
| 1622 |
+
if args.single:
|
| 1623 |
+
process_single_tif(args.single, gpu=args.gpu, out_dir=args.out_dir,
|
| 1624 |
+
diameter=args.diameter)
|
| 1625 |
+
return
|
| 1626 |
+
|
| 1627 |
+
# ββ Full pipeline mode ββ
|
| 1628 |
+
if not args.metadata:
|
| 1629 |
+
parser.error("Provide --single for quick check, or --metadata for full pipeline")
|
| 1630 |
+
|
| 1631 |
+
out_dir = Path(args.out_dir)
|
| 1632 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 1633 |
+
|
| 1634 |
+
print("=" * 65)
|
| 1635 |
+
print("CELL FEATURE EXTRACTION PIPELINE")
|
| 1636 |
+
print("=" * 65)
|
| 1637 |
+
|
| 1638 |
+
print("\n[1] Loading metadata...")
|
| 1639 |
+
df_meta = parse_metadata(args.metadata, args.tif_dir, args.bmp_dir)
|
| 1640 |
+
pairs = get_pairs(df_meta, species=args.species, stage=args.stage)
|
| 1641 |
+
print(f" {len(pairs)} pairs to process")
|
| 1642 |
+
|
| 1643 |
+
groups = {}
|
| 1644 |
+
for p in pairs:
|
| 1645 |
+
key = (p["species"], p["stage"])
|
| 1646 |
+
groups.setdefault(key, []).append(p)
|
| 1647 |
+
|
| 1648 |
+
all_tables = []
|
| 1649 |
+
|
| 1650 |
+
for (species, stage), group_pairs in groups.items():
|
| 1651 |
+
print(f"\n{'='*65}")
|
| 1652 |
+
print(f" Species: {species}, Stage: {stage} ({len(group_pairs)} pairs)")
|
| 1653 |
+
print(f"{'='*65}")
|
| 1654 |
+
|
| 1655 |
+
group_tables = []
|
| 1656 |
+
|
| 1657 |
+
for idx, pair in enumerate(tqdm(group_pairs, desc=f"{species}/{stage}")):
|
| 1658 |
+
tif_path = pair["tif_path"]
|
| 1659 |
+
bmp_path = pair["bmp_path"]
|
| 1660 |
+
um_per_px = pair["um_per_px"] or 1.0
|
| 1661 |
+
tif_w = pair["tif_w"]
|
| 1662 |
+
tif_h = pair["tif_h"]
|
| 1663 |
+
|
| 1664 |
+
if not Path(tif_path).exists():
|
| 1665 |
+
print(f" SKIP TIF not found: {tif_path}")
|
| 1666 |
+
continue
|
| 1667 |
+
if not Path(bmp_path).exists():
|
| 1668 |
+
print(f" SKIP BMP not found: {bmp_path}")
|
| 1669 |
+
continue
|
| 1670 |
+
|
| 1671 |
+
print(f"\n [{idx+1}/{len(group_pairs)}] {Path(tif_path).name}")
|
| 1672 |
+
print(f" TIF size: {tif_w}x{tif_h}, "
|
| 1673 |
+
f"BMP size: {pair['bmp_w']}x{pair['bmp_h']}, "
|
| 1674 |
+
f"scale: {um_per_px} um/px")
|
| 1675 |
+
|
| 1676 |
+
try:
|
| 1677 |
+
table = process_pair(
|
| 1678 |
+
tif_path=tif_path, bmp_path=bmp_path,
|
| 1679 |
+
tif_h=tif_h, tif_w=tif_w, um_per_px=um_per_px,
|
| 1680 |
+
species=species, stage=stage,
|
| 1681 |
+
source_file=Path(tif_path).name,
|
| 1682 |
+
gpu=args.gpu, out_dir=out_dir,
|
| 1683 |
+
cnn_weights=args.cnn_weights,
|
| 1684 |
+
)
|
| 1685 |
+
if table is not None and len(table) > 0:
|
| 1686 |
+
group_tables.append(table)
|
| 1687 |
+
except Exception as e:
|
| 1688 |
+
print(f" FAILED: {e}")
|
| 1689 |
+
import traceback
|
| 1690 |
+
traceback.print_exc()
|
| 1691 |
+
continue
|
| 1692 |
+
|
| 1693 |
+
if group_tables:
|
| 1694 |
+
group_df = pd.concat(group_tables, ignore_index=True)
|
| 1695 |
+
group_path = out_dir / f"features_{species}_{stage}.csv"
|
| 1696 |
+
cols = [c for c in group_df.columns if c != "cell_type"] + ["cell_type"]
|
| 1697 |
+
group_df = group_df[cols]
|
| 1698 |
+
group_df.to_csv(group_path, index=False)
|
| 1699 |
+
print(f"\n Saved {len(group_df)} cells to {group_path}")
|
| 1700 |
+
all_tables.append(group_df)
|
| 1701 |
+
|
| 1702 |
+
if all_tables:
|
| 1703 |
+
combined = pd.concat(all_tables, ignore_index=True)
|
| 1704 |
+
combined_path = out_dir / "all_cell_features.csv"
|
| 1705 |
+
cols = [c for c in combined.columns if c != "cell_type"] + ["cell_type"]
|
| 1706 |
+
combined = combined[cols]
|
| 1707 |
+
combined.to_csv(combined_path, index=False)
|
| 1708 |
+
|
| 1709 |
+
print(f"\n{'='*65}")
|
| 1710 |
+
print(f"DONE. Total: {len(combined)} cells from {len(all_tables)} groups")
|
| 1711 |
+
print(f"Saved to: {combined_path}")
|
| 1712 |
+
print(f"\nClass distribution:")
|
| 1713 |
+
for ct, cnt in combined["cell_type"].value_counts().items():
|
| 1714 |
+
print(f" {ct}: {cnt}")
|
| 1715 |
+
untyped = combined["cell_type"].isna().sum()
|
| 1716 |
+
if untyped > 0:
|
| 1717 |
+
print(f" unclassified: {untyped}")
|
| 1718 |
+
print(f"{'='*65}")
|
| 1719 |
+
else:
|
| 1720 |
+
print("\nNo features extracted. Check file paths and metadata.")
|
| 1721 |
+
|
| 1722 |
+
|
| 1723 |
+
if __name__ == "__main__":
|
| 1724 |
+
main()
|
rootscope/overlay.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Overlay BMP cell-type color labels onto TIF images for visual verification.
|
| 3 |
+
|
| 4 |
+
For each TIF/BMP pair in the metadata, produces a PNG showing:
|
| 5 |
+
- Top: TIF image with cell-type color overlay + legend
|
| 6 |
+
- Bottom (or side): original BMP for comparison
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python overlay_labels_on_tif.py \
|
| 10 |
+
--metadata metadata_with_tif_sizes3.csv \
|
| 11 |
+
--tif-dir ./tif --bmp-dir ./bmp \
|
| 12 |
+
--out-dir label_overlays
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import re
|
| 17 |
+
import numpy as np
|
| 18 |
+
import cv2
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 21 |
+
from skimage.io import imread
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ββ Cell type config (must match extract_features.py) ββ
|
| 25 |
+
CELL_CLASSES = {
|
| 26 |
+
"root_cap": 0,
|
| 27 |
+
"epidermis": 1,
|
| 28 |
+
"exodermis": 2,
|
| 29 |
+
"cortex": 3,
|
| 30 |
+
"endodermis": 4,
|
| 31 |
+
"pericycle": 5,
|
| 32 |
+
"xylem": 6,
|
| 33 |
+
"phloem": 7,
|
| 34 |
+
"stele": 8,
|
| 35 |
+
}
|
| 36 |
+
LABEL_TO_NAME = {v: k for k, v in CELL_CLASSES.items()}
|
| 37 |
+
|
| 38 |
+
# HSV ranges (OpenCV scale: H 0-180, S 0-255, V 0-255)
|
| 39 |
+
COLOR_RANGES = {
|
| 40 |
+
"phloem": [(0, 180, 0, 30, 210, 255)],
|
| 41 |
+
"cortex": [(35, 85, 50, 255, 40, 255)],
|
| 42 |
+
"epidermis": [(100, 130, 50, 255, 80, 255)],
|
| 43 |
+
"stele": [(80, 100, 50, 255, 100, 255)],
|
| 44 |
+
"exodermis": [(22, 38, 60, 255, 100, 255)],
|
| 45 |
+
"endodermis": [(10, 22, 100, 255, 100, 255)],
|
| 46 |
+
"pericycle": [(125, 150, 30, 255, 40, 200)],
|
| 47 |
+
"root_cap": [(150, 175, 40, 255, 80, 255)],
|
| 48 |
+
"xylem": [(0, 8, 150, 255, 120, 255),
|
| 49 |
+
(175, 180, 150, 255, 120, 255)],
|
| 50 |
+
}
|
| 51 |
+
COLOR_PROCESS_ORDER = [
|
| 52 |
+
"phloem", "cortex", "epidermis", "stele", "exodermis",
|
| 53 |
+
"endodermis", "pericycle", "root_cap", "xylem",
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
# Display palette (RGB) for overlay
|
| 57 |
+
DISPLAY_PALETTE = {
|
| 58 |
+
0: (255, 105, 180), # root_cap - pink
|
| 59 |
+
1: (0, 0, 255), # epidermis - blue
|
| 60 |
+
2: (255, 255, 0), # exodermis - yellow
|
| 61 |
+
3: (0, 200, 0), # cortex - green
|
| 62 |
+
4: (255, 165, 0), # endodermis - orange
|
| 63 |
+
5: (128, 0, 128), # pericycle - purple
|
| 64 |
+
6: (255, 0, 0), # xylem - red
|
| 65 |
+
7: (255, 255, 255), # phloem - white
|
| 66 |
+
8: (0, 255, 255), # stele - cyan
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _load_font(size):
|
| 71 |
+
for path in [
|
| 72 |
+
"/usr/share/fonts/liberation/LiberationMono-Regular.ttf",
|
| 73 |
+
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
| 74 |
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
| 75 |
+
]:
|
| 76 |
+
try:
|
| 77 |
+
return ImageFont.truetype(path, size)
|
| 78 |
+
except (OSError, IOError):
|
| 79 |
+
pass
|
| 80 |
+
return ImageFont.load_default()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _normalize_to_uint8(img):
|
| 84 |
+
if img.dtype == np.uint8:
|
| 85 |
+
return img
|
| 86 |
+
img_f = img.astype(np.float32)
|
| 87 |
+
lo, hi = float(np.percentile(img_f, 1)), float(np.percentile(img_f, 99))
|
| 88 |
+
img_f = (img_f - lo) / (hi - lo + 1e-8)
|
| 89 |
+
return (np.clip(img_f, 0.0, 1.0) * 255.0).astype(np.uint8)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def to_2d(img):
|
| 93 |
+
if img.ndim == 2:
|
| 94 |
+
return img
|
| 95 |
+
if img.ndim == 3:
|
| 96 |
+
if img.shape[-1] in (3, 4):
|
| 97 |
+
return img
|
| 98 |
+
return img.max(axis=0)
|
| 99 |
+
if img.ndim == 4:
|
| 100 |
+
return img.max(axis=0)
|
| 101 |
+
raise ValueError(f"Unsupported ndim={img.ndim}")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def ensure_rgb_uint8(img):
|
| 105 |
+
img2 = to_2d(img)
|
| 106 |
+
if img2.ndim == 2:
|
| 107 |
+
g = _normalize_to_uint8(img2)
|
| 108 |
+
return np.stack([g, g, g], axis=-1)
|
| 109 |
+
if img2.ndim == 3:
|
| 110 |
+
if img2.shape[-1] == 1:
|
| 111 |
+
g = _normalize_to_uint8(img2[..., 0])
|
| 112 |
+
return np.stack([g, g, g], axis=-1)
|
| 113 |
+
return _normalize_to_uint8(img2[..., :3])
|
| 114 |
+
raise ValueError(f"Unsupported shape: {img2.shape}")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def create_class_mask_from_bmp(bmp_path):
|
| 118 |
+
bmp_rgb = np.array(Image.open(str(bmp_path)).convert("RGB"))
|
| 119 |
+
bmp_hsv = cv2.cvtColor(bmp_rgb, cv2.COLOR_RGB2HSV)
|
| 120 |
+
h, w = bmp_hsv.shape[:2]
|
| 121 |
+
class_mask = np.full((h, w), -1, dtype=np.int8)
|
| 122 |
+
confidence = np.zeros((h, w), dtype=np.float32)
|
| 123 |
+
sat = bmp_hsv[:, :, 1].astype(np.float32) / 255.0
|
| 124 |
+
val = bmp_hsv[:, :, 2].astype(np.float32) / 255.0
|
| 125 |
+
|
| 126 |
+
for class_name in COLOR_PROCESS_ORDER:
|
| 127 |
+
ranges = COLOR_RANGES[class_name]
|
| 128 |
+
label = CELL_CLASSES[class_name]
|
| 129 |
+
combined = np.zeros((h, w), dtype=bool)
|
| 130 |
+
for (h_lo, h_hi, s_lo, s_hi, v_lo, v_hi) in ranges:
|
| 131 |
+
lower = np.array([h_lo, s_lo, v_lo])
|
| 132 |
+
upper = np.array([h_hi, s_hi, v_hi])
|
| 133 |
+
combined |= cv2.inRange(bmp_hsv, lower, upper) > 0
|
| 134 |
+
conf = val * (1.0 - sat) if class_name == "phloem" else sat * val
|
| 135 |
+
update = combined & (conf >= confidence)
|
| 136 |
+
class_mask[update] = label
|
| 137 |
+
confidence[update] = conf[update]
|
| 138 |
+
|
| 139 |
+
return class_mask
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def colorize_class_mask(class_mask):
|
| 143 |
+
"""Convert class mask to RGB image using display palette."""
|
| 144 |
+
h, w = class_mask.shape
|
| 145 |
+
rgb = np.zeros((h, w, 3), dtype=np.uint8)
|
| 146 |
+
for label, color in DISPLAY_PALETTE.items():
|
| 147 |
+
rgb[class_mask == label] = color
|
| 148 |
+
return rgb
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def overlay_on_tif(tif_rgb, class_mask_colored, alpha=0.45):
|
| 152 |
+
"""Blend class mask colors onto TIF image where mask is not background."""
|
| 153 |
+
has_label = class_mask_colored.sum(axis=-1) > 0
|
| 154 |
+
out = tif_rgb.astype(np.float32).copy()
|
| 155 |
+
mask_f = has_label[..., None].astype(np.float32)
|
| 156 |
+
out = out * (1.0 - alpha * mask_f) + class_mask_colored.astype(np.float32) * (alpha * mask_f)
|
| 157 |
+
return np.clip(out, 0, 255).astype(np.uint8)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def draw_legend(draw, x, y, font):
|
| 161 |
+
"""Draw cell-type color legend."""
|
| 162 |
+
for label in sorted(DISPLAY_PALETTE.keys()):
|
| 163 |
+
name = LABEL_TO_NAME[label]
|
| 164 |
+
color = DISPLAY_PALETTE[label]
|
| 165 |
+
draw.rectangle([x, y, x + 14, y + 14], fill=color, outline=(0, 0, 0))
|
| 166 |
+
draw.text((x + 20, y), name, fill=(255, 255, 255), font=font)
|
| 167 |
+
draw.text((x + 19, y - 1), name, fill=(0, 0, 0), font=font)
|
| 168 |
+
draw.text((x + 20, y), name, fill=(255, 255, 255), font=font)
|
| 169 |
+
y += 18
|
| 170 |
+
return y
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def make_overlay_png(tif_path, bmp_path, out_path, tif_h=None, tif_w=None):
|
| 174 |
+
"""
|
| 175 |
+
Create a verification PNG:
|
| 176 |
+
Top half: TIF with BMP labels overlaid (semi-transparent colors + legend)
|
| 177 |
+
Bottom half: original BMP image for reference
|
| 178 |
+
"""
|
| 179 |
+
# Load TIF
|
| 180 |
+
img_raw = imread(str(tif_path))
|
| 181 |
+
tif_rgb = ensure_rgb_uint8(img_raw)
|
| 182 |
+
th, tw = tif_rgb.shape[:2]
|
| 183 |
+
|
| 184 |
+
# Load BMP and create class mask
|
| 185 |
+
class_mask = create_class_mask_from_bmp(bmp_path)
|
| 186 |
+
bmp_rgb = np.array(Image.open(str(bmp_path)).convert("RGB"))
|
| 187 |
+
bh, bw = bmp_rgb.shape[:2]
|
| 188 |
+
|
| 189 |
+
# Resize class mask to TIF dimensions
|
| 190 |
+
class_mask_resized = cv2.resize(
|
| 191 |
+
class_mask.astype(np.float32), (tw, th),
|
| 192 |
+
interpolation=cv2.INTER_NEAREST
|
| 193 |
+
).astype(np.int8)
|
| 194 |
+
|
| 195 |
+
# Colorize and overlay on TIF
|
| 196 |
+
class_colored = colorize_class_mask(class_mask_resized)
|
| 197 |
+
tif_overlaid = overlay_on_tif(tif_rgb, class_colored, alpha=0.5)
|
| 198 |
+
|
| 199 |
+
# Resize BMP to same width as TIF for stacking
|
| 200 |
+
scale = tw / bw
|
| 201 |
+
new_bh = int(bh * scale)
|
| 202 |
+
bmp_resized = cv2.resize(bmp_rgb, (tw, new_bh), interpolation=cv2.INTER_LINEAR)
|
| 203 |
+
|
| 204 |
+
# Add title bars
|
| 205 |
+
title_h = 30
|
| 206 |
+
font = _load_font(16)
|
| 207 |
+
small_font = _load_font(12)
|
| 208 |
+
|
| 209 |
+
# Total canvas: title + TIF overlay + gap + title + BMP
|
| 210 |
+
gap = 4
|
| 211 |
+
total_h = title_h + th + gap + title_h + new_bh
|
| 212 |
+
canvas = np.zeros((total_h, tw, 3), dtype=np.uint8)
|
| 213 |
+
|
| 214 |
+
# Place TIF overlay
|
| 215 |
+
y_offset = title_h
|
| 216 |
+
canvas[y_offset:y_offset + th, :, :] = tif_overlaid
|
| 217 |
+
|
| 218 |
+
# Place BMP
|
| 219 |
+
y_bmp = title_h + th + gap + title_h
|
| 220 |
+
canvas[y_bmp:y_bmp + new_bh, :, :] = bmp_resized
|
| 221 |
+
|
| 222 |
+
# Draw on PIL
|
| 223 |
+
im = Image.fromarray(canvas)
|
| 224 |
+
draw = ImageDraw.Draw(im)
|
| 225 |
+
|
| 226 |
+
# Title: TIF + label overlay
|
| 227 |
+
tif_name = Path(tif_path).name
|
| 228 |
+
bmp_name = Path(bmp_path).name
|
| 229 |
+
draw.rectangle([0, 0, tw, title_h], fill=(30, 30, 30))
|
| 230 |
+
draw.text((10, 6), f"TIF + BMP labels: {tif_name}", fill=(255, 255, 255), font=font)
|
| 231 |
+
|
| 232 |
+
# Title: BMP reference
|
| 233 |
+
y_title2 = title_h + th + gap
|
| 234 |
+
draw.rectangle([0, y_title2, tw, y_title2 + title_h], fill=(30, 30, 30))
|
| 235 |
+
draw.text((10, y_title2 + 6), f"BMP reference: {bmp_name}", fill=(255, 255, 255), font=font)
|
| 236 |
+
|
| 237 |
+
# Legend on TIF overlay (top-right)
|
| 238 |
+
legend_x = tw - 130
|
| 239 |
+
legend_y = title_h + 10
|
| 240 |
+
# Background box for legend
|
| 241 |
+
n_classes = len(DISPLAY_PALETTE)
|
| 242 |
+
legend_h = n_classes * 18 + 6
|
| 243 |
+
draw.rectangle([legend_x - 4, legend_y - 4, tw - 4, legend_y + legend_h],
|
| 244 |
+
fill=(0, 0, 0, 180))
|
| 245 |
+
draw_legend(draw, legend_x, legend_y, small_font)
|
| 246 |
+
|
| 247 |
+
im.save(str(out_path))
|
| 248 |
+
return out_path
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _parse_size(s):
|
| 252 |
+
m = re.match(r"(\d+)\s*x\s*(\d+)", str(s).strip())
|
| 253 |
+
return (int(m.group(1)), int(m.group(2))) if m else (None, None)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def main():
|
| 257 |
+
parser = argparse.ArgumentParser(
|
| 258 |
+
description="Overlay BMP cell-type labels on TIF images for verification"
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument("--metadata", required=True, help="Path to metadata CSV")
|
| 261 |
+
parser.add_argument("--tif-dir", required=True, help="Directory with TIF files")
|
| 262 |
+
parser.add_argument("--bmp-dir", required=True, help="Directory with BMP files")
|
| 263 |
+
parser.add_argument("--out-dir", default="label_overlays", help="Output directory")
|
| 264 |
+
parser.add_argument("--species", default=None, help="Filter by species")
|
| 265 |
+
parser.add_argument("--stage", default=None, help="Filter by stage")
|
| 266 |
+
parser.add_argument("--gpu", action="store_true", help="Accepted for consistency (not used)")
|
| 267 |
+
args = parser.parse_args()
|
| 268 |
+
|
| 269 |
+
import pandas as pd
|
| 270 |
+
|
| 271 |
+
out_dir = Path(args.out_dir)
|
| 272 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 273 |
+
tif_dir = Path(args.tif_dir)
|
| 274 |
+
bmp_dir = Path(args.bmp_dir)
|
| 275 |
+
|
| 276 |
+
df = pd.read_csv(args.metadata)
|
| 277 |
+
df.columns = df.columns.str.strip().str.lower()
|
| 278 |
+
|
| 279 |
+
if args.species:
|
| 280 |
+
df = df[df["species"].str.lower() == args.species.lower()]
|
| 281 |
+
if args.stage:
|
| 282 |
+
df = df[df["stage"].str.lower() == args.stage.lower()]
|
| 283 |
+
|
| 284 |
+
# Only keep rows with "outlined" in BMP filename (the labeled ones)
|
| 285 |
+
df_outlined = df[df["bmp_filename"].str.lower().str.contains("outlined")]
|
| 286 |
+
if len(df_outlined) == 0:
|
| 287 |
+
print("No 'Outlined' BMPs found, using all rows.")
|
| 288 |
+
df_outlined = df
|
| 289 |
+
|
| 290 |
+
print(f"Processing {len(df_outlined)} TIF/BMP pairs...")
|
| 291 |
+
|
| 292 |
+
for idx, row in df_outlined.iterrows():
|
| 293 |
+
tif_path = tif_dir / row["tif_matched"]
|
| 294 |
+
bmp_path = bmp_dir / row["bmp_filename"]
|
| 295 |
+
|
| 296 |
+
if not tif_path.exists():
|
| 297 |
+
print(f" SKIP TIF not found: {tif_path}")
|
| 298 |
+
continue
|
| 299 |
+
if not bmp_path.exists():
|
| 300 |
+
print(f" SKIP BMP not found: {bmp_path}")
|
| 301 |
+
continue
|
| 302 |
+
|
| 303 |
+
species = row["species"]
|
| 304 |
+
stage = row["stage"]
|
| 305 |
+
stem = tif_path.stem.replace(".aivia", "")
|
| 306 |
+
out_name = f"verify_{species}_{stage}_{stem}.png"
|
| 307 |
+
out_path = out_dir / out_name
|
| 308 |
+
|
| 309 |
+
print(f" [{idx+1}] {tif_path.name} + {bmp_path.name}")
|
| 310 |
+
try:
|
| 311 |
+
make_overlay_png(tif_path, bmp_path, out_path)
|
| 312 |
+
print(f" -> {out_path}")
|
| 313 |
+
except Exception as e:
|
| 314 |
+
print(f" FAILED: {e}")
|
| 315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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Predict cell types on new TIF images using ITERATIVE refinement.
|
| 3 |
+
|
| 4 |
+
Same as predict_cell_types.py but instead of a fixed 2-pass approach,
|
| 5 |
+
iterates predictions until neighbor-celltype features stabilize:
|
| 6 |
+
|
| 7 |
+
Round 1: predict with neighbor celltypes = -1 (unknown)
|
| 8 |
+
Round 2: fill neighbor celltypes from round 1, re-predict
|
| 9 |
+
Round 3: fill neighbor celltypes from round 2, re-predict
|
| 10 |
+
...
|
| 11 |
+
Stop when predictions no longer change OR max_rounds reached.
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python predict_cell_types_iterative.py \
|
| 15 |
+
--tif path/to/new_image.tif \
|
| 16 |
+
--model-dir trained_model \
|
| 17 |
+
--um-per-px 1.0 --gpu \
|
| 18 |
+
--max-rounds 10
|
| 19 |
+
|
| 20 |
+
Output (per TIF, per model):
|
| 21 |
+
predictions/
|
| 22 |
+
{stem}_RandomForest_predictions.csv
|
| 23 |
+
{stem}_RandomForest_overlay.png
|
| 24 |
+
{stem}_XGBoost_predictions.csv
|
| 25 |
+
{stem}_XGBoost_overlay.png
|
| 26 |
+
{stem}_LightGBM_predictions.csv
|
| 27 |
+
{stem}_LightGBM_overlay.png
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
import argparse
|
| 31 |
+
import numpy as np
|
| 32 |
+
import pandas as pd
|
| 33 |
+
import joblib
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 36 |
+
from scipy import ndimage
|
| 37 |
+
from skimage.io import imread
|
| 38 |
+
from skimage.measure import regionprops
|
| 39 |
+
from skimage.morphology import binary_closing, binary_opening, remove_small_objects, disk
|
| 40 |
+
from skimage.segmentation import find_boundaries
|
| 41 |
+
from scipy.ndimage import binary_fill_holes, label as ndlabel
|
| 42 |
+
from collections import deque, defaultdict
|
| 43 |
+
|
| 44 |
+
from .extract_features import (
|
| 45 |
+
ensure_rgb_uint8,
|
| 46 |
+
to_grayscale_float,
|
| 47 |
+
segment_cellpose_sam,
|
| 48 |
+
build_tissue_mask,
|
| 49 |
+
compute_layer_index_edt,
|
| 50 |
+
build_cell_adjacency,
|
| 51 |
+
extract_all_features,
|
| 52 |
+
count_vascular_poles,
|
| 53 |
+
compute_pole_features,
|
| 54 |
+
compute_neighbor_celltypes,
|
| 55 |
+
extract_cnn_embedding_features,
|
| 56 |
+
CELL_CLASSES,
|
| 57 |
+
LABEL_TO_NAME,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Display palette (RGB)
|
| 62 |
+
DISPLAY_PALETTE = {
|
| 63 |
+
0: (255, 105, 180), # root_cap - pink
|
| 64 |
+
1: (0, 0, 255), # epidermis - blue
|
| 65 |
+
2: (255, 255, 0), # exodermis - yellow
|
| 66 |
+
3: (0, 200, 0), # cortex - green
|
| 67 |
+
4: (255, 165, 0), # endodermis - orange
|
| 68 |
+
5: (128, 0, 128), # pericycle - purple
|
| 69 |
+
6: (255, 0, 0), # xylem - red
|
| 70 |
+
7: (255, 255, 255), # phloem - white
|
| 71 |
+
8: (0, 255, 255), # stele - cyan
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _load_font(size):
|
| 76 |
+
for path in [
|
| 77 |
+
"/usr/share/fonts/liberation/LiberationMono-Regular.ttf",
|
| 78 |
+
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
| 79 |
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
| 80 |
+
]:
|
| 81 |
+
try:
|
| 82 |
+
return ImageFont.truetype(path, size)
|
| 83 |
+
except (OSError, IOError):
|
| 84 |
+
pass
|
| 85 |
+
return ImageFont.load_default()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
MODEL_NAMES = ["RandomForest", "XGBoost", "LightGBM"]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def load_models(model_dir):
|
| 92 |
+
"""Load all three models + scalers + encoder.
|
| 93 |
+
|
| 94 |
+
Supports two layouts:
|
| 95 |
+
- Per-model scalers: feature_scaler_RandomForest.joblib, etc. (iterative training)
|
| 96 |
+
- Shared scaler: feature_scaler.joblib (old training)
|
| 97 |
+
"""
|
| 98 |
+
model_dir = Path(model_dir)
|
| 99 |
+
feature_cols = joblib.load(model_dir / "feature_columns.joblib")
|
| 100 |
+
le = joblib.load(model_dir / "label_encoder.joblib")
|
| 101 |
+
|
| 102 |
+
# Check for shared scaler (old layout)
|
| 103 |
+
shared_scaler_path = model_dir / "feature_scaler.joblib"
|
| 104 |
+
shared_scaler = None
|
| 105 |
+
if shared_scaler_path.exists():
|
| 106 |
+
shared_scaler = joblib.load(shared_scaler_path)
|
| 107 |
+
|
| 108 |
+
models = {}
|
| 109 |
+
scalers = {}
|
| 110 |
+
for name in MODEL_NAMES:
|
| 111 |
+
model_path = model_dir / f"model_{name}.joblib"
|
| 112 |
+
if not model_path.exists():
|
| 113 |
+
print(f" WARNING: {model_path} not found, skipping {name}")
|
| 114 |
+
continue
|
| 115 |
+
models[name] = joblib.load(model_path)
|
| 116 |
+
|
| 117 |
+
# Per-model scaler (iterative training) or shared scaler
|
| 118 |
+
per_model_scaler_path = model_dir / f"feature_scaler_{name}.joblib"
|
| 119 |
+
if per_model_scaler_path.exists():
|
| 120 |
+
scalers[name] = joblib.load(per_model_scaler_path)
|
| 121 |
+
elif shared_scaler is not None:
|
| 122 |
+
scalers[name] = shared_scaler
|
| 123 |
+
else:
|
| 124 |
+
raise FileNotFoundError(
|
| 125 |
+
f"No scaler found for {name} in {model_dir}")
|
| 126 |
+
print(f" Loaded {name} from {model_path}")
|
| 127 |
+
|
| 128 |
+
print(f" Classes: {list(le.classes_)}")
|
| 129 |
+
print(f" Features: {len(feature_cols)}")
|
| 130 |
+
print(f" Models loaded: {list(models.keys())}")
|
| 131 |
+
return models, scalers, feature_cols, le
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def save_prediction_overlay(img_rgb, masks, cell_predictions, out_path,
|
| 135 |
+
le, alpha=0.5, label_cells=False):
|
| 136 |
+
"""
|
| 137 |
+
Overlay predicted cell-type colors on TIF, with a legend.
|
| 138 |
+
|
| 139 |
+
label_cells=True also prints an abbreviated cell-type name inside every
|
| 140 |
+
cell. Off by default: on a dense cross-section the per-cell text overlaps
|
| 141 |
+
and hides the image. The color + legend already carry the same information.
|
| 142 |
+
"""
|
| 143 |
+
H, W = masks.shape
|
| 144 |
+
gray = to_grayscale_float(img_rgb)
|
| 145 |
+
base = np.stack([gray, gray, gray], axis=-1)
|
| 146 |
+
|
| 147 |
+
# Build color overlay from predictions
|
| 148 |
+
color_rgb = np.zeros((H, W, 3), dtype=np.uint8)
|
| 149 |
+
for cid, pred_name in cell_predictions.items():
|
| 150 |
+
label_int = CELL_CLASSES.get(pred_name, -1)
|
| 151 |
+
if label_int >= 0 and label_int in DISPLAY_PALETTE:
|
| 152 |
+
color_rgb[masks == cid] = DISPLAY_PALETTE[label_int]
|
| 153 |
+
|
| 154 |
+
has_color = color_rgb.sum(axis=-1) > 0
|
| 155 |
+
mask_f = has_color[..., None].astype(np.float32)
|
| 156 |
+
blended = base * (1.0 - alpha * mask_f) + color_rgb.astype(np.float32) * (alpha * mask_f)
|
| 157 |
+
|
| 158 |
+
# Cell boundaries
|
| 159 |
+
boundaries = find_boundaries(masks, mode="outer")
|
| 160 |
+
blended[boundaries] = [255, 255, 255]
|
| 161 |
+
|
| 162 |
+
im = Image.fromarray(np.clip(blended, 0, 255).astype(np.uint8))
|
| 163 |
+
draw = ImageDraw.Draw(im)
|
| 164 |
+
|
| 165 |
+
# Optional: draw the cell-type name inside each cell (--label-cells)
|
| 166 |
+
if label_cells:
|
| 167 |
+
props = {p.label: p for p in regionprops(masks)}
|
| 168 |
+
med_area = float(np.median([p.area for p in props.values()])) if props else 100.0
|
| 169 |
+
base_fs = max(7, min(14, int(np.sqrt(med_area) * 0.25)))
|
| 170 |
+
font = _load_font(base_fs)
|
| 171 |
+
|
| 172 |
+
for cid, pred_name in cell_predictions.items():
|
| 173 |
+
if cid not in props:
|
| 174 |
+
continue
|
| 175 |
+
cy, cx = props[cid].centroid
|
| 176 |
+
x, y = int(round(cx)), int(round(cy))
|
| 177 |
+
# Abbreviate: first 4 chars
|
| 178 |
+
abbr = pred_name[:4]
|
| 179 |
+
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
| 180 |
+
draw.text((x + dx, y + dy), abbr, fill=(0, 0, 0), font=font, anchor="mm")
|
| 181 |
+
draw.text((x, y), abbr, fill=(255, 255, 255), font=font, anchor="mm")
|
| 182 |
+
|
| 183 |
+
# Legend
|
| 184 |
+
legend_font = _load_font(13)
|
| 185 |
+
legend_x = W - 140
|
| 186 |
+
legend_y = 10
|
| 187 |
+
present_types = sorted(set(cell_predictions.values()))
|
| 188 |
+
n_legend = len(present_types)
|
| 189 |
+
draw.rectangle(
|
| 190 |
+
[legend_x - 4, legend_y - 4, W - 4, legend_y + n_legend * 20 + 4],
|
| 191 |
+
fill=(0, 0, 0),
|
| 192 |
+
)
|
| 193 |
+
for i, name in enumerate(present_types):
|
| 194 |
+
label_int = CELL_CLASSES.get(name, -1)
|
| 195 |
+
color = DISPLAY_PALETTE.get(label_int, (128, 128, 128))
|
| 196 |
+
ly = legend_y + i * 20
|
| 197 |
+
draw.rectangle([legend_x, ly, legend_x + 14, ly + 14], fill=color,
|
| 198 |
+
outline=(255, 255, 255))
|
| 199 |
+
draw.text((legend_x + 20, ly), name, fill=(255, 255, 255), font=legend_font)
|
| 200 |
+
|
| 201 |
+
im.save(str(out_path))
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def anatomical_postprocess(df, layer_lookup, adjacency, masks, le=None, y_proba=None,
|
| 205 |
+
rf_proba_lookup=None):
|
| 206 |
+
"""
|
| 207 |
+
Enforce known root anatomical ring order using the ADJACENCY GRAPH.
|
| 208 |
+
|
| 209 |
+
Root anatomy (outside -> inside):
|
| 210 |
+
root_cap -> epidermis -> exodermis -> cortex -> endodermis -> pericycle -> stele
|
| 211 |
+
|
| 212 |
+
Rules (layer + adjacency based):
|
| 213 |
+
- Exodermis = ONE layer only (epidermis_layer + 1)
|
| 214 |
+
- Endodermis = ONE layer only (the layer neighboring pericycle/stele)
|
| 215 |
+
- Pericycle = ONE layer only (just inside endodermis)
|
| 216 |
+
- Cortex fills the multiple layers between exodermis and endodermis
|
| 217 |
+
- Recover phloem and xylem from stele using probability scores
|
| 218 |
+
"""
|
| 219 |
+
predictions = dict(zip(df["cell_id"].values, df["predicted_cell_type"].values))
|
| 220 |
+
|
| 221 |
+
# Build probability lookup for phloem recovery
|
| 222 |
+
proba_lookup = {}
|
| 223 |
+
if y_proba is not None and le is not None:
|
| 224 |
+
class_names = list(le.classes_)
|
| 225 |
+
for i, cid in enumerate(df["cell_id"].values):
|
| 226 |
+
proba_lookup[int(cid)] = dict(zip(class_names, y_proba[i]))
|
| 227 |
+
|
| 228 |
+
# -- Step 1: Identify tissue groups from model predictions --
|
| 229 |
+
epidermis_cells = {cid for cid, pred in predictions.items()
|
| 230 |
+
if pred == "epidermis"}
|
| 231 |
+
root_cap_cells = {cid for cid, pred in predictions.items()
|
| 232 |
+
if pred == "root_cap"}
|
| 233 |
+
outer_cells = epidermis_cells | root_cap_cells
|
| 234 |
+
|
| 235 |
+
inner_types = ("pericycle", "stele", "xylem", "phloem")
|
| 236 |
+
inner_cells = {cid for cid, pred in predictions.items()
|
| 237 |
+
if pred in inner_types}
|
| 238 |
+
|
| 239 |
+
# -- Step 2: Find exodermis ring -- SINGLE LAYER only --
|
| 240 |
+
epi_layer_counts = defaultdict(int)
|
| 241 |
+
for cid in epidermis_cells:
|
| 242 |
+
lv = layer_lookup.get(cid, -1)
|
| 243 |
+
if lv >= 0:
|
| 244 |
+
epi_layer_counts[lv] += 1
|
| 245 |
+
main_epi_layer = max(epi_layer_counts, key=epi_layer_counts.get) if epi_layer_counts else 0
|
| 246 |
+
|
| 247 |
+
epi_neighbor_cells = set()
|
| 248 |
+
for epi_cid in epidermis_cells:
|
| 249 |
+
for nbr in adjacency.get(epi_cid, set()):
|
| 250 |
+
if nbr not in outer_cells and nbr not in inner_cells:
|
| 251 |
+
epi_neighbor_cells.add(nbr)
|
| 252 |
+
|
| 253 |
+
epi_nbr_layer_counts = defaultdict(int)
|
| 254 |
+
for cid in epi_neighbor_cells:
|
| 255 |
+
lv = layer_lookup.get(cid, -1)
|
| 256 |
+
if lv >= 0 and lv > main_epi_layer:
|
| 257 |
+
epi_nbr_layer_counts[lv] += 1
|
| 258 |
+
|
| 259 |
+
if epi_nbr_layer_counts:
|
| 260 |
+
exo_layer = max(epi_nbr_layer_counts, key=epi_nbr_layer_counts.get)
|
| 261 |
+
else:
|
| 262 |
+
exo_layer = main_epi_layer + 1
|
| 263 |
+
|
| 264 |
+
n_exo_promoted = 0
|
| 265 |
+
n_exo_demoted = 0
|
| 266 |
+
for cid, pred in list(predictions.items()):
|
| 267 |
+
lv = layer_lookup.get(cid, -1)
|
| 268 |
+
if lv == exo_layer and cid not in outer_cells and cid not in inner_cells:
|
| 269 |
+
if pred != "exodermis":
|
| 270 |
+
n_exo_promoted += 1
|
| 271 |
+
predictions[cid] = "exodermis"
|
| 272 |
+
elif pred == "exodermis":
|
| 273 |
+
predictions[cid] = "cortex"
|
| 274 |
+
n_exo_demoted += 1
|
| 275 |
+
|
| 276 |
+
n_final_exo = sum(1 for p in predictions.values() if p == "exodermis")
|
| 277 |
+
print(f" Post-processing: exodermis restricted to layer {exo_layer} "
|
| 278 |
+
f"(epi_layer={main_epi_layer}): {n_final_exo} exodermis cells, "
|
| 279 |
+
f"promoted {n_exo_promoted} into exo, demoted {n_exo_demoted} to cortex")
|
| 280 |
+
|
| 281 |
+
# -- Step 3: Find endodermis ring -- SINGLE LAYER only --
|
| 282 |
+
cells_neighboring_inner = set()
|
| 283 |
+
for inner_cid in inner_cells:
|
| 284 |
+
for nbr in adjacency.get(inner_cid, set()):
|
| 285 |
+
if nbr not in inner_cells and nbr not in outer_cells:
|
| 286 |
+
cells_neighboring_inner.add(nbr)
|
| 287 |
+
|
| 288 |
+
exo_cells_final = {cid for cid, pred in predictions.items()
|
| 289 |
+
if pred == "exodermis"}
|
| 290 |
+
endo_candidates = cells_neighboring_inner - exo_cells_final
|
| 291 |
+
|
| 292 |
+
endo_layer_counts = defaultdict(int)
|
| 293 |
+
for cid in endo_candidates:
|
| 294 |
+
lv = layer_lookup.get(cid, -1)
|
| 295 |
+
if lv >= 0:
|
| 296 |
+
endo_layer_counts[lv] += 1
|
| 297 |
+
endo_layer = max(endo_layer_counts, key=endo_layer_counts.get) if endo_layer_counts else -1
|
| 298 |
+
|
| 299 |
+
n_relabeled_endo = 0
|
| 300 |
+
for cid in endo_candidates:
|
| 301 |
+
lv = layer_lookup.get(cid, -1)
|
| 302 |
+
if lv == endo_layer:
|
| 303 |
+
if predictions.get(cid) != "endodermis":
|
| 304 |
+
n_relabeled_endo += 1
|
| 305 |
+
predictions[cid] = "endodermis"
|
| 306 |
+
|
| 307 |
+
n_fixed_endo = 0
|
| 308 |
+
for cid, pred in list(predictions.items()):
|
| 309 |
+
if pred == "endodermis":
|
| 310 |
+
lv = layer_lookup.get(cid, -1)
|
| 311 |
+
if lv != endo_layer:
|
| 312 |
+
predictions[cid] = "cortex"
|
| 313 |
+
n_fixed_endo += 1
|
| 314 |
+
|
| 315 |
+
n_final_endo = sum(1 for p in predictions.values() if p == "endodermis")
|
| 316 |
+
print(f" Post-processing: endodermis restricted to layer {endo_layer}: "
|
| 317 |
+
f"{n_final_endo} endodermis cells, relabeled {n_relabeled_endo} into endo, "
|
| 318 |
+
f"demoted {n_fixed_endo} to cortex")
|
| 319 |
+
|
| 320 |
+
# -- Step 4: Pericycle -- SINGLE RING only (adjacency-based) --
|
| 321 |
+
endo_cells_final = {cid for cid, pred in predictions.items()
|
| 322 |
+
if pred == "endodermis"}
|
| 323 |
+
|
| 324 |
+
peri_candidates = set()
|
| 325 |
+
for endo_cid in endo_cells_final:
|
| 326 |
+
endo_lv = layer_lookup.get(endo_cid, -1)
|
| 327 |
+
for nbr in adjacency.get(endo_cid, set()):
|
| 328 |
+
nbr_lv = layer_lookup.get(nbr, -1)
|
| 329 |
+
if nbr_lv > endo_lv and nbr not in endo_cells_final:
|
| 330 |
+
nbr_pred = predictions.get(nbr)
|
| 331 |
+
if nbr_pred not in ("epidermis", "root_cap", "exodermis", "cortex",
|
| 332 |
+
"endodermis"):
|
| 333 |
+
peri_candidates.add(nbr)
|
| 334 |
+
|
| 335 |
+
peri_layer_counts = defaultdict(int)
|
| 336 |
+
for cid in peri_candidates:
|
| 337 |
+
lv = layer_lookup.get(cid, -1)
|
| 338 |
+
if lv >= 0:
|
| 339 |
+
peri_layer_counts[lv] += 1
|
| 340 |
+
peri_layer = max(peri_layer_counts, key=peri_layer_counts.get) if peri_layer_counts else (endo_layer + 1 if endo_layer >= 0 else -1)
|
| 341 |
+
|
| 342 |
+
allowed_pericycle = set()
|
| 343 |
+
n_peri_promoted = 0
|
| 344 |
+
for cid in peri_candidates:
|
| 345 |
+
lv = layer_lookup.get(cid, -1)
|
| 346 |
+
if lv == peri_layer:
|
| 347 |
+
allowed_pericycle.add(cid)
|
| 348 |
+
if predictions.get(cid) != "pericycle":
|
| 349 |
+
n_peri_promoted += 1
|
| 350 |
+
predictions[cid] = "pericycle"
|
| 351 |
+
|
| 352 |
+
n_peri_demoted = 0
|
| 353 |
+
for cid, pred in list(predictions.items()):
|
| 354 |
+
if pred == "pericycle" and cid not in allowed_pericycle:
|
| 355 |
+
predictions[cid] = "stele"
|
| 356 |
+
n_peri_demoted += 1
|
| 357 |
+
|
| 358 |
+
n_final_peri = sum(1 for p in predictions.values() if p == "pericycle")
|
| 359 |
+
print(f" Post-processing: pericycle restricted to endodermis-adjacent cells "
|
| 360 |
+
f"in layer {peri_layer} (endo_layer={endo_layer}): {n_final_peri} pericycle "
|
| 361 |
+
f"cells, promoted {n_peri_promoted} into peri, demoted {n_peri_demoted} to stele")
|
| 362 |
+
|
| 363 |
+
# -- Step 5: Fix stray epidermis deep inside the root --
|
| 364 |
+
n_fixed_epi = 0
|
| 365 |
+
for cid, pred in list(predictions.items()):
|
| 366 |
+
if pred == "epidermis":
|
| 367 |
+
lv = layer_lookup.get(cid, -1)
|
| 368 |
+
if lv >= main_epi_layer + 3:
|
| 369 |
+
nbrs = adjacency.get(cid, set())
|
| 370 |
+
nbr_preds = [predictions.get(n) for n in nbrs
|
| 371 |
+
if n in predictions and predictions.get(n) != "epidermis"]
|
| 372 |
+
if nbr_preds:
|
| 373 |
+
from collections import Counter
|
| 374 |
+
predictions[cid] = Counter(nbr_preds).most_common(1)[0][0]
|
| 375 |
+
n_fixed_epi += 1
|
| 376 |
+
if n_fixed_epi > 0:
|
| 377 |
+
print(f" Post-processing: fixed {n_fixed_epi} stray epidermis cells")
|
| 378 |
+
|
| 379 |
+
# -- Step 6: Recover phloem and xylem from inner tissue using probabilities --
|
| 380 |
+
if proba_lookup:
|
| 381 |
+
def _effective_prob(cid, cls_name):
|
| 382 |
+
"""Return the best available probability for xylem/phloem."""
|
| 383 |
+
probs = proba_lookup.get(cid, {})
|
| 384 |
+
model_prob = probs.get(cls_name, 0.0)
|
| 385 |
+
if rf_proba_lookup and model_prob < 0.05:
|
| 386 |
+
rf_probs = rf_proba_lookup.get(cid, {})
|
| 387 |
+
rf_prob = rf_probs.get(cls_name, 0.0)
|
| 388 |
+
if rf_prob > model_prob:
|
| 389 |
+
return rf_prob
|
| 390 |
+
return model_prob
|
| 391 |
+
|
| 392 |
+
# Recover phloem from stele (and xylem)
|
| 393 |
+
n_recovered_phloem = 0
|
| 394 |
+
n_recovered_phloem_rf = 0
|
| 395 |
+
for cid, pred in list(predictions.items()):
|
| 396 |
+
if pred in ("stele", "xylem"):
|
| 397 |
+
phloem_prob = _effective_prob(cid, "phloem")
|
| 398 |
+
probs = proba_lookup.get(cid, {})
|
| 399 |
+
current_prob = probs.get(pred, 0.0)
|
| 400 |
+
if phloem_prob >= 0.12 and phloem_prob >= current_prob - 0.25:
|
| 401 |
+
predictions[cid] = "phloem"
|
| 402 |
+
n_recovered_phloem += 1
|
| 403 |
+
if probs.get("phloem", 0.0) < 0.05:
|
| 404 |
+
n_recovered_phloem_rf += 1
|
| 405 |
+
if n_recovered_phloem > 0:
|
| 406 |
+
msg = f" Post-processing: recovered {n_recovered_phloem} phloem cells from stele/xylem"
|
| 407 |
+
if n_recovered_phloem_rf > 0:
|
| 408 |
+
msg += f" ({n_recovered_phloem_rf} via RF fallback)"
|
| 409 |
+
print(msg)
|
| 410 |
+
|
| 411 |
+
# Recover xylem from stele
|
| 412 |
+
n_recovered_xylem = 0
|
| 413 |
+
n_recovered_xylem_rf = 0
|
| 414 |
+
for cid, pred in list(predictions.items()):
|
| 415 |
+
if pred == "stele":
|
| 416 |
+
xylem_prob = _effective_prob(cid, "xylem")
|
| 417 |
+
probs = proba_lookup.get(cid, {})
|
| 418 |
+
current_prob = probs.get(pred, 0.0)
|
| 419 |
+
if xylem_prob >= 0.08 and xylem_prob >= current_prob - 0.30:
|
| 420 |
+
predictions[cid] = "xylem"
|
| 421 |
+
n_recovered_xylem += 1
|
| 422 |
+
if probs.get("xylem", 0.0) < 0.05:
|
| 423 |
+
n_recovered_xylem_rf += 1
|
| 424 |
+
if n_recovered_xylem > 0:
|
| 425 |
+
msg = f" Post-processing: recovered {n_recovered_xylem} xylem cells from stele"
|
| 426 |
+
if n_recovered_xylem_rf > 0:
|
| 427 |
+
msg += f" ({n_recovered_xylem_rf} via RF fallback)"
|
| 428 |
+
print(msg)
|
| 429 |
+
|
| 430 |
+
# Xylem strand growing
|
| 431 |
+
n_strand_grown = 0
|
| 432 |
+
for _round in range(3):
|
| 433 |
+
grown_this_round = 0
|
| 434 |
+
current_xylem = {cid for cid, p in predictions.items() if p == "xylem"}
|
| 435 |
+
for cid, pred in list(predictions.items()):
|
| 436 |
+
if pred != "stele":
|
| 437 |
+
continue
|
| 438 |
+
nbrs = adjacency.get(cid, set())
|
| 439 |
+
n_xylem_nbrs = sum(1 for n in nbrs if n in current_xylem)
|
| 440 |
+
if n_xylem_nbrs >= 2:
|
| 441 |
+
xylem_prob = _effective_prob(cid, "xylem")
|
| 442 |
+
if xylem_prob >= 0.05:
|
| 443 |
+
predictions[cid] = "xylem"
|
| 444 |
+
grown_this_round += 1
|
| 445 |
+
n_strand_grown += grown_this_round
|
| 446 |
+
if grown_this_round == 0:
|
| 447 |
+
break
|
| 448 |
+
if n_strand_grown > 0:
|
| 449 |
+
print(f" Post-processing: grew xylem strands by {n_strand_grown} cells")
|
| 450 |
+
|
| 451 |
+
# Update dataframe
|
| 452 |
+
df["predicted_cell_type"] = df["cell_id"].map(predictions)
|
| 453 |
+
return df, predictions
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _prepare_features(df_base, feature_cols, scaler):
|
| 457 |
+
"""Align feature columns and scale. Returns X_scaled, handling NaN."""
|
| 458 |
+
for col in feature_cols:
|
| 459 |
+
if col not in df_base.columns:
|
| 460 |
+
df_base[col] = 0.0
|
| 461 |
+
|
| 462 |
+
X = df_base[feature_cols].values.astype(np.float32)
|
| 463 |
+
|
| 464 |
+
# Handle NaN
|
| 465 |
+
nan_mask = np.isnan(X)
|
| 466 |
+
if nan_mask.any():
|
| 467 |
+
col_means = np.nanmean(X, axis=0)
|
| 468 |
+
for j in range(X.shape[1]):
|
| 469 |
+
X[nan_mask[:, j], j] = col_means[j] if not np.isnan(col_means[j]) else 0.0
|
| 470 |
+
|
| 471 |
+
X_scaled = scaler.transform(X)
|
| 472 |
+
return X_scaled
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def iterative_predict(model, df_base, adjacency, feature_cols, scaler, le,
|
| 476 |
+
max_rounds=10):
|
| 477 |
+
"""
|
| 478 |
+
Iteratively predict cell types until neighbor-celltype features converge.
|
| 479 |
+
|
| 480 |
+
Round 1: predict with neighbor celltypes = -1 (unknown)
|
| 481 |
+
Round N: fill neighbor celltypes from round N-1 predictions, re-predict
|
| 482 |
+
Stop when no predictions change or max_rounds reached.
|
| 483 |
+
|
| 484 |
+
Returns: (df, pred_names, y_proba) from the final round.
|
| 485 |
+
"""
|
| 486 |
+
neighbor_ct_cols = ["radial_inward_neighbor_celltype", "radial_outward_neighbor_celltype",
|
| 487 |
+
"tangential_cw_neighbor_celltype", "tangential_ccw_neighbor_celltype"]
|
| 488 |
+
has_neighbor_ct = any(c in feature_cols for c in neighbor_ct_cols)
|
| 489 |
+
|
| 490 |
+
prev_pred_names = None
|
| 491 |
+
best_pred_names = None
|
| 492 |
+
best_proba = None
|
| 493 |
+
best_df = None
|
| 494 |
+
best_n_changed = float("inf")
|
| 495 |
+
prev_n_changed = float("inf")
|
| 496 |
+
n_stalled = 0 # count rounds where n_changed doesn't decrease
|
| 497 |
+
|
| 498 |
+
for round_num in range(1, max_rounds + 1):
|
| 499 |
+
df_round = df_base.copy()
|
| 500 |
+
|
| 501 |
+
if has_neighbor_ct:
|
| 502 |
+
if round_num == 1:
|
| 503 |
+
# First round: no neighbor celltype info
|
| 504 |
+
df_round = compute_neighbor_celltypes(
|
| 505 |
+
df_round, adjacency, cell_type_labels=None
|
| 506 |
+
)
|
| 507 |
+
else:
|
| 508 |
+
# Use previous round's predictions as neighbor celltypes
|
| 509 |
+
prev_labels = {}
|
| 510 |
+
for i, cid in enumerate(df_base["cell_id"].values):
|
| 511 |
+
prev_labels[int(cid)] = CELL_CLASSES.get(prev_pred_names[i], -1)
|
| 512 |
+
|
| 513 |
+
df_round = compute_neighbor_celltypes(
|
| 514 |
+
df_round, adjacency, cell_type_labels=prev_labels
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
X_scaled = _prepare_features(df_round, feature_cols, scaler)
|
| 518 |
+
y_pred = model.predict(X_scaled)
|
| 519 |
+
y_proba = model.predict_proba(X_scaled)
|
| 520 |
+
pred_names = le.inverse_transform(y_pred)
|
| 521 |
+
|
| 522 |
+
# Count changes from previous round
|
| 523 |
+
if prev_pred_names is not None:
|
| 524 |
+
n_changed = sum(1 for a, b in zip(prev_pred_names, pred_names) if a != b)
|
| 525 |
+
n_total = len(pred_names)
|
| 526 |
+
print(f" Round {round_num}: {n_changed}/{n_total} cells changed "
|
| 527 |
+
f"({100.0 * n_changed / n_total:.2f}%)")
|
| 528 |
+
|
| 529 |
+
if n_changed == 0:
|
| 530 |
+
print(f" Converged at round {round_num}!")
|
| 531 |
+
best_pred_names = pred_names.copy()
|
| 532 |
+
best_proba = y_proba.copy()
|
| 533 |
+
best_df = df_round.copy()
|
| 534 |
+
break
|
| 535 |
+
|
| 536 |
+
# Track best round (fewest changes = most stable)
|
| 537 |
+
if n_changed < best_n_changed:
|
| 538 |
+
best_n_changed = n_changed
|
| 539 |
+
best_pred_names = pred_names.copy()
|
| 540 |
+
best_proba = y_proba.copy()
|
| 541 |
+
best_df = df_round.copy()
|
| 542 |
+
n_stalled = 0
|
| 543 |
+
else:
|
| 544 |
+
n_stalled += 1
|
| 545 |
+
|
| 546 |
+
# Detect oscillation: if no improvement for 3 rounds, stop
|
| 547 |
+
if n_stalled >= 3:
|
| 548 |
+
print(f" Oscillation detected (no improvement for 3 rounds), "
|
| 549 |
+
f"using best round with {best_n_changed} changes.")
|
| 550 |
+
break
|
| 551 |
+
|
| 552 |
+
prev_n_changed = n_changed
|
| 553 |
+
else:
|
| 554 |
+
print(f" Round 1: initial prediction ({len(pred_names)} cells)")
|
| 555 |
+
best_pred_names = pred_names.copy()
|
| 556 |
+
best_proba = y_proba.copy()
|
| 557 |
+
best_df = df_round.copy()
|
| 558 |
+
|
| 559 |
+
prev_pred_names = pred_names.copy()
|
| 560 |
+
|
| 561 |
+
else:
|
| 562 |
+
print(f" Reached max rounds ({max_rounds}), "
|
| 563 |
+
f"using best round with {best_n_changed} changes.")
|
| 564 |
+
|
| 565 |
+
return best_df, best_pred_names, best_proba
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def load_image(tif_path):
|
| 569 |
+
"""Read a TIFF and return it as an RGB uint8 array (z-stacks max-projected)."""
|
| 570 |
+
img_raw = imread(str(tif_path))
|
| 571 |
+
return ensure_rgb_uint8(img_raw, stack_mode="max")
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 575 |
+
# PIPELINE STAGES
|
| 576 |
+
#
|
| 577 |
+
# predict_single_tif() below runs these in order. They are also exposed
|
| 578 |
+
# separately so a caller that pays for GPU time by the second (a web app on
|
| 579 |
+
# ZeroGPU, say) can wrap only stage_segment and stage_embed β the two steps
|
| 580 |
+
# that actually touch the GPU β and run the rest on CPU.
|
| 581 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 582 |
+
|
| 583 |
+
def stage_segment(img_rgb, gpu=True, cellpose_model=None):
|
| 584 |
+
"""GPU stage 1 β Cellpose-SAM. Returns the int32 label mask."""
|
| 585 |
+
return segment_cellpose_sam(img_rgb, use_gpu=gpu, model=cellpose_model)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def stage_features(masks, img_rgb, um_per_px=1.0, verbose=True):
|
| 589 |
+
"""CPU stage β tissue mask, layer index, debris removal, handcrafted
|
| 590 |
+
features.
|
| 591 |
+
|
| 592 |
+
Debris removal edits ``masks`` in place, so the (possibly modified) mask is
|
| 593 |
+
returned alongside the feature table.
|
| 594 |
+
|
| 595 |
+
Returns ``(masks, df_base, layer_lookup, adjacency, n_layers)``, or
|
| 596 |
+
``(masks, None, ...)`` if every cell was debris.
|
| 597 |
+
"""
|
| 598 |
+
if verbose:
|
| 599 |
+
print(" Computing layer index...")
|
| 600 |
+
tissue = build_tissue_mask(masks)
|
| 601 |
+
layer_lookup, n_layers, adjacency = compute_layer_index_edt(masks, tissue)
|
| 602 |
+
if verbose:
|
| 603 |
+
print(f" {n_layers} layers")
|
| 604 |
+
|
| 605 |
+
# Filter out debris cells outside the main tissue body
|
| 606 |
+
n_cells = int(masks.max())
|
| 607 |
+
debris_cells = set()
|
| 608 |
+
for cid in range(1, n_cells + 1):
|
| 609 |
+
cell_px = masks == cid
|
| 610 |
+
n_total = cell_px.sum()
|
| 611 |
+
if n_total == 0:
|
| 612 |
+
continue
|
| 613 |
+
n_in_tissue = (cell_px & tissue).sum()
|
| 614 |
+
if n_in_tissue / n_total < 0.5:
|
| 615 |
+
debris_cells.add(cid)
|
| 616 |
+
if debris_cells:
|
| 617 |
+
if verbose:
|
| 618 |
+
print(f" Removed {len(debris_cells)} debris cells outside tissue")
|
| 619 |
+
for cid in debris_cells:
|
| 620 |
+
masks[masks == cid] = 0
|
| 621 |
+
layer_lookup.pop(cid, None)
|
| 622 |
+
n_cells = int(masks.max())
|
| 623 |
+
|
| 624 |
+
if n_cells == 0:
|
| 625 |
+
return masks, None, layer_lookup, adjacency, n_layers
|
| 626 |
+
|
| 627 |
+
if verbose:
|
| 628 |
+
print(" Extracting features...")
|
| 629 |
+
df_base = extract_all_features(masks, img_rgb, um_per_px, layer_lookup,
|
| 630 |
+
adjacency, tissue_mask=tissue)
|
| 631 |
+
df_base["n_layers_total"] = n_layers
|
| 632 |
+
return masks, df_base, layer_lookup, adjacency, n_layers
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def stage_embed(masks, img_rgb, df_base, gpu=True, cnn_weights=None,
|
| 636 |
+
dinov2_model=None, verbose=True):
|
| 637 |
+
"""GPU stage 2 β fine-tuned DINOv2 per-cell embeddings, merged into
|
| 638 |
+
``df_base``. Returns the merged table (unchanged if embeddings are
|
| 639 |
+
unavailable)."""
|
| 640 |
+
if verbose:
|
| 641 |
+
print(" Extracting CNN embeddings...")
|
| 642 |
+
cnn_df = extract_cnn_embedding_features(masks, img_rgb, use_gpu=gpu,
|
| 643 |
+
weights_path=cnn_weights,
|
| 644 |
+
model=dinov2_model)
|
| 645 |
+
if cnn_df is not None:
|
| 646 |
+
df_base = df_base.merge(cnn_df, on="cell_id", how="left")
|
| 647 |
+
emb_cols = [c for c in df_base.columns if c.startswith("cnn_emb_")]
|
| 648 |
+
df_base[emb_cols] = df_base[emb_cols].fillna(0.0)
|
| 649 |
+
return df_base
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def stage_classify(df_base, masks, img_rgb, layer_lookup, adjacency,
|
| 653 |
+
models_dict, scalers, feature_cols, le,
|
| 654 |
+
out_dir="predictions", stem="image", source_name=None,
|
| 655 |
+
um_per_px=1.0, max_rounds=10, label_cells=False):
|
| 656 |
+
"""CPU stage β iterative prediction with each model plus the weighted
|
| 657 |
+
ensemble, anatomical post-processing, and per-model CSV + overlay PNG.
|
| 658 |
+
|
| 659 |
+
Returns the concatenated per-cell table across all models."""
|
| 660 |
+
out_dir = Path(out_dir)
|
| 661 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 662 |
+
if source_name is None:
|
| 663 |
+
source_name = f"{stem}.tif"
|
| 664 |
+
|
| 665 |
+
all_dfs = []
|
| 666 |
+
model_probas = {} # model_name -> (cell_ids, y_proba)
|
| 667 |
+
for model_name, model in models_dict.items():
|
| 668 |
+
print(f"\n --- {model_name} (iterative, max {max_rounds} rounds) ---")
|
| 669 |
+
|
| 670 |
+
model_scaler = scalers[model_name]
|
| 671 |
+
df, pred_names, y_proba = iterative_predict(
|
| 672 |
+
model, df_base, adjacency, feature_cols, model_scaler, le,
|
| 673 |
+
max_rounds=max_rounds,
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
pred_conf = y_proba.max(axis=1)
|
| 677 |
+
df["predicted_cell_type"] = pred_names
|
| 678 |
+
df["prediction_confidence"] = np.round(pred_conf, 4)
|
| 679 |
+
df["source_file"] = source_name
|
| 680 |
+
df["um_per_px"] = um_per_px
|
| 681 |
+
df["model"] = model_name
|
| 682 |
+
|
| 683 |
+
# Report (before post-processing)
|
| 684 |
+
print(f" Model predictions:")
|
| 685 |
+
for ct, cnt in pd.Series(pred_names).value_counts().items():
|
| 686 |
+
print(f" {ct}: {cnt}")
|
| 687 |
+
|
| 688 |
+
# Anatomical post-processing
|
| 689 |
+
rf_fallback = None
|
| 690 |
+
if model_name != "RandomForest" and "RandomForest" in model_probas:
|
| 691 |
+
rf_cids, rf_proba_arr = model_probas["RandomForest"]
|
| 692 |
+
rf_class_names = list(le.classes_)
|
| 693 |
+
rf_fallback = {}
|
| 694 |
+
for i, cid in enumerate(rf_cids):
|
| 695 |
+
rf_fallback[int(cid)] = dict(zip(rf_class_names, rf_proba_arr[i]))
|
| 696 |
+
|
| 697 |
+
print(f" Applying anatomical post-processing...")
|
| 698 |
+
df, cell_predictions = anatomical_postprocess(
|
| 699 |
+
df, layer_lookup, adjacency, masks, le=le, y_proba=y_proba,
|
| 700 |
+
rf_proba_lookup=rf_fallback
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
# Report (after post-processing)
|
| 704 |
+
final_preds = df["predicted_cell_type"].values
|
| 705 |
+
print(f" Final predictions:")
|
| 706 |
+
for ct, cnt in pd.Series(final_preds).value_counts().items():
|
| 707 |
+
print(f" {ct}: {cnt}")
|
| 708 |
+
|
| 709 |
+
# Count vascular poles
|
| 710 |
+
final_labels = {}
|
| 711 |
+
for cid, pred in cell_predictions.items():
|
| 712 |
+
final_labels[cid] = CELL_CLASSES.get(pred, -1)
|
| 713 |
+
pole_info = count_vascular_poles(final_labels, adjacency, masks)
|
| 714 |
+
n_ph = pole_info["phloem"]["n_poles"]
|
| 715 |
+
n_xy = pole_info["xylem"]["n_poles"]
|
| 716 |
+
print(f" Vascular poles: phloem={n_ph}, xylem={n_xy}")
|
| 717 |
+
|
| 718 |
+
df["n_phloem_poles"] = n_ph
|
| 719 |
+
df["n_xylem_poles"] = n_xy
|
| 720 |
+
|
| 721 |
+
# Store probabilities for ensemble
|
| 722 |
+
model_probas[model_name] = (df["cell_id"].values.copy(), y_proba.copy())
|
| 723 |
+
|
| 724 |
+
# Save per-model CSV
|
| 725 |
+
csv_path = out_dir / f"{stem}_{model_name}_predictions.csv"
|
| 726 |
+
df.to_csv(csv_path, index=False)
|
| 727 |
+
print(f" Saved: {csv_path}")
|
| 728 |
+
|
| 729 |
+
# Save per-model overlay PNG
|
| 730 |
+
overlay_path = out_dir / f"{stem}_{model_name}_overlay.png"
|
| 731 |
+
save_prediction_overlay(img_rgb, masks, cell_predictions,
|
| 732 |
+
overlay_path, le, label_cells=label_cells)
|
| 733 |
+
print(f" Saved: {overlay_path}")
|
| 734 |
+
|
| 735 |
+
all_dfs.append(df)
|
| 736 |
+
|
| 737 |
+
# -- Ensemble voting (average probabilities across models) --
|
| 738 |
+
if len(model_probas) >= 2:
|
| 739 |
+
print(f"\n --- Ensemble ({len(model_probas)} models) ---")
|
| 740 |
+
|
| 741 |
+
ref_model = list(model_probas.keys())[0]
|
| 742 |
+
ref_cell_ids = model_probas[ref_model][0]
|
| 743 |
+
n_classes = model_probas[ref_model][1].shape[1]
|
| 744 |
+
|
| 745 |
+
minority_classes = {"xylem", "phloem"}
|
| 746 |
+
minority_idx = set()
|
| 747 |
+
for cls_name in minority_classes:
|
| 748 |
+
try:
|
| 749 |
+
minority_idx.add(list(le.classes_).index(cls_name))
|
| 750 |
+
except ValueError:
|
| 751 |
+
pass
|
| 752 |
+
rf_trust_threshold = 0.20
|
| 753 |
+
|
| 754 |
+
avg_proba = np.zeros((len(ref_cell_ids), n_classes), dtype=np.float64)
|
| 755 |
+
n_models = len(model_probas)
|
| 756 |
+
rf_proba = model_probas.get("RandomForest", (None, None))[1]
|
| 757 |
+
|
| 758 |
+
if rf_proba is not None and minority_idx:
|
| 759 |
+
rf_top_idx = np.argmax(rf_proba, axis=1)
|
| 760 |
+
rf_top_conf = rf_proba[np.arange(len(rf_proba)), rf_top_idx]
|
| 761 |
+
rf_minority_mask = np.array([
|
| 762 |
+
(idx in minority_idx and conf >= rf_trust_threshold)
|
| 763 |
+
for idx, conf in zip(rf_top_idx, rf_top_conf)
|
| 764 |
+
])
|
| 765 |
+
n_rf_trusted = rf_minority_mask.sum()
|
| 766 |
+
print(f" RF-trust rule: {n_rf_trusted} cells where RF predicts minority class")
|
| 767 |
+
|
| 768 |
+
for mname, (cids, proba) in model_probas.items():
|
| 769 |
+
weight = np.ones(len(ref_cell_ids), dtype=np.float64)
|
| 770 |
+
if mname == "RandomForest":
|
| 771 |
+
weight[rf_minority_mask] = 2.0
|
| 772 |
+
avg_proba += proba * weight[:, np.newaxis]
|
| 773 |
+
total_weight = np.full(len(ref_cell_ids), float(n_models), dtype=np.float64)
|
| 774 |
+
total_weight[rf_minority_mask] += 1.0
|
| 775 |
+
avg_proba /= total_weight[:, np.newaxis]
|
| 776 |
+
else:
|
| 777 |
+
for mname, (cids, proba) in model_probas.items():
|
| 778 |
+
avg_proba += proba
|
| 779 |
+
avg_proba /= n_models
|
| 780 |
+
|
| 781 |
+
ens_pred_idx = np.argmax(avg_proba, axis=1)
|
| 782 |
+
ens_pred_names = le.inverse_transform(ens_pred_idx)
|
| 783 |
+
ens_conf = avg_proba.max(axis=1)
|
| 784 |
+
|
| 785 |
+
df_ens = df_base.copy()
|
| 786 |
+
df_ens["predicted_cell_type"] = ens_pred_names
|
| 787 |
+
df_ens["prediction_confidence"] = np.round(ens_conf, 4)
|
| 788 |
+
df_ens["source_file"] = source_name
|
| 789 |
+
df_ens["um_per_px"] = um_per_px
|
| 790 |
+
df_ens["model"] = "Ensemble"
|
| 791 |
+
|
| 792 |
+
print(f" Ensemble predictions:")
|
| 793 |
+
for ct, cnt in pd.Series(ens_pred_names).value_counts().items():
|
| 794 |
+
print(f" {ct}: {cnt}")
|
| 795 |
+
|
| 796 |
+
print(f" Applying anatomical post-processing...")
|
| 797 |
+
df_ens, ens_cell_predictions = anatomical_postprocess(
|
| 798 |
+
df_ens, layer_lookup, adjacency, masks, le=le, y_proba=avg_proba
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
final_ens_preds = df_ens["predicted_cell_type"].values
|
| 802 |
+
print(f" Final predictions:")
|
| 803 |
+
for ct, cnt in pd.Series(final_ens_preds).value_counts().items():
|
| 804 |
+
print(f" {ct}: {cnt}")
|
| 805 |
+
|
| 806 |
+
ens_final_labels = {}
|
| 807 |
+
for cid, pred in ens_cell_predictions.items():
|
| 808 |
+
ens_final_labels[cid] = CELL_CLASSES.get(pred, -1)
|
| 809 |
+
ens_pole_info = count_vascular_poles(ens_final_labels, adjacency, masks)
|
| 810 |
+
n_ph_ens = ens_pole_info["phloem"]["n_poles"]
|
| 811 |
+
n_xy_ens = ens_pole_info["xylem"]["n_poles"]
|
| 812 |
+
print(f" Vascular poles: phloem={n_ph_ens}, xylem={n_xy_ens}")
|
| 813 |
+
|
| 814 |
+
df_ens["n_phloem_poles"] = n_ph_ens
|
| 815 |
+
df_ens["n_xylem_poles"] = n_xy_ens
|
| 816 |
+
|
| 817 |
+
ens_csv_path = out_dir / f"{stem}_Ensemble_predictions.csv"
|
| 818 |
+
df_ens.to_csv(ens_csv_path, index=False)
|
| 819 |
+
print(f" Saved: {ens_csv_path}")
|
| 820 |
+
|
| 821 |
+
ens_overlay_path = out_dir / f"{stem}_Ensemble_overlay.png"
|
| 822 |
+
save_prediction_overlay(img_rgb, masks, ens_cell_predictions,
|
| 823 |
+
ens_overlay_path, le, label_cells=label_cells)
|
| 824 |
+
print(f" Saved: {ens_overlay_path}")
|
| 825 |
+
|
| 826 |
+
all_dfs.append(df_ens)
|
| 827 |
+
|
| 828 |
+
return pd.concat(all_dfs, ignore_index=True)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def predict_single_tif(tif_path, models_dict, scalers, feature_cols, le,
|
| 832 |
+
um_per_px=1.0, gpu=True, out_dir="predictions",
|
| 833 |
+
max_rounds=10, cnn_weights=None, label_cells=False,
|
| 834 |
+
cellpose_model=None, dinov2_model=None):
|
| 835 |
+
"""
|
| 836 |
+
Full pipeline: segment -> features -> iterative predict -> overlay.
|
| 837 |
+
"""
|
| 838 |
+
out_dir = Path(out_dir)
|
| 839 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 840 |
+
stem = Path(tif_path).stem.replace(".aivia", "")
|
| 841 |
+
|
| 842 |
+
print(f"\n Processing: {tif_path}")
|
| 843 |
+
|
| 844 |
+
# Load TIF
|
| 845 |
+
img_rgb = load_image(tif_path)
|
| 846 |
+
print(f" Image shape: {img_rgb.shape}")
|
| 847 |
+
|
| 848 |
+
# Segment
|
| 849 |
+
print(" Segmenting (Cellpose-SAM)...")
|
| 850 |
+
masks = stage_segment(img_rgb, gpu=gpu, cellpose_model=cellpose_model)
|
| 851 |
+
n_cells = int(masks.max())
|
| 852 |
+
print(f" {n_cells} cells found")
|
| 853 |
+
|
| 854 |
+
if n_cells == 0:
|
| 855 |
+
print(" No cells found, skipping.")
|
| 856 |
+
return None
|
| 857 |
+
|
| 858 |
+
# BFS layer index, debris removal, handcrafted features
|
| 859 |
+
masks, df_base, layer_lookup, adjacency, n_layers = stage_features(
|
| 860 |
+
masks, img_rgb, um_per_px=um_per_px)
|
| 861 |
+
if df_base is None:
|
| 862 |
+
print(" No cells left after debris removal, skipping.")
|
| 863 |
+
return None
|
| 864 |
+
|
| 865 |
+
# CNN embeddings
|
| 866 |
+
df_base = stage_embed(masks, img_rgb, df_base, gpu=gpu,
|
| 867 |
+
cnn_weights=cnn_weights, dinov2_model=dinov2_model)
|
| 868 |
+
|
| 869 |
+
return stage_classify(
|
| 870 |
+
df_base, masks, img_rgb, layer_lookup, adjacency,
|
| 871 |
+
models_dict, scalers, feature_cols, le,
|
| 872 |
+
out_dir=out_dir, stem=stem, source_name=Path(tif_path).name,
|
| 873 |
+
um_per_px=um_per_px, max_rounds=max_rounds, label_cells=label_cells,
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def main():
|
| 878 |
+
parser = argparse.ArgumentParser(
|
| 879 |
+
description="Predict cell types on new TIF images (iterative refinement)"
|
| 880 |
+
)
|
| 881 |
+
parser.add_argument("--tif", default=None,
|
| 882 |
+
help="Single TIF path")
|
| 883 |
+
parser.add_argument("--tif-dir", default=None,
|
| 884 |
+
help="Directory of TIF files (batch mode)")
|
| 885 |
+
parser.add_argument("--model-dir", required=True,
|
| 886 |
+
help="Directory with trained model artifacts")
|
| 887 |
+
parser.add_argument("--um-per-px", type=float, default=1.0,
|
| 888 |
+
help="Microns per pixel (default 1.0)")
|
| 889 |
+
parser.add_argument("--gpu", action="store_true",
|
| 890 |
+
help="Use GPU for Cellpose")
|
| 891 |
+
parser.add_argument("--out-dir", default="predictions",
|
| 892 |
+
help="Output directory")
|
| 893 |
+
parser.add_argument("--max-rounds", type=int, default=10,
|
| 894 |
+
help="Max iterative prediction rounds (default 10)")
|
| 895 |
+
parser.add_argument("--cnn-weights", default=None,
|
| 896 |
+
help="Path to fine-tuned DINOv2 backbone.pt (must "
|
| 897 |
+
"match what the models were trained on). "
|
| 898 |
+
"If omitted, uses pretrained DINOv2.")
|
| 899 |
+
args = parser.parse_args()
|
| 900 |
+
|
| 901 |
+
if not args.tif and not args.tif_dir:
|
| 902 |
+
parser.error("Provide --tif for single image or --tif-dir for batch")
|
| 903 |
+
|
| 904 |
+
print("=" * 60)
|
| 905 |
+
print("CELL TYPE PREDICTION (ITERATIVE)")
|
| 906 |
+
print("=" * 60)
|
| 907 |
+
|
| 908 |
+
print("\n[1] Loading models...")
|
| 909 |
+
models_dict, scalers, feature_cols, le = load_models(args.model_dir)
|
| 910 |
+
|
| 911 |
+
if not models_dict:
|
| 912 |
+
print(" ERROR: No models found. Run train_classifier.py first.")
|
| 913 |
+
return
|
| 914 |
+
|
| 915 |
+
# Collect TIF paths
|
| 916 |
+
if args.tif:
|
| 917 |
+
tif_paths = [Path(args.tif)]
|
| 918 |
+
else:
|
| 919 |
+
tif_dir = Path(args.tif_dir)
|
| 920 |
+
tif_paths = sorted(tif_dir.glob("*.tif"))
|
| 921 |
+
print(f"\n Found {len(tif_paths)} TIF files in {tif_dir}")
|
| 922 |
+
|
| 923 |
+
print(f"\n[2] Predicting cell types with {len(models_dict)} models "
|
| 924 |
+
f"({', '.join(models_dict.keys())}) β iterative, max {args.max_rounds} rounds...")
|
| 925 |
+
all_tables = []
|
| 926 |
+
for tif_path in tif_paths:
|
| 927 |
+
try:
|
| 928 |
+
df = predict_single_tif(
|
| 929 |
+
str(tif_path), models_dict, scalers, feature_cols, le,
|
| 930 |
+
um_per_px=args.um_per_px, gpu=args.gpu, out_dir=args.out_dir,
|
| 931 |
+
max_rounds=args.max_rounds,
|
| 932 |
+
cnn_weights=args.cnn_weights,
|
| 933 |
+
label_cells=getattr(args, "label_cells", False),
|
| 934 |
+
)
|
| 935 |
+
if df is not None:
|
| 936 |
+
all_tables.append(df)
|
| 937 |
+
except Exception as e:
|
| 938 |
+
print(f" FAILED: {e}")
|
| 939 |
+
import traceback
|
| 940 |
+
traceback.print_exc()
|
| 941 |
+
|
| 942 |
+
# Combined CSV (all models x all images)
|
| 943 |
+
if all_tables:
|
| 944 |
+
combined = pd.concat(all_tables, ignore_index=True)
|
| 945 |
+
combined_path = Path(args.out_dir) / "all_predictions.csv"
|
| 946 |
+
combined.to_csv(combined_path, index=False)
|
| 947 |
+
print(f"\n Combined predictions: {combined_path} ({len(combined)} rows)")
|
| 948 |
+
|
| 949 |
+
print(f"\n{'=' * 60}")
|
| 950 |
+
print(f"DONE. Results in {args.out_dir}/")
|
| 951 |
+
print(f"{'=' * 60}")
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
if __name__ == "__main__":
|
| 955 |
+
main()
|
rootscope/weights.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Model-weight resolution for Rootscope.
|
| 3 |
+
|
| 4 |
+
The trained classifier models and the fine-tuned DINOv2 backbone are too large
|
| 5 |
+
to ship inside the pip/conda package, so Rootscope resolves them at run time in
|
| 6 |
+
this priority order:
|
| 7 |
+
|
| 8 |
+
1. An explicit path you pass (``--model-dir`` / ``--cnn-weights``).
|
| 9 |
+
2. Environment variables ``ROOTSCOPE_MODEL_DIR`` / ``ROOTSCOPE_CNN_WEIGHTS``.
|
| 10 |
+
3. A local ``models/`` folder next to the installed package.
|
| 11 |
+
4. Auto-download from the Hugging Face Hub repo ``DEFAULT_HF_REPO``, cached in
|
| 12 |
+
``~/.cache/huggingface`` (override with ``ROOTSCOPE_HF_REPO``).
|
| 13 |
+
5. Auto-download from a plain base URL, if ``ROOTSCOPE_MODELS_URL`` is set β
|
| 14 |
+
an escape hatch for self-hosting the weights somewhere else.
|
| 15 |
+
|
| 16 |
+
The very first prediction downloads the weights once; every run after that uses
|
| 17 |
+
the cache. Downloads via the Hub resume if interrupted and are checksummed, so
|
| 18 |
+
a dropped connection does not mean starting over.
|
| 19 |
+
|
| 20 |
+
Note: the Cellpose-SAM segmentation weights are NOT handled here β the
|
| 21 |
+
``cellpose`` library downloads and caches those itself on first use.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
# `X | None` annotations below need this on Python 3.9,
|
| 25 |
+
# which pyproject still declares as the supported floor.
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import os
|
| 29 |
+
import sys
|
| 30 |
+
import urllib.request
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
# Where the published weights live: a Hugging Face model repo whose root
|
| 35 |
+
# contains the .joblib model files and backbone.pt.
|
| 36 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
+
DEFAULT_HF_REPO = "ct-tranchau/Rootscope"
|
| 38 |
+
|
| 39 |
+
# Optional escape hatch: a plain base URL under which each file name below is
|
| 40 |
+
# directly downloadable, e.g. "https://zenodo.org/records/XXXXXXX/files".
|
| 41 |
+
# Only used if the environment variable ROOTSCOPE_MODELS_URL is set.
|
| 42 |
+
DEFAULT_MODELS_URL = ""
|
| 43 |
+
|
| 44 |
+
# Classifier artifacts.
|
| 45 |
+
#
|
| 46 |
+
# All three models are published and downloaded by default. RandomForest is the
|
| 47 |
+
# large one (~350 MB), and it is listed as OPTIONAL only so that prediction
|
| 48 |
+
# degrades gracefully to XGBoost + LightGBM if a user supplies their own
|
| 49 |
+
# --model-dir without it. Do not treat that as a reason to omit it from a
|
| 50 |
+
# release: the ensemble double-weights RandomForest wherever it predicts a
|
| 51 |
+
# minority class (see the RF-trust rule in predict.py), and RF is the only
|
| 52 |
+
# bagging model of the three, so it decorrelates from the two boosting models.
|
| 53 |
+
MODEL_FILES_REQUIRED = [
|
| 54 |
+
"feature_columns.joblib",
|
| 55 |
+
"label_encoder.joblib",
|
| 56 |
+
"model_XGBoost.joblib",
|
| 57 |
+
"feature_scaler_XGBoost.joblib",
|
| 58 |
+
"model_LightGBM.joblib",
|
| 59 |
+
"feature_scaler_LightGBM.joblib",
|
| 60 |
+
]
|
| 61 |
+
MODEL_FILES_OPTIONAL = [
|
| 62 |
+
"model_RandomForest.joblib",
|
| 63 |
+
"feature_scaler_RandomForest.joblib",
|
| 64 |
+
]
|
| 65 |
+
CNN_WEIGHTS_FILE = "backbone.pt"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _cache_dir() -> Path:
|
| 69 |
+
root = os.environ.get("ROOTSCOPE_CACHE")
|
| 70 |
+
base = Path(root) if root else Path.home() / ".cache" / "rootscope"
|
| 71 |
+
return base
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _package_models_dir() -> Path:
|
| 75 |
+
return Path(__file__).resolve().parent.parent / "models"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _hf_repo() -> str:
|
| 79 |
+
return os.environ.get("ROOTSCOPE_HF_REPO", DEFAULT_HF_REPO).strip()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _models_base_url() -> str:
|
| 83 |
+
return os.environ.get("ROOTSCOPE_MODELS_URL", DEFAULT_MODELS_URL).rstrip("/")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _has_required_models(d: Path) -> bool:
|
| 87 |
+
return d.is_dir() and all((d / f).exists() for f in MODEL_FILES_REQUIRED)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ββ Hugging Face Hub βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
def _hf_snapshot(repo: str, patterns) -> Path | None:
|
| 93 |
+
"""Download the matching files from the Hub and return the local folder."""
|
| 94 |
+
try:
|
| 95 |
+
from huggingface_hub import snapshot_download
|
| 96 |
+
except ImportError:
|
| 97 |
+
print(
|
| 98 |
+
"[rootscope] huggingface_hub is not installed, so the model weights "
|
| 99 |
+
"cannot be downloaded automatically.\n"
|
| 100 |
+
" Install it with `pip install huggingface_hub`, or pass "
|
| 101 |
+
"--model-dir / --cnn-weights explicitly."
|
| 102 |
+
)
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
local = snapshot_download(repo_id=repo, allow_patterns=list(patterns))
|
| 107 |
+
return Path(local)
|
| 108 |
+
except Exception as e: # noqa: BLE001
|
| 109 |
+
print(f"[rootscope] Could not fetch weights from Hugging Face repo '{repo}': {e}")
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ββ plain-URL fallback βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
+
|
| 115 |
+
def _download(url: str, dest: Path) -> None:
|
| 116 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 117 |
+
tmp = dest.with_suffix(dest.suffix + ".part")
|
| 118 |
+
|
| 119 |
+
def _hook(block_num, block_size, total_size):
|
| 120 |
+
if total_size <= 0:
|
| 121 |
+
return
|
| 122 |
+
done = min(block_num * block_size, total_size)
|
| 123 |
+
pct = 100.0 * done / total_size
|
| 124 |
+
sys.stdout.write(
|
| 125 |
+
f"\r {dest.name}: {done/1e6:6.1f} / {total_size/1e6:6.1f} MB "
|
| 126 |
+
f"({pct:5.1f}%)"
|
| 127 |
+
)
|
| 128 |
+
sys.stdout.flush()
|
| 129 |
+
|
| 130 |
+
print(f" Downloading {dest.name} ...")
|
| 131 |
+
urllib.request.urlretrieve(url, tmp, _hook) # noqa: S310 (trusted release URL)
|
| 132 |
+
sys.stdout.write("\n")
|
| 133 |
+
tmp.replace(dest)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _download_set(base_url: str, files, dest_dir: Path, skip_missing: bool):
|
| 137 |
+
for name in files:
|
| 138 |
+
target = dest_dir / name
|
| 139 |
+
if target.exists():
|
| 140 |
+
continue
|
| 141 |
+
url = f"{base_url}/{name}"
|
| 142 |
+
try:
|
| 143 |
+
_download(url, target)
|
| 144 |
+
except Exception as e: # noqa: BLE001
|
| 145 |
+
if skip_missing:
|
| 146 |
+
print(f" (optional) skipped {name}: {e}")
|
| 147 |
+
else:
|
| 148 |
+
raise
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ββ public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
+
|
| 153 |
+
def resolve_model_dir(user_arg: str | None = None) -> Path:
|
| 154 |
+
"""Return a directory containing the classifier artifacts, downloading
|
| 155 |
+
them on first use if necessary."""
|
| 156 |
+
# 1. explicit argument
|
| 157 |
+
if user_arg:
|
| 158 |
+
d = Path(user_arg)
|
| 159 |
+
if not _has_required_models(d):
|
| 160 |
+
raise FileNotFoundError(
|
| 161 |
+
f"--model-dir '{d}' does not contain the required model files "
|
| 162 |
+
f"({', '.join(MODEL_FILES_REQUIRED)})."
|
| 163 |
+
)
|
| 164 |
+
return d
|
| 165 |
+
|
| 166 |
+
# 2. environment variable
|
| 167 |
+
env = os.environ.get("ROOTSCOPE_MODEL_DIR")
|
| 168 |
+
if env and _has_required_models(Path(env)):
|
| 169 |
+
return Path(env)
|
| 170 |
+
|
| 171 |
+
# 3. models/ folder shipped alongside the package
|
| 172 |
+
pkg = _package_models_dir()
|
| 173 |
+
if _has_required_models(pkg):
|
| 174 |
+
return pkg
|
| 175 |
+
|
| 176 |
+
# 4. legacy cache from a previous plain-URL download
|
| 177 |
+
cache = _cache_dir() / "models"
|
| 178 |
+
if _has_required_models(cache):
|
| 179 |
+
return cache
|
| 180 |
+
|
| 181 |
+
# 5. Hugging Face Hub (the normal path)
|
| 182 |
+
repo = _hf_repo()
|
| 183 |
+
if repo:
|
| 184 |
+
print(f"[rootscope] Fetching model weights from Hugging Face '{repo}' (first run only)...")
|
| 185 |
+
snap = _hf_snapshot(repo, ["*.joblib"])
|
| 186 |
+
if snap is not None and _has_required_models(snap):
|
| 187 |
+
return snap
|
| 188 |
+
|
| 189 |
+
# 6. plain base URL, if configured
|
| 190 |
+
base_url = _models_base_url()
|
| 191 |
+
if base_url:
|
| 192 |
+
print(f"[rootscope] Fetching model weights into {cache} (first run only)...")
|
| 193 |
+
_download_set(base_url, MODEL_FILES_REQUIRED, cache, skip_missing=False)
|
| 194 |
+
_download_set(base_url, MODEL_FILES_OPTIONAL, cache, skip_missing=True)
|
| 195 |
+
return cache
|
| 196 |
+
|
| 197 |
+
raise RuntimeError(
|
| 198 |
+
"Rootscope could not find or download the trained model weights.\n"
|
| 199 |
+
"Do ONE of the following:\n"
|
| 200 |
+
" β’ Check your internet connection (weights come from the Hugging Face "
|
| 201 |
+
f"repo '{_hf_repo()}'), or\n"
|
| 202 |
+
" β’ Put the model files in a folder and pass --model-dir <folder>, or\n"
|
| 203 |
+
" β’ export ROOTSCOPE_MODEL_DIR=/path/to/models, or\n"
|
| 204 |
+
" β’ export ROOTSCOPE_MODELS_URL=<base url> to self-host them.\n"
|
| 205 |
+
f"Required files: {', '.join(MODEL_FILES_REQUIRED)}"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def resolve_cnn_weights(user_arg: str | None = None) -> Path | None:
|
| 210 |
+
"""Return the path to the fine-tuned DINOv2 backbone, or None to fall back
|
| 211 |
+
to pretrained DINOv2 (lower accuracy)."""
|
| 212 |
+
if user_arg:
|
| 213 |
+
p = Path(user_arg)
|
| 214 |
+
if not p.exists():
|
| 215 |
+
raise FileNotFoundError(f"--cnn-weights '{p}' not found.")
|
| 216 |
+
return p
|
| 217 |
+
|
| 218 |
+
env = os.environ.get("ROOTSCOPE_CNN_WEIGHTS")
|
| 219 |
+
if env and Path(env).exists():
|
| 220 |
+
return Path(env)
|
| 221 |
+
|
| 222 |
+
pkg = _package_models_dir() / CNN_WEIGHTS_FILE
|
| 223 |
+
if pkg.exists():
|
| 224 |
+
return pkg
|
| 225 |
+
|
| 226 |
+
cache = _cache_dir() / "models" / CNN_WEIGHTS_FILE
|
| 227 |
+
if cache.exists():
|
| 228 |
+
return cache
|
| 229 |
+
|
| 230 |
+
repo = _hf_repo()
|
| 231 |
+
if repo:
|
| 232 |
+
snap = _hf_snapshot(repo, [CNN_WEIGHTS_FILE])
|
| 233 |
+
if snap is not None and (snap / CNN_WEIGHTS_FILE).exists():
|
| 234 |
+
return snap / CNN_WEIGHTS_FILE
|
| 235 |
+
|
| 236 |
+
base_url = _models_base_url()
|
| 237 |
+
if base_url:
|
| 238 |
+
try:
|
| 239 |
+
_download(f"{base_url}/{CNN_WEIGHTS_FILE}", cache)
|
| 240 |
+
return cache
|
| 241 |
+
except Exception as e: # noqa: BLE001
|
| 242 |
+
print(f"[rootscope] Could not download {CNN_WEIGHTS_FILE}: {e}")
|
| 243 |
+
|
| 244 |
+
print(
|
| 245 |
+
"[rootscope] WARNING: fine-tuned DINOv2 backbone not found β falling "
|
| 246 |
+
"back to pretrained DINOv2. Predictions will be less accurate than the "
|
| 247 |
+
"published model. Provide --cnn-weights backbone.pt to fix this."
|
| 248 |
+
)
|
| 249 |
+
return None
|