labsyspharm / ashlar

ASHLAR: Alignment by Simultaneous Harmonization of Layer/Adjacency Registration
https://labsyspharm.github.io/ashlar/
MIT License
126 stars 42 forks source link

Help Wanted - how to input positions in a fileseries #171

Closed joaomamede closed 1 year ago

joaomamede commented 1 year ago

We imaged a bit of tissue with non square positions to save time and disk space.

Is there any way to input the positions in a fileseries input? If not, only by inputting ome.tiffs with coordinates on metadata would work?

Each field of view is a single file, and the metadata between files is not linked (as in series).

Thank you!

Yu-AnChen commented 1 year ago

Maybe my response here is applicable to your situation.

joaomamede commented 1 year ago

Maybe my response here is applicable to your situation.

I will give it a try. Thank you.

joaomamede commented 1 year ago

It worked. I did a few modifications to be easier for what I have, while keeping more metadata. I first tried to get the metadata positions from the ome.tiffs directly but pims JVM couldn't handle the looping, so I defaulted to the original ND2.


import copy
import pathlib
import uuid

import ome_types
import tifffile
from nd2reader import ND2Reader
import pims

def make_ome_pixel(
    img_path, sample_ome, position_x, position_y,
):
    img_path = pathlib.Path(img_path)
    sample_ome = copy.deepcopy(sample_ome)
    pixel = sample_ome.images[0].pixels

#     pixel.physical_size_x = pixel_size
#     pixel.physical_size_y = pixel_size

    UUID = ome_types.model.tiff_data.UUID(
        file_name=str(img_path.name),
        value=uuid.uuid4().urn
    )

    tiff_block = pixel.tiff_data_blocks[0]

    num_planes = len(pixel.planes)
    tiff_block.uuid = UUID

    for i in range(num_planes):
        pixel.planes[i].position_x = position_x
        pixel.planes[i].position_y = position_y
#         plane = pixel.
#             the_c=i, the_z=0, the_t=0,
#             position_x=position_x, position_y=position_y
#         )
#         pixel.planes.append(plane)

    return pixel

folder = "/media/Jenni/20230224-humice/orchid/"
img_paths = sorted(pathlib.Path(folder).glob('Cycle1*.nd2'))

img_paths

reader = ND2Reader(str(img_paths[0]))
xy_positions = list(zip(reader.metadata['x_coordinates'][::reader.sizes['z']], reader.metadata['y_coordinates'][::reader.sizes['z']]))
reader.close()

img_paths = sorted(pathlib.Path(folder).glob('Cycle1*.tif'))

reader = pims.Bioformats(str(img_paths[0]),java_memory = '2048m')
sample_ome = ome_types.from_xml(str( reader._metadata.dumpXML()))
reader.close()

pixels = [
    make_ome_pixel(path, sample_ome, float(pos_x), float(pos_y))
    for path, (pos_x, pos_y) in zip(img_paths, xy_positions)
]

omexml = ome_types.model.OME()
omexml.images = [ome_types.model.Image(pixels=p) for p in pixels]

out_path = 'Cycle1.companion.ome'
print(f"Writing to {out_path}\n")
with open(out_path, 'w') as f:
    f.write(omexml.to_xml())