Skip to content

Instantly share code, notes, and snippets.

@bbarad
Created May 28, 2025 17:16
Show Gist options
  • Select an option

  • Save bbarad/c556c6f5181f30a441017f01954cee25 to your computer and use it in GitHub Desktop.

Select an option

Save bbarad/c556c6f5181f30a441017f01954cee25 to your computer and use it in GitHub Desktop.
Combine named binary mrc segmentations into a single quantized mrc.
## Segmentation values and names are hardcoded (line 7).
## All segmentations should be in a single "segmentations" folder.
## This should match what is used in the config.yml for surface morphometrics
from sys import argv
import mrcfile
import os
import numpy as np
component_values = {"vesicle":1,
"er":2,
"mvb":3,
"golgi":4,
"imm":5,
"omm":6,
"nuclear_membrane":7,
"plasma_membrane":8,
"ocm":9,
"icm":10,
"thylakoid":11,
"organelle":12}
folder = argv[1]
folder_path = folder+"/mrc/"
print(os.listdir(folder_path))
files = os.listdir(folder_path)
results = []
pixsize = None
extended_header = None
for value in files:
component = value[:-4]
if not component in component_values.keys():
print(f"Ignoring component {component} because not in config")
continue
print(component, component_values[component])
with mrcfile.open(folder_path+value) as mrc:
extended_header = mrc.extended_header
pixsize = mrc.voxel_size
data = mrc.data
data = data+np.min(data)
data = data*component_values[component]
results.append(data)
new_matrix = sum(results)
new_matrix = np.flip(new_matrix,1)
print(new_matrix.shape)
with mrcfile.new("segmentations/"+folder+".mrc", overwrite=True) as new_mrc:
new_mrc.set_data(new_matrix)
new_mrc.set_extended_header(extended_header)
new_mrc.voxel_size = pixsize
@bbarad
Copy link
Author

bbarad commented Jun 1, 2025

You should have classname.mrcs in an mrc/ folder. If you have tifs in individual folders instead of the mrc folder full of named tifs, you can generate those mrcs with imod (repeat for each classname):
tif2mrc /CLASSNAME/*.mrc mrc/CLASSNAME.mrc

Adjust the dictionary in lines 9-20 to match your surface morphometrics config file - thats what will be read out by surface morphometrics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment