# Programmatically Create a SegmentationNode and LabelMapNode from Polygon Coordinates

**URL:** <https://discourse.slicer.org/t/programmatically-create-a-segmentationnode-and-labelmapnode-from-polygon-coordinates/8448>\
**Category:** Development\
**Tags:** segmentation\
**Created:** [September 16, 2019, 6:00pm UTC](https://discourse.slicer.org/t/programmatically-create-a-segmentationnode-and-labelmapnode-from-polygon-coordinates/8448 "2019-09-16T18:00:16Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [September 17, 2019, 3:55am UTC](https://discourse.slicer.org/t/programmatically-create-a-segmentationnode-and-labelmapnode-from-polygon-coordinates/8448/4 "2019-09-17T03:55:26Z")

</div>

> [@rmd](#):
>
> my main question is how to save a .vtk file from the slicer python interpreter?

Probably the simplest is to create a segmentation node directly instead of creating a vtk file that can be loaded as segmentation. Here is a complete example of creating a segment (including closed surface and binary labelmap representation) from a list of contour points:

```python
# Create segmentation node where we will store segments
segmentationNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentationNode")
segmentationNode.CreateDefaultDisplayNodes()

# Create a segment from planar contours - can be repeated for multiple segments

segmentName = "test"
segmentColor = [1, 0, 0]
contours = [
    [[10,10,0], [30,10,0], [30,40,0], [10,25,0]],
    [[12,13,10], [31,9,10], [34,41,10], [12,23,10]],
    [[14,8,20], [22,11,20], [28,16,20], [16,28,20], [2,21,20]],
]

contoursPolyData = vtk.vtkPolyData()
contourPoints = vtk.vtkPoints()
contourLines = vtk.vtkCellArray()
contoursPolyData.SetLines(contourLines)
contoursPolyData.SetPoints(contourPoints)
for contour in contours:
    startPointIndex = contourPoints.GetNumberOfPoints()
    contourLine = vtk.vtkPolyLine()
    linePointIds = contourLine.GetPointIds()
    for point in contour:
        linePointIds.InsertNextId(contourPoints.InsertNextPoint(point))
    linePointIds.InsertNextId(startPointIndex) # make the contour line closed
    contourLines.InsertNextCell(contourLine)

segment = slicer.vtkSegment()
segment.SetName(segmentName)
segment.SetColor(segmentColor)
segment.AddRepresentation('Planar contour', contoursPolyData)
segmentationNode.GetSegmentation().AddSegment(segment)

```

---

_[View the full topic](https://discourse.slicer.org/t/programmatically-create-a-segmentationnode-and-labelmapnode-from-polygon-coordinates/8448)._
