|
| 1 | +import os |
| 2 | +from glob import glob |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import h5py |
| 6 | +import numpy as np |
| 7 | +import zarr |
| 8 | + |
| 9 | +from synapse_net.file_utils import read_mrc |
| 10 | +from tqdm import tqdm |
| 11 | + |
| 12 | +from ome_zarr.writer import write_image |
| 13 | +from ome_zarr.io import parse_url |
| 14 | + |
| 15 | + |
| 16 | +IN_ROOT = "/scratch-grete/projects/nim00007/cryo-et/from_portal/for_eval" |
| 17 | +OUT_ROOT = "/scratch-grete/projects/nim00007/cryo-et/from_portal/segmentations/DA_with_new_portalData_origDim" # noqa |
| 18 | + |
| 19 | +IN_ROOT = "/scratch-grete/projects/nim00007/cryo-et/from_portal/for_domain_adaptation" |
| 20 | +OUT_ROOT = "/scratch-grete/projects/nim00007/cryo-et/from_portal/segmentations/DA_with_new_portalData_forDAdata" |
| 21 | + |
| 22 | + |
| 23 | +def export_to_ome_zarr(export_file, seg, voxel_size): |
| 24 | + store = parse_url(export_file, mode="w").store |
| 25 | + root = zarr.group(store=store) |
| 26 | + |
| 27 | + scale = list(voxel_size.values()) |
| 28 | + trafo = [ |
| 29 | + [{"scale": scale, "type": "scale"}] |
| 30 | + ] |
| 31 | + write_image(seg, root, axes="zyx", coordinate_transformations=trafo, scaler=None) |
| 32 | + |
| 33 | + |
| 34 | +def export_segmentation(export_folder, segmentation_file): |
| 35 | + fname = Path(segmentation_file).stem |
| 36 | + key = "/vesicles/segment_from_vesicle_DA_portal_v3" |
| 37 | + export_file = os.path.join(export_folder, f"{fname}.ome.zarr") |
| 38 | + |
| 39 | + if os.path.exists(export_file): |
| 40 | + return |
| 41 | + |
| 42 | + input_file = os.path.join(IN_ROOT, f"{fname}.mrc") |
| 43 | + raw, voxel_size = read_mrc(input_file) |
| 44 | + voxel_size = {k: v * 10 for k, v in voxel_size.items()} |
| 45 | + |
| 46 | + try: |
| 47 | + with h5py.File(segmentation_file, "r") as f: |
| 48 | + seg = f[key][:] |
| 49 | + except OSError as e: |
| 50 | + print(e) |
| 51 | + return |
| 52 | + |
| 53 | + seg = np.flip(seg, axis=1) |
| 54 | + assert seg.shape == raw.shape |
| 55 | + |
| 56 | + assert seg.max() < 128, f"{seg.max()}" |
| 57 | + seg = seg.astype("int8") |
| 58 | + export_to_ome_zarr(export_file, seg, voxel_size) |
| 59 | + |
| 60 | + |
| 61 | +def main(): |
| 62 | + export_folder = "./for_portal2" |
| 63 | + os.makedirs(export_folder, exist_ok=True) |
| 64 | + files = glob(os.path.join(OUT_ROOT, "*.h5")) |
| 65 | + for file in tqdm(files): |
| 66 | + export_segmentation(export_folder, file) |
| 67 | + |
| 68 | + |
| 69 | +main() |
0 commit comments