How to color a stl file using VTK in python

Hello,

I am a newbie in VTK.

I have generated a STL file (of bones) using VTK, and now I want to have specific color labels for each slice, for example :

  • if the width of slice(n) > N (number) => green,

  • if width of slice(n) < M => red,

  • if width of M<slice(n)<N => orange.

Is there’s a way to do it ?

STL files cannot store color. You can use “Plane cut” tool in “Dynamic modeler” module to cut up a model with slice planes.

What is your overall goal?

Thank’s for your answer.

I want to parse my 3D object by slices, and check for each point “x” if the width is superior to a certain treshold, if so => Color the corresponding slice “GREEN”. Else, color it “RED”.

What follow is my code. But I am coloring the x-axis and not the z-axis.

import vtk, sys
import statistics
# Read in your STL file
f = vtk.vtkSTLReader()
f.SetFileName("airways_no_labels.stl")
f.Update() # This is necessary to have the data ready to read.

# The vtkSTLReader reads in your file as a vtkPolyData, 'obj' is a reference to
# that output. I'm using the bounds that are automatically calculated during
# the import phase to give a range for the height of the points in the file.v
# I believe that the bounds are (xmin, xmax, ymin, ymax, zmin, zmax).
obj = f.GetOutputDataObject(0)
min_x , max_x , min_y , max_y ,min_z, max_z = obj.GetBounds()

lut = vtk.vtkLookupTable()
lut.SetTableRange(min_z, max_z)
lut.Build()

heights = vtk.vtkDoubleArray()
heights.SetName("Z_Value")

Colors = vtk.vtkUnsignedCharArray()
Colors.SetNumberOfComponents(3)
Colors.SetNumberOfTuples(obj.GetNumberOfCells())

for i in range(obj.GetNumberOfPoints()):
    z = obj.GetPoint(i)[-1] # z axis
    x = obj.GetPoint(i)[0] # x axis

# This is just a try but won't work
    if min_x < x < max_x: 
        Colors.InsertVariantValue(255,z)
    if min_x < x < 300 :
        Colors.InsertVariantValue(155,z)
    if 300 < x < max_x :
        heights.InsertVariantValue(0,z)
#end of the "TRY"

    # Add this array to the point data as a scalar.
obj.GetPointData().SetScalars(Colors)


mapper = vtk.vtkPolyDataMapper()
mapper.SetInputDataObject(obj)
mapper.SetScalarRange(min_z, max_z)
mapper.SetLookupTable(lut)
mapper.SetUseLookupTableScalarRange(True)

actor = vtk.vtkActor()
actor.SetMapper(mapper)

renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
renderer.SetBackground(.1, .2, .4)

renw = vtk.vtkRenderWindow()
renw.AddRenderer(renderer)

iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renw)

renw.Render()
iren.Start()

#Then save it as .vtk file

Hello Sir,
I am facing an issue. If you are comfortable with mitk I can proceed with my question.