Exporting Segment as OBJ through Python

Heya there! I would love to get some advice on how to export a segment I created to a file. I found this code from another topic and was wondering how and where I can the info. needed to do this for a .obj.

Write to STL file

surfaceMesh = segmentationNode.GetClosedSurfaceRepresentation(addedSegmentID)
writer = vtk.vtkSTLWriter()
writer.SetInputData(surfaceMesh)
writer.SetFileName("Z:/something.stl")
writer.Update()

Thank you in advance <3

Use vtkOBJWriter instead of vtkSTLWriter to write OBJ file.

See also this topic:

Thank you for the quick reply! It’s working now~

1 Like

Good day, I have a quick question!

outputFolder = "Z:/Dicom2Text/DicomPrefabs"
ExportSegmentsClosedSurfaceRepresentationToFiles(outputFolder, segmentatioNode, [segmentTypeID], "OBJ", true, 1.0, false)

Given your advice on the topic you provided me I have been trying to use “ExportSegmentsClosedSurfaceRepresentationToFiles”
What am I missing from the code above to make it call the method?

Thank you <3

I fixed it, but now I am getting a different issue

outputFolder = "Z:/Dicom2Text/DicomPrefabs"
slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsClosedSurfaceRepresentationToFiles(outputFolder, segmentationNode, [segmentTypeID], "OBJ", True, 1.0, False)

The error I am getting is:
TypeError: ExportSegmentsClosedSurfaceRepresentationToFiles argument 3: method requires a VTK object

To get help on how to use a method, use help method in the Python interactor:

>>> help(slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsClosedSurfaceRepresentationToFiles)
Help on method_descriptor:

ExportSegmentsClosedSurfaceRepresentationToFiles(...)
    V.ExportSegmentsClosedSurfaceRepresentationToFiles(string,
        vtkMRMLSegmentationNode, vtkStringArray, string, bool, float,
        bool) -> bool
    C++: static bool ExportSegmentsClosedSurfaceRepresentationToFiles(
        std::string destinationFolder,
        vtkMRMLSegmentationNode *segmentationNode,
        vtkStringArray *segmentIds=nullptr,
        std::string fileFormat="STL", bool lps=true,
        double sizeScale=1.0, bool merge=false)
    
    Export closed surface representation of multiple segments to
    files. Typically used for writing 3D printable model files.

As you can see, a vtkStringArray object is expected, while you provided a Python list of strings. If you want to export all segments, you can use None, if you want to export specific segments, create a vtk.vtkStringArray object and add the segment IDs that you would like to export.

1 Like

Thank you so much!!! I got it to work and all the information you have provided me has given a much better understand about the magic going on behind the scenes!!!

1 Like