|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +from glob import glob |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import h5py |
| 7 | +import mrcfile |
| 8 | +import cryovesnet |
| 9 | + |
| 10 | + |
| 11 | +# additional parameters? |
| 12 | +def _segment_vesicles(directory): |
| 13 | + pl = cryovesnet.Pipeline(directory, pattern="*.mrc") |
| 14 | + pl.setup_cryovesnet_dir(make_masks=False) |
| 15 | + |
| 16 | + pl.run_deep() |
| 17 | + pl.label_vesicles(within_segmentation_region=False) |
| 18 | + pl.label_vesicles_adaptive(separating=True) |
| 19 | + pl.make_spheres() |
| 20 | + pl.repair_spheres() |
| 21 | + |
| 22 | + |
| 23 | +def _prepare_input(path, output_folder, input_key, resolution): |
| 24 | + out_path = os.path.join(output_folder, f"{Path(path).stem}.mrc") |
| 25 | + |
| 26 | + if path.endswith(".h5"): |
| 27 | + assert resolution is not None |
| 28 | + with h5py.File(path, "r") as f: |
| 29 | + vol = f[input_key][:] |
| 30 | + |
| 31 | + mrcfile.new(out_path, data=vol) |
| 32 | + with mrcfile.open(out_path, mode="r+") as f: |
| 33 | + f.header.cella.x = resolution[0] |
| 34 | + f.header.cella.y = resolution[1] |
| 35 | + f.header.cella.z = resolution[2] |
| 36 | + |
| 37 | + # TODO just copy the file |
| 38 | + elif path.endswith(".mrc"): |
| 39 | + pass |
| 40 | + |
| 41 | + |
| 42 | +# TODO support nested |
| 43 | +def apply_cryo_vesnet( |
| 44 | + input_folder, output_folder, pattern, input_key, |
| 45 | + resolution=None, output_key="prediction/vesicles/cryovesnet" |
| 46 | +): |
| 47 | + files = sorted(glob(os.path.join(input_folder, pattern))) |
| 48 | + with tempfile.TemporaryDirectory() as tmp: |
| 49 | + |
| 50 | + # Prepare the input files by copying them over or resaving them (if h5). |
| 51 | + for file in files: |
| 52 | + if resolution is None: |
| 53 | + res = None |
| 54 | + else: |
| 55 | + fname = Path(file).stem |
| 56 | + res = resolution[fname] if isinstance(resolution, dict) else resolution |
| 57 | + _prepare_input(file, tmp, input_key, res) |
| 58 | + |
| 59 | + # Segment the vesicles in all files. |
| 60 | + _segment_vesicles(tmp) |
| 61 | + breakpoint() |
| 62 | + |
| 63 | + # TODO |
| 64 | + # Re-save the segmentations to the output folder. |
0 commit comments