champ7 commited on
Commit
ab0d63b
·
verified ·
1 Parent(s): f680f54

Create nellie3.py

Browse files
Files changed (1) hide show
  1. nellie3.py +302 -0
nellie3.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import logging
4
+ import random
5
+ import cv2
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import tifffile as tiff
9
+ from scipy.sparse import csr_matrix
10
+ from tabulate import tabulate
11
+ from tqdm import tqdm
12
+ from huggingface_hub import snapshot_download
13
+
14
+ from nellie.im_info.verifier import FileInfo, ImInfo
15
+ from nellie.segmentation.filtering import Filter
16
+ from nellie.segmentation.labelling import Label
17
+ from skimage.filters import rank, sobel
18
+ from skimage import exposure
19
+ from skimage.morphology import disk, binary_dilation
20
+ from skimage.segmentation import find_boundaries
21
+ from skimage.util import img_as_ubyte
22
+
23
+ # Logging setup
24
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s", datefmt="%H:%M:%S")
25
+ logger = logging.getLogger(__name__)
26
+
27
+ # =====================================================================
28
+ # Preprocessing Logic
29
+ # =====================================================================
30
+ def preprocess_method_1(image_obj: np.ndarray) -> np.ndarray:
31
+ """ W1: CLAHE preprocessing """
32
+ if image_obj.ndim == 3:
33
+ image_obj = image_obj[0]
34
+ p1, p99 = np.percentile(image_obj, (1, 99.9))
35
+ robust_img = exposure.rescale_intensity(image_obj, in_range=(p1, p99), out_range=(0, 255)).astype(np.uint8)
36
+ clahe = cv2.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))
37
+ clahe_img = clahe.apply(robust_img)
38
+ return clahe_img
39
+
40
+ def preprocess_method_2(img_input: np.ndarray) -> np.ndarray:
41
+ img_min, img_max = img_input.min(), img_input.max()
42
+ img_normalized = (img_input - img_min) / (img_max - img_min if img_max > img_min else 1.0)
43
+ img_8bit = img_as_ubyte(img_normalized)
44
+ nellie_input = rank.entropy(img_8bit, disk(25))
45
+ edge_map = sobel(img_normalized)
46
+ texture_features = nellie_input * (1.0 + edge_map * 5.0)
47
+ tex_min, tex_max = texture_features.min(), texture_features.max()
48
+ tex_normalized = (texture_features - tex_min) / (tex_max - tex_min if tex_max > tex_min else 1.0)
49
+ return (tex_normalized * 255).astype(np.uint8)
50
+
51
+ def preprocess_combined(img_raw: np.ndarray) -> np.ndarray:
52
+ return preprocess_method_2(preprocess_method_1(img_raw))
53
+
54
+ # =====================================================================
55
+ # Vectorized Metric Evaluation
56
+ # =====================================================================
57
+ def evaluate_predictions(pred_mask: np.ndarray, gt_mask: np.ndarray, iou_threshold: float = 0.5):
58
+ """Vectorized instance-level matching using strict IoU >= 0.5"""
59
+ pred_mask, gt_mask = pred_mask.astype(np.int32), gt_mask.astype(np.int32)
60
+ pred_labels = np.unique(pred_mask)[np.unique(pred_mask) != 0]
61
+ gt_labels = np.unique(gt_mask)[np.unique(gt_mask) != 0]
62
+ num_pred, num_gt = len(pred_labels), len(gt_labels)
63
+
64
+ pred_bg, gt_bg = pred_mask > 0, gt_mask > 0
65
+ union_pixel = np.logical_or(pred_bg, gt_bg).sum()
66
+ global_pixel_iou = np.logical_and(pred_bg, gt_bg).sum() / union_pixel if union_pixel > 0 else 0.0
67
+
68
+ if num_gt == 0 and num_pred == 0: return global_pixel_iou, 1.0, 1.0, 1.0, num_pred, num_gt
69
+ if num_gt == 0 or num_pred == 0: return global_pixel_iou, 0.0, 0.0, 0.0, num_pred, num_gt
70
+
71
+ overlapping = gt_bg & pred_bg
72
+ if not np.any(overlapping): return global_pixel_iou, 0.0, 0.0, 0.0, num_pred, num_gt
73
+
74
+ gt_id_map = {id_: i for i, id_ in enumerate(gt_labels)}
75
+ pred_id_map = {id_: j for j, id_ in enumerate(pred_labels)}
76
+
77
+ gt_indices = np.array([gt_id_map[x] for x in gt_mask[overlapping]])
78
+ pred_indices = np.array([pred_id_map[x] for x in pred_mask[overlapping]])
79
+ intersection = csr_matrix((np.ones(len(gt_indices), dtype=np.int32), (gt_indices, pred_indices)), shape=(num_gt, num_pred)).toarray()
80
+
81
+ gt_vec = np.array([np.bincount(gt_mask.ravel())[id_] for id_ in gt_labels])[:, None]
82
+ pred_vec = np.array([np.bincount(pred_mask.ravel())[id_] for id_ in pred_labels])[None, :]
83
+
84
+ union = gt_vec + pred_vec - intersection
85
+ iou_matrix = np.divide(intersection, union, out=np.zeros_like(intersection, dtype=float), where=union != 0)
86
+
87
+ matches = iou_matrix > iou_threshold
88
+ tp = np.sum(np.any(matches, axis=0))
89
+
90
+ precision = tp / num_pred if num_pred > 0 else 0.0
91
+ recall = tp / num_gt if num_gt > 0 else 0.0
92
+ instance_f1 = (2 * precision * recall) / (precision + recall) if (precision + recall) > 0 else 0.0
93
+
94
+ return global_pixel_iou, precision, recall, instance_f1, num_pred, num_gt
95
+
96
+ # =====================================================================
97
+ # Dataset Prep & Core Pipeline
98
+ # =====================================================================
99
+ def prepare_datasets(raw_tif_files, base_dir="generated_datasets"):
100
+ dirs = {
101
+ "Raw": os.path.join(base_dir, "dataset_raw"),
102
+ "Prep 1": os.path.join(base_dir, "dataset_prep1"),
103
+ "Prep 2": os.path.join(base_dir, "dataset_prep2"),
104
+ "Prep 1->2": os.path.join(base_dir, "dataset_prep1_2")
105
+ }
106
+ for d in dirs.values(): os.makedirs(d, exist_ok=True)
107
+
108
+ for filepath in tqdm(raw_tif_files, desc="Building Datasets"):
109
+ fname = os.path.basename(filepath)
110
+ if os.path.exists(os.path.join(dirs["Prep 1->2"], fname)):
111
+ continue
112
+
113
+ img_raw = np.squeeze(tiff.imread(filepath))
114
+ tiff.imwrite(os.path.join(dirs["Raw"], fname), img_raw)
115
+ tiff.imwrite(os.path.join(dirs["Prep 1"], fname), preprocess_method_1(img_raw))
116
+ tiff.imwrite(os.path.join(dirs["Prep 2"], fname), preprocess_method_2(img_raw))
117
+ tiff.imwrite(os.path.join(dirs["Prep 1->2"], fname), preprocess_combined(img_raw))
118
+
119
+ return dirs
120
+
121
+ def run_nellie_experiment(dataset_dir, combined_data_path, run_native_filter, target_filenames):
122
+ files = [os.path.join(dataset_dir, fname) for fname in target_filenames]
123
+ results, saved_masks = [], {}
124
+
125
+ for filepath in tqdm(files, desc=f"Evaluating", leave=False):
126
+ if not os.path.exists(filepath): continue
127
+ filename = os.path.basename(filepath)
128
+
129
+ # CHANGED: Replaced _w1.TIF with _w3_seg.npy
130
+ gt_mask_path = os.path.join(combined_data_path, filename.replace("_w1.TIF", "_w3_seg.npy"))
131
+ if not os.path.exists(gt_mask_path): continue
132
+
133
+ f_info = FileInfo(filepath=filepath)
134
+ f_info.find_metadata()
135
+ f_info.load_metadata()
136
+
137
+ img_array = np.squeeze(tiff.imread(filepath))
138
+ f_info.axes = "ZYX" if img_array.ndim == 3 else "YX"
139
+ f_info.good_axes, f_info.good_dims = True, True
140
+ im_info = ImInfo(file_info=f_info)
141
+
142
+ if run_native_filter:
143
+ frangi_filter = Filter(im_info=im_info, device="auto")
144
+ frangi_filter.run()
145
+ else:
146
+ prep_path = im_info.create_output_path(pipeline_path="im_preprocessed", ext=".ome.tif")
147
+ im_info.allocate_memory(output_path=prep_path, data=img_array, dtype=str(img_array.dtype))
148
+
149
+ label_processor = Label(im_info=im_info, otsu_thresh_intensity=False, min_radius_um=10.0, device="auto")
150
+ label_processor.run()
151
+ pred_mask = np.squeeze(tiff.imread(im_info.pipeline_paths["im_instance_label"]))
152
+
153
+ gt_data = np.load(gt_mask_path, allow_pickle=True)
154
+ if gt_data.ndim == 0 and isinstance(gt_data.item(), dict):
155
+ gt_data = gt_data.item().get("masks", gt_data.item())
156
+ gt_to_compare = np.squeeze(gt_data)
157
+
158
+ metrics = evaluate_predictions(pred_mask, gt_to_compare, iou_threshold=0.5)
159
+ results.append(metrics)
160
+ saved_masks[filename] = (pred_mask, metrics[4])
161
+
162
+ return results, saved_masks
163
+
164
+ # =====================================================================
165
+ # Plot Single Experiment
166
+ # =====================================================================
167
+ def plot_single_experiment_visual(sample_filename, combined_data_path, data_src_dir, raw_data_dir, config_name, pred_mask, pred_count):
168
+ logger.info(f"Generating visual plot for: {config_name}")
169
+
170
+ # --- Load Data ---
171
+ # CHANGED: Replaced _w1.TIF with _w3_seg.npy
172
+ gt_data = np.load(os.path.join(combined_data_path, sample_filename.replace("_w1.TIF", "_w3_seg.npy")), allow_pickle=True)
173
+ if gt_data.ndim == 0 and isinstance(gt_data.item(), dict):
174
+ gt_data = gt_data.item().get("masks", gt_data.item())
175
+ gt_mask = np.squeeze(gt_data)
176
+ gt_count = len(np.unique(gt_mask)[np.unique(gt_mask) != 0])
177
+
178
+ feed_img = tiff.imread(os.path.join(data_src_dir, sample_filename))
179
+ raw_img = tiff.imread(os.path.join(raw_data_dir, sample_filename))
180
+
181
+ # --- Ground Truth High-Def Assets ---
182
+ gt_binary = gt_mask > 0
183
+ gt_boundaries = find_boundaries(gt_binary, mode="outer")
184
+ gt_thick_boundaries = binary_dilation(gt_boundaries, disk(1))
185
+ gt_masked_fill = np.ma.masked_where(~gt_binary, gt_binary)
186
+ gt_masked_edges = np.ma.masked_where(~gt_thick_boundaries, gt_thick_boundaries)
187
+
188
+ # --- Prediction High-Def Assets ---
189
+ pred_binary = pred_mask > 0
190
+ pred_boundaries = find_boundaries(pred_binary, mode="outer")
191
+ pred_thick_boundaries = binary_dilation(pred_boundaries, disk(1))
192
+ pred_masked_fill = np.ma.masked_where(~pred_binary, pred_binary)
193
+ pred_masked_edges = np.ma.masked_where(~pred_thick_boundaries, pred_thick_boundaries)
194
+
195
+ cmap_choice = "gray" if "Prep 1" in data_src_dir or "Raw" in data_src_dir else "magma"
196
+ fig, axes = plt.subplots(1, 3, figsize=(18, 6))
197
+
198
+ # 1. Ground Truth Overlay (on Raw Image)
199
+ axes[0].imshow(raw_img, cmap="gray")
200
+ axes[0].imshow(gt_masked_fill, cmap="summer", alpha=0.25)
201
+ axes[0].imshow(gt_masked_edges, cmap="Greens", alpha=0.9)
202
+ axes[0].set_title(f"GT Overlay on Raw (Count: {gt_count})", fontsize=12, fontweight="bold")
203
+ axes[0].axis("off")
204
+
205
+ # 2. Input Image Alone (The preprocessed image actually fed to Nellie)
206
+ axes[1].imshow(feed_img, cmap=cmap_choice)
207
+ axes[1].set_title(f"Data Fed into Nellie", fontsize=12, fontweight="bold")
208
+ axes[1].axis("off")
209
+
210
+ # 3. Predicted Mask Overlay (on Raw Image)
211
+ axes[2].imshow(raw_img, cmap="gray")
212
+ axes[2].imshow(pred_masked_fill, cmap="autumn", alpha=0.25)
213
+ axes[2].imshow(pred_masked_edges, cmap="Wistia", alpha=0.9)
214
+ axes[2].set_title(f"Predicted Mask on Raw (Count: {pred_count})", fontsize=12, fontweight="bold")
215
+ axes[2].axis("off")
216
+
217
+ plt.suptitle(f"EXPERIMENT: {config_name}\nFile: {sample_filename}", fontsize=16, fontweight="bold")
218
+ plt.tight_layout()
219
+ plt.show()
220
+
221
+ # =====================================================================
222
+ # Main Execution Flow
223
+ # =====================================================================
224
+ def main():
225
+ n_samples = 10 # Evaluate 10 images
226
+
227
+ logger.info("Downloading dataset...")
228
+ # CHANGED: Updated repository ID to celldataW1
229
+ dataset_dir = snapshot_download(repo_id="champ7/celldataW1", repo_type="dataset", allow_patterns="combined_data/*")
230
+ combined_data_path = os.path.join(dataset_dir, "combined_data")
231
+
232
+ # Extract complete list and sample N files
233
+ raw_tif_files = sorted(glob.glob(os.path.join(combined_data_path, "*.TIF")))
234
+ if n_samples and n_samples < len(raw_tif_files):
235
+ random.seed(42) # Ensure the same random subset is used across runs
236
+ raw_tif_files = random.sample(raw_tif_files, n_samples)
237
+ logger.info(f"Subsampled dataset to {n_samples} random images.")
238
+
239
+ target_filenames = [os.path.basename(f) for f in raw_tif_files]
240
+ sample_filename = target_filenames[0]
241
+ dirs = prepare_datasets(raw_tif_files)
242
+
243
+ configs = [
244
+ {"name": "Prep 1 Only (Bypassing Nellie Filter)", "data_src": "Prep 1", "run_filter": False},
245
+ {"name": "Prep 2 Only (Bypassing Nellie Filter)", "data_src": "Prep 2", "run_filter": False},
246
+ {"name": "Prep 1->2 Only (Bypassing Nellie Filter)", "data_src": "Prep 1->2", "run_filter": False},
247
+ {"name": "Nellie Native Only (Raw -> Nellie Filter)", "data_src": "Raw", "run_filter": True},
248
+ {"name": "Prep 1 + Nellie Native Filter", "data_src": "Prep 1", "run_filter": True},
249
+ {"name": "Prep 2 + Nellie Native Filter", "data_src": "Prep 2", "run_filter": True},
250
+ {"name": "Prep 1->2 + Nellie Native Filter", "data_src": "Prep 1->2", "run_filter": True},
251
+ ]
252
+
253
+ aggregate_table = []
254
+ headers = ["Strategy Configuration", "Total GT Cells", "Total Pred Cells", "Mean Pixel IoU", "Mean Precision", "Mean Recall", "Mean F1"]
255
+
256
+ for config in configs:
257
+ logger.info(f"Running strategy: {config['name']}")
258
+
259
+ metrics, saved_masks = run_nellie_experiment(
260
+ dataset_dir=dirs[config["data_src"]],
261
+ combined_data_path=combined_data_path,
262
+ run_native_filter=config["run_filter"],
263
+ target_filenames=target_filenames
264
+ )
265
+
266
+ ious, precs, recs, f1s = [m[0] for m in metrics], [m[1] for m in metrics], [m[2] for m in metrics], [m[3] for m in metrics]
267
+ total_pred, total_gt = sum([m[4] for m in metrics]), sum([m[5] for m in metrics])
268
+
269
+ current_result_row = [
270
+ config["name"],
271
+ total_gt, total_pred,
272
+ f"{np.mean(ious):.4f}", f"{np.mean(precs):.4f}", f"{np.mean(recs):.4f}", f"{np.mean(f1s):.4f}"
273
+ ]
274
+ aggregate_table.append(current_result_row)
275
+
276
+ # Immediate output for this run
277
+ print(f"\n" + "="*80)
278
+ print(f" EXPERIMENT RESULTS: {config['name']}")
279
+ print(f"="*80)
280
+ print(tabulate([current_result_row], headers=headers, tablefmt="fancy_grid"))
281
+ print("\n")
282
+
283
+ # Visual Plot
284
+ pred_mask_sample, pred_count_sample = saved_masks[sample_filename]
285
+ plot_single_experiment_visual(
286
+ sample_filename=sample_filename,
287
+ combined_data_path=combined_data_path,
288
+ data_src_dir=dirs[config["data_src"]],
289
+ raw_data_dir=dirs["Raw"],
290
+ config_name=config["name"],
291
+ pred_mask=pred_mask_sample,
292
+ pred_count=pred_count_sample
293
+ )
294
+
295
+ # Final Summary Table
296
+ print("\n" + "=" * 115)
297
+ print(" " * 35 + f"FINAL 7-WAY EVALUATION REPORT (N={len(target_filenames)} images)")
298
+ print("=" * 115)
299
+ print(tabulate(aggregate_table, headers=headers, tablefmt="fancy_grid"))
300
+
301
+ if __name__ == "__main__":
302
+ main()