"""Convert the canonical 2D demo images to OME-Zarr 0.5 (Zarr v3). Layout: axes c, y, x; 512 px chunks inside 4096 px shards (few files per store, read by HTTP Range); gzip (browser DecompressionStream, no WASM), after a byte shuffle for multi-byte dtypes (bench: matches blosc-zstd size within 1%); a 2x mean pyramid down to <= 512 px. Each store carries an omero block (labels, colours, windows, active channels) and an `attribution` attribute. Usage: convert.py [ ...] (see SOURCES); writes out/.ome.zarr """ import json import shutil import subprocess import sys from pathlib import Path import numpy as np import zarr from numcodecs.zarr3 import Shuffle from zarr.codecs import GzipCodec ROOT = Path('/Volumes/TB5/ZARR') SRC, OUT = ROOT / 'src', ROOT / 'out' CHUNK, SHARD = 512, 4096 def downsample(a: np.ndarray) -> np.ndarray: """2x2 mean of a (c, y, x) array; odd edges repeat their last row/column.""" c, y, x = a.shape if y % 2 or x % 2: a = np.pad(a, ((0, 0), (0, y % 2), (0, x % 2)), mode='edge') out = np.empty((c, a.shape[1] // 2, a.shape[2] // 2), a.dtype) for i in range(c): # per channel keeps the float temporary small f = a[i].astype(np.float32) m = (f[0::2, 0::2] + f[1::2, 0::2] + f[0::2, 1::2] + f[1::2, 1::2]) * 0.25 out[i] = np.rint(m) if np.issubdtype(a.dtype, np.integer) else m return out def window(a: np.ndarray, lo=0.5, hi=99.8) -> tuple[float, float]: """Display window from percentiles of a strided sample (fast on big planes).""" step = max(1, int(np.sqrt(a.size / 4e6))) s = a[::step, ::step] s = s[s > 0] if (s > 0).mean() > 0.05 else s.ravel() # ignore empty background return float(np.percentile(s, lo)), float(np.percentile(s, hi)) def write(name, data, channels, *, scale=(1.0, 1.0), unit=None, attribution): """data: (c, y, x); channels: [{label, color, window:(start,end), active}].""" path = OUT / f'{name}.ome.zarr' if path.exists(): shutil.rmtree(path) store = zarr.storage.LocalStore(path) root = zarr.create_group(store, zarr_format=3) levels, a, s = [], data, list(scale) while True: levels.append((a, list(s))) if max(a.shape[1:]) <= CHUNK: break a, s = downsample(a), [s[0] * 2, s[1] * 2] gzip = GzipCodec(level=6) codecs = [Shuffle(elementsize=data.dtype.itemsize), gzip] if data.dtype.itemsize > 1 else [gzip] for i, (lev, _) in enumerate(levels): c, y, x = lev.shape cy, cx = min(CHUNK, y), min(CHUNK, x) # A shard is a whole number of chunks and no bigger than the level needs. sy = min(SHARD, -(-y // cy) * cy) sx = min(SHARD, -(-x // cx) * cx) arr = root.create_array( str(i), shape=lev.shape, dtype=lev.dtype, chunks=(1, cy, cx), shards=(1, sy, sx), compressors=codecs, fill_value=0, dimension_names=['c', 'y', 'x']) arr[:] = lev space = {'type': 'space', **({'unit': unit} if unit else {})} is_int = np.issubdtype(data.dtype, np.integer) info = np.iinfo(data.dtype) if is_int else None root.attrs['ome'] = { 'version': '0.5', 'multiscales': [{ 'name': name, 'axes': [{'name': 'c', 'type': 'channel'}, {'name': 'y', **space}, {'name': 'x', **space}], 'datasets': [{'path': str(i), 'coordinateTransformations': [ {'type': 'scale', 'scale': [1.0, *sc]}]} for i, (_, sc) in enumerate(levels)], }], 'omero': { 'name': name, 'rdefs': {'model': 'color'}, 'channels': [{ 'label': ch['label'], 'color': ch['color'], 'active': ch.get('active', True), 'window': {'start': ch['window'][0], 'end': ch['window'][1], 'min': float(info.min) if info else ch['window'][0], 'max': float(info.max) if info else ch['window'][1]}, } for ch in channels], }, } root.attrs['attribution'] = attribution mb = sum(f.stat().st_size for f in path.rglob('*') if f.is_file()) / 1e6 nfiles = sum(1 for f in path.rglob('*') if f.is_file()) print(f'{name}: {data.shape} {data.dtype}, {len(levels)} levels, {nfiles} files, {mb:.1f} MB') return mb def rgb_channels(a): return [{'label': lab, 'color': col, 'window': (0, 255)} for lab, col in (('red', 'FF0000'), ('green', '00FF00'), ('blue', '0000FF'))] def read_tif(path) -> np.ndarray: import tifffile a = tifffile.imread(path) return np.moveaxis(a, -1, 0) if a.ndim == 3 and a.shape[-1] in (3, 4) else a[None] def gdal_resize(src, dst, w, h): subprocess.run(['gdal_translate', '-q', '-outsize', str(w), str(h), '-r', 'cubic', '-co', 'COMPRESS=NONE', str(src), str(dst)], check=True) def ngff_level(store: Path, level: int): """(array (c, y, x), scale (y, x), omero, multiscale) from a v2/v3 OME-Zarr image group.""" g = zarr.open_group(store, mode='r') attrs = dict(g.attrs) attrs = attrs.get('ome', attrs) ms = attrs['multiscales'][0] axes = [ax if isinstance(ax, str) else ax['name'] for ax in ms['axes']] ds = ms['datasets'][level] a = g[ds['path']][...] idx = tuple(slice(None) if ax in ('c', 'y', 'x') else 0 for ax in axes) a = a[idx] kept = [ax for ax in axes if ax in ('c', 'y', 'x')] if 'c' not in kept: a, kept = a[None], ['c', *kept] a = np.transpose(a, [kept.index(k) for k in ('c', 'y', 'x')]) sc = next(t['scale'] for t in ds['coordinateTransformations'] if t['type'] == 'scale') scale = (float(sc[axes.index('y')]), float(sc[axes.index('x')])) return np.ascontiguousarray(a), scale, attrs.get('omero'), ms def idr_channels(omero, a): out = [] for i, ch in enumerate((omero or {}).get('channels', [])[: a.shape[0]]): w = ch.get('window', {}) win = (w['start'], w['end']) if 'start' in w and w['end'] > w['start'] else window(a[i]) out.append({'label': ch.get('label', f'ch{i}'), 'color': ch.get('color', 'FFFFFF'), 'window': win, 'active': ch.get('active', True)}) return out CC_BY = 'CC BY 4.0' def idr_attr(study, image, title, citation, doi): return {'title': title, 'source': f'Image Data Resource {study}, image {image}', 'url': f'https://idr.openmicroscopy.org/webclient/?show=image-{image}', 'license': CC_BY, 'citation': citation, 'doi': doi, 'modified': 'converted to OME-Zarr 0.5 (Zarr v3, sharded, gzip), new 2x pyramid'} def idr0157(): p = SRC / 'idr0157' / '0' a, scale, omero, _ = ngff_level(p, 0) return write('idr0157-asterella-thallus', a, rgb_channels(a), scale=scale, unit='micrometer', attribution=idr_attr('idr0157', 15154258, 'Asterella gracilis thallus cross section (brightfield, multi-focus fused)', 'Peters K, Ziegler J, Neumann S. Bryophyte imaging (IDR idr0157).', '10.17867/10000197')) def idr0054(): a, scale, omero, _ = ngff_level(SRC / 'idr0054', 0) ch = idr_channels(omero, a) # Labels carry mass tags ('CD3-170Er'); show six markers in distinct colours. shown = {'DNA1': '0000FF', 'CD3': 'FF0000', 'CD19': '00FF00', 'CD324/E-Cadherin': 'FFFF00', 'CD68': 'FF00FF', 'alphaSMA': '00FFFF'} for i, c in enumerate(ch): marker = c['label'].rsplit('-', 1)[0] c['active'] = marker in shown c['color'] = shown.get(marker, c['color']) c['window'] = window(a[i], 0.5, 99.5) # the source windows are mostly 0-255 return write('idr0054-tonsil-imc', a, ch, scale=scale, unit='micrometer', attribution=idr_attr('idr0054', 5025551, 'Human tonsil, imaging mass cytometry (27 markers)', 'Durand M et al. 2019, J Exp Med, doi:10.1084/jem.20181994', '10.17867/10000122')) def idr0073(): a, scale, omero, _ = ngff_level(SRC / 'idr0073', 1) # level 0 not mirrored (923 MB) return write('idr0073-lung-tlo', a, rgb_channels(a), scale=scale, unit='micrometer', attribution={**idr_attr('idr0073', 9798462, 'Lung tertiary lymphoid organ, IHC whole slide (lung08)', 'Schaadt NS et al. 2020, PLoS Comput Biol, doi:10.1371/journal.pcbi.1007385', '10.17867/10000134'), 'modified': 'source level 1 (half resolution) as level 0; converted to OME-Zarr 0.5'}) def idr0066(): a, scale, omero, _ = ngff_level(SRC / 'idr0066', 0) ch = idr_channels(omero, a) or [{'label': 'Cy3', 'color': 'FF8000', 'window': window(a[0])}] return write('idr0066-chick-embryo-mip', a, ch, scale=scale, unit='micrometer', attribution=idr_attr('idr0066', 8343616, 'Chicken embryo, mesoSPIM light-sheet maximum-intensity projection', 'Voigt FF et al. 2019, Nat Methods, doi:10.1038/s41592-019-0554-0', '10.17867/10000127')) def idr0033(): a, scale, omero, _ = ngff_level(SRC / 'idr0033' / '0', 0) return write('idr0033-cell-painting', a, idr_channels(omero, a), scale=scale, unit='micrometer', attribution=idr_attr('idr0033', 14002892, 'U2OS cells, Cell Painting (5 channels), plate BR00109990 well C2', 'Rohban MH et al. 2017, eLife, doi:10.7554/eLife.24060', '10.17867/10000105')) def idr0158(): """Imaris ResolutionLevel 1 (half resolution): level 0 of channel 3 (BCL2) has 28 corrupt gzip chunks in IDR's own file, and full resolution is over budget.""" import h5py f = h5py.File(SRC / 'MxIF_P1_FL4.ims', 'r') info = f['DataSetInfo'] txt = lambda g, k: b''.join(g.attrs[k]).decode() if k in g.attrs else '' img = info['Image'] W, H = int(txt(img, 'X')), int(txt(img, 'Y')) sx = (float(txt(img, 'ExtMax0')) - float(txt(img, 'ExtMin0'))) / W * 2 sy = (float(txt(img, 'ExtMax1')) - float(txt(img, 'ExtMin1'))) / H * 2 w1, h1 = -(-W // 2), -(-H // 2) tp = f['DataSet/ResolutionLevel 1/TimePoint 0'] # Source colours repeat (two greens, two blues); give each marker its own. colours = {'aSMA': 'FF00FF', 'Nuclei': '0000FF', 'CD20': '00FF00', 'BCL2': 'FF0000', 'CD10': 'FFFF00'} chans, planes = [], [] for i in range(len(tp)): plane = tp[f'Channel {i}/Data'][0, :h1, :w1] planes.append(plane) label = txt(info[f'Channel {i}'], 'Name').split(':')[-1] or f'ch{i}' chans.append({'label': label, 'color': colours.get(label, 'FFFFFF'), 'window': window(plane)}) a = np.stack(planes) attribution = idr_attr('idr0158', 15159193, 'Follicular lymphoma, multiplexed immunofluorescence (MxIF_P1_FL4)', 'Radtke AJ et al. 2024, Cancer Cell, doi:10.1016/j.ccell.2024.02.001', '10.17867/10000199') attribution['modified'] = ('Imaris resolution level 1 (half of 21347 x 17611) as level 0; channel colours reassigned; ' 'converted to OME-Zarr 0.5 (Zarr v3, sharded, gzip)') return write('idr0158-lymphoma-mxif', a, chans, scale=(sy, sx), unit='micrometer', attribution=attribution) def sentinel2(): import tifffile bands = [('B02', 'blue', '0000FF', True), ('B03', 'green', '00FF00', True), ('B04', 'red', 'FF0000', True), ('B08', 'NIR', 'FFFFFF', False), ('B11', 'SWIR 1.6 um', 'FF00FF', False), ('B12', 'SWIR 2.2 um', 'FFFF00', False)] a = np.stack([tifffile.imread(SRC / 's2' / f'{b}.tif') for b, *_ in bands]) chans = [{'label': f'{b} {lab}', 'color': col, 'active': act, 'window': window(a[i], 1, 99.5)} for i, (b, lab, col, act) in enumerate(bands)] return write('sentinel2-richat-structure', a, chans, scale=(10.0, 10.0), unit='meter', attribution={ 'title': 'Richat Structure (Eye of the Sahara), Mauritania: Sentinel-2 L2A, 2025-12-26 (bands 2, 3, 4, 8, 11, 12 at 10 m)', 'source': 'Copernicus Sentinel-2 (S2C_29QKD_20251226_0_L2A), Element 84 Earth Search open bucket', 'url': 'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/29/Q/KD/2025/12/S2C_29QKD_20251226_0_L2A/', 'license': 'Copernicus Sentinel data terms (free, full and open)', 'credit': 'Contains modified Copernicus Sentinel data 2025', 'modified': '51.2 km crop, 20 m bands resampled to 10 m (bilinear); reflectance DN with BOA offset 1000; OME-Zarr 0.5'}) def webb(): a = read_tif(SRC / 'cliffs.tif')[:3] return write('webb-cosmic-cliffs', a, rgb_channels(a), attribution={ 'title': "Webb NIRCam 'Cosmic Cliffs' in the Carina Nebula (weic2205a)", 'url': 'https://esawebb.org/images/weic2205a/', 'license': CC_BY, 'credit': 'NASA, ESA, CSA, and STScI', 'modified': '(converted to OME-Zarr, multiscale)'}) def black_marble(): # Tile C1 covers 0-90 E, 0-90 N at 15 arc-seconds (~500 m); crop 0-45 E, 20-65 N. src, crop = SRC / 'BlackMarble_2016_C1_geo.tif', SRC / 'blackmarble_crop.tif' subprocess.run(['gdal_translate', '-q', '-projwin', '0', '65', '45', '20', '-co', 'COMPRESS=NONE', str(src), str(crop)], check=True) a = read_tif(crop)[:3] return write('nasa-black-marble-europe', a, rgb_channels(a), attribution={ 'title': 'Black Marble 2016: Earth at night, Europe, North Africa and the Middle East (0-45 E, 20-65 N, ~500 m)', 'url': 'https://science.nasa.gov/earth/earth-observatory/earth-at-night/maps/', 'license': 'NASA imagery: not copyrighted; acknowledge NASA', 'credit': 'NASA Earth Observatory', 'modified': 'cropped from tile C1; converted to OME-Zarr 0.5'}) def moon(): small = SRC / 'moon12k.tif' if not small.exists(): gdal_resize(SRC / 'moon16k.tif', small, 12288, 6144) a = read_tif(small)[:3] return write('nasa-moon-lroc-color', a, rgb_channels(a), attribution={ 'title': 'CGI Moon Kit: LROC colour map (simple cylindrical)', 'url': 'https://svs.gsfc.nasa.gov/4720', 'license': 'Public domain (NASA SVS)', 'credit': "NASA's Scientific Visualization Studio (LRO LROC WAC, LOLA)", 'modified': 'downsampled from 16384 x 8192 to 12288 x 6144 (cubic); OME-Zarr 0.5'}) def empiar10404(): raw = np.load(SRC / 'empiar10404_l3.npy') lo, hi = window(raw, 0.5, 99.5) a = (np.clip((raw.astype(np.float32) - lo) / (hi - lo), 0, 1) * 255).round().astype(np.uint8)[None] return write('empiar10404-sars-cov-2-organoid', a, [{'label': 'TEM', 'color': 'FFFFFF', 'window': (0, 255)}], scale=(0.007974, 0.007974), unit='micrometer', attribution={ 'title': 'SARS-CoV-2 infected human gut organoid, TEM map (12448_G1HR_Mesh003, pyramid level 3, ~8 nm)', 'source': 'EMPIAR-10404', 'url': 'https://www.ebi.ac.uk/empiar/EMPIAR-10404/', 'license': 'CC0', 'citation': 'Lamers MM et al. 2020, Science 369:50-54, doi:10.1126/science.abc1669', 'doi': '10.6019/EMPIAR-10404', 'modified': f'level 3 of the source pyramid; uint16 windowed to uint8 ({lo:.0f}-{hi:.0f}); OME-Zarr 0.5'}) def empiar12850(): a = zarr.open_array(SRC / 'empiar12850' / 'data_level_1', mode='r', zarr_format=2)[0][None] return write('empiar12850-mouse-brain-tem', a, [{'label': 'TEM', 'color': 'FFFFFF', 'window': window(a[0], 0.5, 99.5)}], scale=(0.0034, 0.0034), unit='micrometer', attribution={ 'title': 'Mouse brain TEM, 3.4 nm (EM2B6 266_240326GN_JEM1400_Slot812)', 'source': 'EMPIAR-12850', 'url': 'https://www.ebi.ac.uk/empiar/EMPIAR-12850/', 'license': 'CC0', 'citation': 'Konishi K et al. 2025, J Microsc 300:94-107, doi:10.1111/jmi.13436', 'doi': '10.6019/EMPIAR-12850', 'modified': 'source data_level_1 re-saved as OME-Zarr 0.5 with a new pyramid'}) SOURCES = {f.__name__: f for f in (idr0157, idr0054, idr0073, idr0066, idr0033, idr0158, sentinel2, webb, black_marble, moon, empiar10404, empiar12850)} if __name__ == '__main__': OUT.mkdir(exist_ok=True) sizes = {n: SOURCES[n]() for n in sys.argv[1:]} print(json.dumps(sizes))