ilia-kats / spatialmuon

0 stars 0 forks source link

SpatialMuData object can only be printed after loading it again from disk? #3

Open timtreis opened 2 years ago

timtreis commented 2 years ago
f_ome = "/data/spatialmuon/datasets/imc/raw/OMEandSingleCellMasks/ome/ZTMA208_slide_28.23kx22.4ky_7000x7000_5_20171115_108_67_Ay14x4_364_a0_full.tiff"
f_masks = "/data/spatialmuon/datasets/imc/raw/OMEandSingleCellMasks/Basel_Zuri_masks/ZTMA208_slide_28.23kx22.4ky_7000x7000_5_20171115_108_67_Ay14x4_364_a0_full_maks.tiff"
outfile = "/home/treis/spmsandbox/debug.h5smu"

def tiff_to_spm_raster(path):
    """ Opens a .tiff and converts it to a spm.Raster(). """

    ome = tifffile.TiffFile(path)
    metadata = ElementTree.fromstring(ome.ome_metadata)[0]
    for chld in metadata:
        if chld.tag.endswith("Pixels"):
            metadata = chld
            break
    channel_names = []
    for channel in metadata:
        if channel.tag.endswith("Channel"):
            channel_names.append(channel.attrib["Fluor"])
    var = pd.DataFrame({"channel_name": channel_names})
    res = spatialmuon.Raster(
        X=np.moveaxis(ome.asarray(), 0, -1), 
        var=var
    )

    return(res)

def tiff_to_spm_rastermask(path):
    """ Opens a .tiff and converts it to a spm.RasterMask(). """

    masks = np.asarray(tifffile.imread(path))

    res = spatialmuon.RasterMasks(mask=masks)

    return(res)

# Delete if it exists
if os.path.isfile(outfile):
    os.unlink(outfile)

smudata = SpatialMuData(outfile)
print(str(np.round(os.path.getsize(outfile)/1024)) + " kb")

mod1 = SpatialModality(coordinate_unit="μm")
mod1["ome"] = tiff_to_spm_raster(f_ome)
mod1["masks"] = tiff_to_spm_rastermask(f_masks)

mod2 = SpatialModality(coordinate_unit="μm")
mod2["ome"] = tiff_to_spm_raster(f_ome)
mod2["masks"] = tiff_to_spm_rastermask(f_masks)

smudata["IMC1"] = mod1
smudata["IMC2"] = mod2
print(str(np.round(os.path.getsize(outfile)/1024)) + " kb")
smudata

image