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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import glob
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
import tifffile
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import matplotlib.subplots as plt_subplots
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
from scipy.ndimage import median_filter
|
| 10 |
+
from skimage.filters import gaussian
|
| 11 |
+
from skimage import exposure
|
| 12 |
+
from huggingface_hub import snapshot_download
|
| 13 |
+
from csbdeep.utils import normalize
|
| 14 |
+
from stardist.models import Config2D, StarDist2D
|
| 15 |
+
from stardist import fill_label_holes, calculate_extents, random_label_cmap
|
| 16 |
+
from stardist.matching import matching
|
| 17 |
+
|
| 18 |
+
# --- 1. Data Loading & Preparation ---
|
| 19 |
+
def load_and_split_dataset(repo_id="champ7/celldatamag", test_size=10):
|
| 20 |
+
print(f"Downloading dataset from Hugging Face: {repo_id}...")
|
| 21 |
+
local_dir = snapshot_download(repo_id=repo_id, repo_type="dataset")
|
| 22 |
+
|
| 23 |
+
# Target specifically _w2.TIF based on the dataset structure
|
| 24 |
+
search_path = os.path.join(local_dir, "**", "*_w2.TIF")
|
| 25 |
+
image_paths = sorted(glob.glob(search_path, recursive=True))
|
| 26 |
+
|
| 27 |
+
X, Y = [], []
|
| 28 |
+
for img_path in image_paths:
|
| 29 |
+
# Map _w2.TIF to _w3_seg.npy based on the provided screenshot
|
| 30 |
+
mask_path = img_path.replace("_w2.TIF", "_w3_seg.npy")
|
| 31 |
+
|
| 32 |
+
if os.path.exists(mask_path):
|
| 33 |
+
img = tifffile.imread(img_path)
|
| 34 |
+
mask = np.load(mask_path, allow_pickle=True)
|
| 35 |
+
|
| 36 |
+
if mask.ndim == 0 and isinstance(mask.item(), dict):
|
| 37 |
+
mask = mask.item().get('masks', mask.item())
|
| 38 |
+
|
| 39 |
+
img = np.squeeze(img)
|
| 40 |
+
mask = np.squeeze(mask)
|
| 41 |
+
|
| 42 |
+
mask = fill_label_holes(mask.astype(np.int32))
|
| 43 |
+
X.append(img)
|
| 44 |
+
Y.append(mask)
|
| 45 |
+
|
| 46 |
+
print(f"Loaded {len(X)} valid 2D image-mask pairs.")
|
| 47 |
+
|
| 48 |
+
if len(X) <= test_size:
|
| 49 |
+
raise ValueError("Not enough images to create a split. Reduce test_size or check the dataset.")
|
| 50 |
+
|
| 51 |
+
X_test, Y_test = X[:test_size], Y[:test_size]
|
| 52 |
+
X_train, Y_train = X[test_size:], Y[test_size:]
|
| 53 |
+
|
| 54 |
+
return X_train, Y_train, X_test, Y_test
|
| 55 |
+
|
| 56 |
+
# --- 2. Preprocessing Definitions ---
|
| 57 |
+
def process_w2(image_obj):
|
| 58 |
+
""" W2: Organelles (Red Fluorescence) -> CLAHE & Top-Hat preprocessing """
|
| 59 |
+
if image_obj.ndim == 3:
|
| 60 |
+
image_obj = image_obj[0]
|
| 61 |
+
p1, p99 = np.percentile(image_obj, (1, 99.9))
|
| 62 |
+
robust_img = exposure.rescale_intensity(image_obj, in_range=(p1, p99), out_range=(0, 255)).astype(np.uint8)
|
| 63 |
+
clahe = cv2.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))
|
| 64 |
+
clahe_img = clahe.apply(robust_img)
|
| 65 |
+
return clahe_img
|
| 66 |
+
|
| 67 |
+
def preprocess_2(img):
|
| 68 |
+
""" Standard StarDist Percentile Normalization """
|
| 69 |
+
return normalize(img, 1, 99.8, axis=(0,1))
|
| 70 |
+
|
| 71 |
+
def preprocess_none(img):
|
| 72 |
+
""" Basic Min-Max scaling to prevent float crashes on raw inputs """
|
| 73 |
+
return (img - np.min(img)) / (np.ptp(img) + 1e-8)
|
| 74 |
+
|
| 75 |
+
def apply_preprocessing(img, mode="none", to_rgb=False):
|
| 76 |
+
""" Router for preprocessing modes """
|
| 77 |
+
if mode == "prep1":
|
| 78 |
+
out = process_w2(img)
|
| 79 |
+
elif mode == "prep2":
|
| 80 |
+
out = preprocess_2(img)
|
| 81 |
+
elif mode == "prep1_then_prep2":
|
| 82 |
+
out = process_w2(img)
|
| 83 |
+
out = preprocess_2(out)
|
| 84 |
+
else:
|
| 85 |
+
out = preprocess_none(img)
|
| 86 |
+
|
| 87 |
+
out = out.astype(np.float32)
|
| 88 |
+
|
| 89 |
+
if to_rgb and out.ndim == 2:
|
| 90 |
+
out = np.stack((out,) * 3, axis=-1)
|
| 91 |
+
|
| 92 |
+
return out
|
| 93 |
+
|
| 94 |
+
# --- 3. Visualization Function ---
|
| 95 |
+
def plot_test_results(X_test, Y_test, Y_pred, X_input, experiment_name, mode_label, num_images=2):
|
| 96 |
+
"""Plots 3 columns: Original+GT, Model Input, Model Input+Pred"""
|
| 97 |
+
print(f"\nGenerating plots for: {experiment_name}")
|
| 98 |
+
lbl_cmap = random_label_cmap()
|
| 99 |
+
|
| 100 |
+
for i in range(min(num_images, len(X_test))):
|
| 101 |
+
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
|
| 102 |
+
|
| 103 |
+
# Column 1: Original Image + GT
|
| 104 |
+
axes[0].imshow(X_test[i], cmap='gray')
|
| 105 |
+
axes[0].imshow(Y_test[i], cmap=lbl_cmap, alpha=0.5)
|
| 106 |
+
axes[0].set_title(f"Image {i+1}: Original + Ground Truth")
|
| 107 |
+
axes[0].axis('off')
|
| 108 |
+
|
| 109 |
+
# Column 2: The actual input fed to the model
|
| 110 |
+
disp_img = X_input[i]
|
| 111 |
+
if disp_img.ndim == 3:
|
| 112 |
+
disp_img = disp_img[..., 0]
|
| 113 |
+
|
| 114 |
+
axes[1].imshow(disp_img, cmap='gray')
|
| 115 |
+
axes[1].set_title(f"Image {i+1}: Model Input ({mode_label})")
|
| 116 |
+
axes[1].axis('off')
|
| 117 |
+
|
| 118 |
+
# Column 3: Model Input + Prediction
|
| 119 |
+
axes[2].imshow(disp_img, cmap='gray')
|
| 120 |
+
axes[2].imshow(Y_pred[i], cmap=lbl_cmap, alpha=0.5)
|
| 121 |
+
axes[2].set_title(f"Image {i+1}: Model Input + Prediction")
|
| 122 |
+
axes[2].axis('off')
|
| 123 |
+
|
| 124 |
+
plt.tight_layout()
|
| 125 |
+
plt.show()
|
| 126 |
+
|
| 127 |
+
# --- 4. Training Function ---
|
| 128 |
+
def train_model(X_train, Y_train, model_name, prep_mode="none"):
|
| 129 |
+
print(f"\n--- Training Custom Model ONCE: {model_name} (Training Data Preprocessing: {prep_mode}) ---")
|
| 130 |
+
|
| 131 |
+
X_trn_proc = [apply_preprocessing(x, mode=prep_mode, to_rgb=False) for x in X_train]
|
| 132 |
+
|
| 133 |
+
rng = np.random.RandomState(42)
|
| 134 |
+
ind = rng.permutation(len(X_trn_proc))
|
| 135 |
+
n_val = max(1, int(round(0.15 * len(ind))))
|
| 136 |
+
ind_train, ind_val = ind[:-n_val], ind[-n_val:]
|
| 137 |
+
|
| 138 |
+
X_trn = [X_trn_proc[i] for i in ind_train]
|
| 139 |
+
Y_trn = [Y_train[i] for i in ind_train]
|
| 140 |
+
X_val = [X_trn_proc[i] for i in ind_val]
|
| 141 |
+
Y_val = [Y_train[i] for i in ind_val]
|
| 142 |
+
|
| 143 |
+
conf = Config2D(
|
| 144 |
+
n_rays=32,
|
| 145 |
+
grid=(2,2),
|
| 146 |
+
n_channel_in=1,
|
| 147 |
+
train_patch_size=(256,256),
|
| 148 |
+
train_batch_size=4,
|
| 149 |
+
)
|
| 150 |
+
model = StarDist2D(conf, name=model_name, basedir='models')
|
| 151 |
+
|
| 152 |
+
median_size = calculate_extents(list(Y_train), np.median)
|
| 153 |
+
fov = np.array(model._axes_tile_overlap('YX'))
|
| 154 |
+
if any(median_size > fov):
|
| 155 |
+
print("WARNING: Median object size is larger than the field of view.")
|
| 156 |
+
|
| 157 |
+
model.train(X_trn, Y_trn, validation_data=(X_val, Y_val), epochs=30, steps_per_epoch=50)
|
| 158 |
+
model.optimize_thresholds(X_val, Y_val)
|
| 159 |
+
|
| 160 |
+
return model
|
| 161 |
+
|
| 162 |
+
# --- 5. Evaluation Loop ---
|
| 163 |
+
def run_evaluation(model, X_test, Y_test, experiment_name, prep_mode, is_pretrained_he=False):
|
| 164 |
+
print(f"\nEvaluating: {experiment_name}")
|
| 165 |
+
metrics = []
|
| 166 |
+
|
| 167 |
+
Y_pred_list = []
|
| 168 |
+
X_input_list = []
|
| 169 |
+
|
| 170 |
+
for i, (img, gt) in enumerate(zip(X_test, Y_test)):
|
| 171 |
+
img_input = apply_preprocessing(img, mode=prep_mode, to_rgb=is_pretrained_he)
|
| 172 |
+
X_input_list.append(img_input)
|
| 173 |
+
|
| 174 |
+
pred_mask, _ = model.predict_instances(img_input, prob_thresh=0.5, nms_thresh=0.3)
|
| 175 |
+
Y_pred_list.append(pred_mask)
|
| 176 |
+
|
| 177 |
+
# IoU Threshold 0.0 for matching calculation
|
| 178 |
+
res = matching(gt, pred_mask, thresh=0.0)
|
| 179 |
+
|
| 180 |
+
metrics.append({
|
| 181 |
+
"Image": i+1,
|
| 182 |
+
"F1": res.f1,
|
| 183 |
+
"IoU": res.mean_matched_score
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
df = pd.DataFrame(metrics)
|
| 187 |
+
mean_f1 = df['F1'].mean()
|
| 188 |
+
mean_iou = df['IoU'].mean()
|
| 189 |
+
|
| 190 |
+
print(f"Results for {experiment_name}:")
|
| 191 |
+
print(f"Mean F1-Score: {mean_f1:.4f}")
|
| 192 |
+
print(f"Mean IoU: {mean_iou:.4f}\n")
|
| 193 |
+
|
| 194 |
+
plot_test_results(X_test, Y_test, Y_pred_list, X_input_list, experiment_name, prep_mode, num_images=2)
|
| 195 |
+
|
| 196 |
+
return mean_f1, mean_iou
|
| 197 |
+
|
| 198 |
+
# --- Main Execution Block ---
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
np.random.seed(42)
|
| 201 |
+
|
| 202 |
+
# 1. Load Data with updated repo
|
| 203 |
+
X_train, Y_train, X_test, Y_test = load_and_split_dataset(repo_id="champ7/celldatamag", test_size=10)
|
| 204 |
+
|
| 205 |
+
all_results = []
|
| 206 |
+
|
| 207 |
+
# 2. Preload the versatile H&E model
|
| 208 |
+
print("\nLoading pre-trained '2D_versatile_he' model...")
|
| 209 |
+
pretrained_model = StarDist2D.from_pretrained('2D_versatile_he')
|
| 210 |
+
|
| 211 |
+
# 3. Train the custom model EXACTLY ONCE (using 'none' as the baseline training preprocessing)
|
| 212 |
+
custom_trained_model = train_model(X_train, Y_train, model_name="single_custom_model", prep_mode="none")
|
| 213 |
+
|
| 214 |
+
# 4. Define all 8 experiments
|
| 215 |
+
experiments = [
|
| 216 |
+
# (Experiment Name, Preprocessing Mode, Model to Evaluate, is_pretrained_flag)
|
| 217 |
+
("Exp 1: Pretrained, No Preprocessing", "none", pretrained_model, True),
|
| 218 |
+
("Exp 2: Pretrained, Preprocessing 1", "prep1", pretrained_model, True),
|
| 219 |
+
("Exp 3: Pretrained, Preprocessing 2", "prep2", pretrained_model, True),
|
| 220 |
+
("Exp 4: Pretrained, Prep 1 -> Prep 2", "prep1_then_prep2", pretrained_model, True),
|
| 221 |
+
|
| 222 |
+
("Exp 5: Trained, No Preprocessing", "none", custom_trained_model, False),
|
| 223 |
+
("Exp 6: Trained, Preprocessing 1", "prep1", custom_trained_model, False),
|
| 224 |
+
("Exp 7: Trained, Preprocessing 2", "prep2", custom_trained_model, False),
|
| 225 |
+
("Exp 8: Trained, Prep 1 -> Prep 2", "prep1_then_prep2", custom_trained_model, False),
|
| 226 |
+
]
|
| 227 |
+
|
| 228 |
+
# 5. Run through all inference/evaluation states
|
| 229 |
+
for exp_name, prep_mode, model_to_eval, is_pretrained in experiments:
|
| 230 |
+
f1, iou = run_evaluation(model_to_eval, X_test, Y_test, exp_name, prep_mode, is_pretrained_he=is_pretrained)
|
| 231 |
+
all_results.append({
|
| 232 |
+
"Experiment": exp_name,
|
| 233 |
+
"Mean F1-Score": round(f1, 4),
|
| 234 |
+
"Mean IoU": round(iou, 4)
|
| 235 |
+
})
|
| 236 |
+
|
| 237 |
+
# --- 6. Final Summary Table ---
|
| 238 |
+
print("\n" + "="*70)
|
| 239 |
+
print("FINAL METRICS SUMMARY (IoU Threshold = 0.0)".center(70))
|
| 240 |
+
print("="*70)
|
| 241 |
+
|
| 242 |
+
results_df = pd.DataFrame(all_results)
|
| 243 |
+
print(results_df.to_string(index=False, justify='left'))
|
| 244 |
+
print("="*70)
|