I have a binary segmentation mask, I converted this to an STL file. I converted to mm space from pixel coordinate space by
Finding the coordinates of the vertices using marching cubes lewinn algorithm from skimage
multiplying the coordinates of the vertices with the corresponding x,y,z pixel spacing and adding the ImagePositionPatient of the first dicom slice obtained from the dicom meta tags
convert to stl using numpy-stl
When I load the image it seems that the loaded STL is having the same size and shape, but it has some rotational and translational offset, how do I form the stl file so that it is automatically aligned as soon as I load ?
I would recommend to convert form segmentation to STL using Slicer. If you use skimage or other basic Python tools that are not intended for medical imaging, then most likely they don’t handle image origin, spacing, axis directions properly and may not be aware of commond anatomical coordinate systems conventions (RAS/LPS). You can of course figure out and apply the transform manually, it is just a bit more work for you.
Thank you for the response, how do I apply the transform manually ? since all my segmentations are computer generated and not manually generated I store the coordinates as numpy array.
If you want to apply a linear transform (translation, rotation, scaling) to a mesh then you can represent it as a homogeneous transformation matrix and apply to all the mesh points by a single matrix multiplication. Constructing this transform and applying it manually is a useful learning exercise, but normally you would just use labelmap image <-> segmentation <-> mesh conversions that are conveniently available in Slicer (including all necessary coordinate system transformations, mesh smoothing, etc.). It takes two clicks of a button (right-click on the labelmap, segmentation, or model node in Data module then choose what you want to convert to) or by running a few lines of Python code (see examples in script repository).