|
| 1 | +""" |
| 2 | +Update OME-Zarr Version |
| 3 | +======================= |
| 4 | +
|
| 5 | +This script shows how to write the same OME-Zarr image |
| 6 | +using a new version. |
| 7 | +""" |
| 8 | + |
| 9 | +# %% |
| 10 | +from pathlib import Path |
| 11 | +from tempfile import TemporaryDirectory |
| 12 | + |
| 13 | +import numpy as np |
| 14 | + |
| 15 | +from iohub.ngff import TransformationMeta, open_ome_zarr |
| 16 | + |
| 17 | +# %% |
| 18 | +# Set storage path |
| 19 | +tmp_dir = TemporaryDirectory() |
| 20 | +old_store_path = Path(tmp_dir.name) / "old.zarr" |
| 21 | +new_store_path = Path(tmp_dir.name) / "new.zarr" |
| 22 | + |
| 23 | +# %% |
| 24 | +# Create a version 0.4 OME-Zarr dataset |
| 25 | +random_image = np.random.randint( |
| 26 | + 0, np.iinfo(np.uint16).max, size=(10, 2, 32, 128, 128), dtype=np.uint16 |
| 27 | +) |
| 28 | +scale = [2.0, 3.0, 4.0, 5.0, 6.0] |
| 29 | + |
| 30 | + |
| 31 | +with open_ome_zarr( |
| 32 | + old_store_path, |
| 33 | + layout="hcs", |
| 34 | + mode="w-", |
| 35 | + channel_names=["DAPI", "GFP"], |
| 36 | + version="0.4", |
| 37 | +) as old_dataset: |
| 38 | + position = old_dataset.create_position("A", "1", "0") |
| 39 | + image = position.create_image( |
| 40 | + "0", |
| 41 | + random_image, |
| 42 | + chunks=(1, 1, 4, 32, 32), |
| 43 | + transform=[TransformationMeta(type="scale", scale=scale)], |
| 44 | + ) |
| 45 | + |
| 46 | +# %% |
| 47 | +# Write the same image with version 0.5 and sharding |
| 48 | + |
| 49 | +with open_ome_zarr(old_store_path, mode="r", layout="hcs") as old_dataset: |
| 50 | + with open_ome_zarr( |
| 51 | + new_store_path, |
| 52 | + layout="hcs", |
| 53 | + mode="w", |
| 54 | + channel_names=old_dataset.channel_names, |
| 55 | + version="0.5", |
| 56 | + ) as new_dataset: |
| 57 | + for name, old_position in old_dataset.positions(): |
| 58 | + row, col, fov = name.split("/") |
| 59 | + new_position = new_dataset.create_position(row, col, fov) |
| 60 | + old_image = old_position["0"] |
| 61 | + new_image = new_position.create_image( |
| 62 | + "0", |
| 63 | + data=old_image.numpy(), |
| 64 | + chunks=(1, 1, 4, 32, 32), |
| 65 | + shards_ratio=(2, 1, 8, 4, 4), |
| 66 | + transform=old_position.metadata.multiscales[0] |
| 67 | + .datasets[0] |
| 68 | + .coordinate_transformations, |
| 69 | + ) |
| 70 | + |
| 71 | +# %% |
| 72 | +# Read the new FOV to verify it was written correctly |
| 73 | +with open_ome_zarr(new_store_path / "A/1/0", mode="r") as dataset: |
| 74 | + assert dataset.scale == scale |
| 75 | + image = dataset["0"] |
| 76 | + assert image.shards == (2, 1, 32, 128, 128) |
| 77 | + assert np.array_equal(image.numpy(), random_image) |
| 78 | + |
| 79 | +# %% |
| 80 | +# Clean up |
| 81 | +tmp_dir.cleanup() |
0 commit comments