|
| 1 | +import os |
| 2 | +from glob import glob |
| 3 | + |
| 4 | +import h5py |
| 5 | +import imageio.v3 as imageio |
| 6 | +import napari |
| 7 | +import numpy as np |
| 8 | + |
| 9 | +from skimage.measure import label |
| 10 | +# from skimage.morphology import remove_small_holes |
| 11 | +from tqdm import tqdm |
| 12 | + |
| 13 | + |
| 14 | +def process_labels(labels): |
| 15 | + labels = label(labels) |
| 16 | + |
| 17 | + min_size = 75 |
| 18 | + ids, sizes = np.unique(labels, return_counts=True) |
| 19 | + filter_ids = ids[sizes < min_size] |
| 20 | + labels[np.isin(labels, filter_ids)] = 0 |
| 21 | + |
| 22 | + # labels = remove_small_holes(labels, area_threshold=min_size) |
| 23 | + return labels |
| 24 | + |
| 25 | + |
| 26 | +def postprocess_annotation(im_path, ann_path, output_folder, view=False): |
| 27 | + fname = os.path.basename(im_path) |
| 28 | + |
| 29 | + out_path = os.path.join(output_folder, fname.replace(".tif", ".h5")) |
| 30 | + if os.path.exists(out_path): |
| 31 | + return |
| 32 | + |
| 33 | + labels = imageio.imread(ann_path) |
| 34 | + |
| 35 | + # Skip empty labels. |
| 36 | + if labels.max() == 0: |
| 37 | + print("Skipping", im_path) |
| 38 | + return |
| 39 | + |
| 40 | + image = imageio.imread(im_path) |
| 41 | + labels = process_labels(labels) |
| 42 | + |
| 43 | + if view: |
| 44 | + v = napari.Viewer() |
| 45 | + v.add_image(image) |
| 46 | + v.add_labels(labels) |
| 47 | + napari.run() |
| 48 | + return |
| 49 | + |
| 50 | + with h5py.File(out_path, "a") as f: |
| 51 | + f.create_dataset("data", data=image, compression="gzip") |
| 52 | + f.create_dataset("labels/compartments", data=labels, compression="gzip") |
| 53 | + |
| 54 | + |
| 55 | +def postprocess_annotations(view): |
| 56 | + images = sorted(glob("output/images/*.tif")) |
| 57 | + annotations = sorted(glob("output/annotations/*.tif")) |
| 58 | + |
| 59 | + output_folder = "output/postprocessed_annotations" |
| 60 | + os.makedirs(output_folder, exist_ok=True) |
| 61 | + for im, ann in tqdm(zip(images, annotations), total=len(images)): |
| 62 | + postprocess_annotation(im, ann, output_folder, view=view) |
| 63 | + |
| 64 | + |
| 65 | +def main(): |
| 66 | + postprocess_annotations(view=False) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + main() |
0 commit comments