import vtk
import random
reader = vtk.vtkDICOMImageReader()
reader.SetDirectoryName('D://mydata//yuanhm11//Desktop//dicom')
render = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
ir = vtk.vtkRenderWindowInteractor()
ir.SetRenderWindow(renWin)
renWin.AddRenderer(render)
style = vtk.vtkInteractorStyleTrackballCamera()
ir.SetInteractorStyle(style)
contour = vtk.vtkContourFilter()
contour.SetInputConnection(reader.GetOutputPort())
contour.GenerateValues(1, 100, 180)
connectivity_filter = vtk.vtkPolyDataConnectivityFilter()
connectivity_filter.SetInputConnection(contour.GetOutputPort())
connectivity_filter.SetExtractionModeToAllRegions()
connectivity_filter.Update()
regionSizes = connectivity_filter.GetRegionSizes()
num_regions = regionSizes.GetNumberOfTuples()
for i in range(num_regions):
PointNum = regionSizes.GetValue(i)
if PointNum > 30000:#阈值
region = vtk.vtkPolyDataConnectivityFilter()
region.SetInputConnection(connectivity_filter.GetOutputPort())
region.SetExtractionModeToSpecifiedRegions()
region.AddSpecifiedRegion(i)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(region.GetOutputPort())
mapper.SetScalarVisibility(True)
mapper.SetScalarModeToUseCellData()
mapper.SetScalarRange(0, 1) # 设置标量范围
actor = vtk.vtkActor()
actor.GetProperty().SetColor(random.randint(0, 255)/255.0,random.randint(0, 255)/255.0,random.randint(0, 255)/255.0)
actor.SetMapper(mapper)
render.AddActor(actor)
ir.Initialize()
ir.Start()
只保留一部分连通域并每个连通域赋予不同的颜色
于 2023-12-12 12:44:44 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)