champ7 commited on
Commit
efd4d7b
·
verified ·
1 Parent(s): 23c10f2

Create nelliew1.py

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