VTK学习笔记(二十八)ExtractEnclosedPoints python示例
1、Python vtkSelectEnclosedPoints Examples
Python vtkSelectEnclosedPoints - 10 examples found. These are the top rated real world Python examples of vtk.vtkSelectEnclosedPoints extracted from open source projects. You can rate examples to help us improve the quality of examples.
1.1、File: findPointsInCell.py Project: gacevedobolton/myVTKPythonLibrary
def findPointsInCell(points,
cell,
verbose=1):
ugrid_cell = vtk.vtkUnstructuredGrid()
ugrid_cell.SetPoints(cell.GetPoints())
cell = vtk.vtkHexahedron()
for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point)
cell_array_cell = vtk.vtkCellArray()
cell_array_cell.InsertNextCell(cell)
ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell)
geometry_filter = vtk.vtkGeometryFilter()
geometry_filter.SetInputData(ugrid_cell)
geometry_filter.Update()
cell_boundary = geometry_filter.GetOutput()
pdata_points = vtk.vtkPolyData()
pdata_points.SetPoints(points)
enclosed_points_filter = vtk.vtkSelectEnclosedPoints()
enclosed_points_filter.SetSurfaceData(cell_boundary)
enclosed_points_filter.SetInputData(pdata_points)
enclosed_points_filter.Update()
points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple(k_point)[0]]
return points_in_cell
1.2、File: world.py Project: cjauvin/pypetree
def select_point_cloud(self):
if not self.scene.get_active_point_cloud(): return
self.unselect_point_cloud()
transform = vtk.vtkTransform()
transform.SetMatrix(self.actor.GetMatrix())
transform_filter = vtk.vtkTransformPolyDataFilter()
transform_filter.SetInputConnection(self.src.GetOutputPort())
transform_filter.SetTransform(transform)
enclosed_pts = vtk.vtkSelectEnclosedPoints()
if USING_VTK6:
enclosed_pts.SetInputData(self.scene.get_active_point_cloud().polydata)
enclosed_pts.SetSurfaceConnection(transform_filter.GetOutputPort())
else:
enclosed_pts.SetInput(self.scene.get_active_point_cloud().polydata)
enclosed_pts.SetSurface(transform_filter.GetOutput())
enclosed_pts.Update()
inside_arr = enclosed_pts.GetOutput().GetPointData().\
GetArray('SelectedPoints')
self.selected_pts = []
for i in range(inside_arr.GetNumberOfTuples()):
if inside_arr.GetComponent(i, 0):
self.scene.get_active_point_cloud().colors.\
SetTuple3(i, *name_to_rgb('blue'))
self.selected_pts.append(i)
self.scene.get_active_point_cloud().selected_pts[i] += 1
self.scene.get_active_point_cloud().colors.Modified()
self.frame.ren_win.Render()
1.3、File: vtklib.py Project: ajgeers/utils
def insidepoints(points, surface, tolerance=1e-4):
"""Mark points as to whether they are inside a closed surface"""
marker = vtk.vtkSelectEnclosedPoints()
marker.SetInput(points)
marker.SetSurface(surface)
marker.SetTolerance(tolerance)
marker.Update()
return marker.GetOutput()
1.4、File: TissuePunctures.py Project: PerkTutor/PythonMetrics
def SetAnatomy( self, role, node ):
if ( role == "Tissue" and node.GetPolyData() != None ):
self.tissueNode = node
self.enclosedFilter = vtk.vtkSelectEnclosedPoints()
self.enclosedFilter.Initialize( self.tissueNode.GetPolyData() )
return True
return False
1.5、File: STL_VTK.py Project: ksiezykm/GeometryGenerator
def IsInsideCheck(pX,pY,pZ,mesh):
select = vtk.vtkSelectEnclosedPoints()
select.SetSurface(mesh)
select.SetTolerance(.00001)
pts = vtk.vtkPoints()
pts.InsertNextPoint((pX),(pY),(pZ))
pts_pd = vtk.vtkPolyData()
pts_pd.SetPoints(pts)
select.SetInput(pts_pd)
select.Update()
return select.IsInside(0)
1.6、File: surftools.py Project: dgoyard/pyfreesurfer
def voxelize(self, shape, tol=0):
""" Compute the enclosed points of the TriSurface.
This code uses vtk.
Parameters
----------
shape: 3-uplet
the image shape.
Returns
-------
inside_array: array
a mask array with the enclosed voxels.
"""
import vtk
from vtk.util.numpy_support import vtk_to_numpy
nx, ny, nz = shape
gridx, gridy, gridz = numpy.meshgrid(numpy.linspace(0, nx - 1, nx),
numpy.linspace(0, ny - 1, ny),
numpy.linspace(0, nz - 1, nz))
vtk_points = vtk.vtkPoints()
for point in zip(gridx.flatten(), gridy.flatten(), gridz.flatten()):
vtk_points.InsertNextPoint(point)
points_polydata = vtk.vtkPolyData()
points_polydata.SetPoints(vtk_points)
surf_polydata = self._polydata()
enclosed_pts = vtk.vtkSelectEnclosedPoints()
enclosed_pts.SetInput(points_polydata)
enclosed_pts.SetTolerance(tol)
enclosed_pts.SetSurface(surf_polydata)
enclosed_pts.SetCheckSurface(1)
enclosed_pts.Update()
inside_points = enclosed_pts.GetOutput().GetPointData().GetArray(
"SelectedPoints")
enclosed_pts.ReleaseDataFlagOn()
enclosed_pts.Complete()
inside_array = vtk_to_numpy(inside_points).reshape(ny, nx, nz)
inside_array = numpy.swapaxes(inside_array, 1, 0)
return inside_array
1.7、File: vtk_itf.py Project: dladd/pyFormex
def vtkPointInsideObject(S,P,tol=0.):
"""vtk function to test which of the points P are inside surface S"""
from vtk import vtkSelectEnclosedPoints
vpp = convert2VPD(P)
vps =convert2VPD(S,clean=False)
enclosed_pts = vtkSelectEnclosedPoints()
enclosed_pts.SetInput(vpp)
enclosed_pts.SetTolerance(tol)
enclosed_pts.SetSurface(vps)
enclosed_pts.SetCheckSurface(1)
enclosed_pts.Update()
inside_arr = enclosed_pts.GetOutput().GetPointData().GetArray('SelectedPoints')
enclosed_pts.ReleaseDataFlagOn()
enclosed_pts.Complete()
del enclosed_pts
return asarray(v2n(inside_arr),'bool')
参考:Python vtkSelectEnclosedPoints Examples
2、CellsInsideObject
2.1、代码
import vtk
def get_program_parameters():
import argparse
description = 'Read a polydata file of a surface and determine if it is a closed surface.'
epilogue = '''
This example illustrates how to extract the cells that exist inside a closed surface.
It uses vtkSelectEnclosedPoints to mark points that are inside and outside the surface.
vtkMultiThreshold is used to extract the three meshes into three vtkMultiBlockDataSet's.
The cells completely outside are shown in crimson, completely inside are yellow and
border cells are green.
A translucent copy of the closed surface helps illustrate the selection process.
If two polydata datasets are provided, the example uses the second as the closed surface.
If only one dataset is provided, the closed surface is generated by rotating the
first dataset by 90 degrees around its Y axis.
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('filename1', help='Enter a polydata file e.g cow.g.')
parser.add_argument('filename2', default=None, nargs='?', help='Enter another polydata file e.g cow.g.')
args = parser.parse_args()
return args.filename1, args.filename2
def ReadPolyData(file_name):
import os
path, extension = os.path.splitext(file_name)
extension = extension.lower()
if extension == ".ply":
reader = vtk.vtkPLYReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".vtp":
reader = vtk.vtkXMLpoly_dataReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".obj":
reader = vtk.vtkOBJReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".stl":
reader = vtk.vtkSTLReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".vtk":
reader = vtk.vtkpoly_dataReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".g":
reader = vtk.vtkBYUReader()
reader.SetGeometryFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
else:
poly_data = None
return poly_data
def main():
fn1, fn2 = get_program_parameters()
polyData1 = ReadPolyData(fn1)
if fn2:
polyData2 = ReadPolyData(fn1)
else:
print('Generating modified polyData1')
center = polyData1.GetCenter()
transform = vtk.vtkTransform()
transform.Translate(center[0], center[1], center[2])
transform.RotateY(90.0)
transform.Translate(-center[0], -center[1], -center[2])
transformPD = vtk.vtkTransformPolyDataFilter()
transformPD.SetTransform(transform)
transformPD.SetInputData(polyData1)
transformPD.Update()
polyData2 = transformPD.GetOutput()
select = vtk.vtkSelectEnclosedPoints()
select.SetInputData(polyData1)
select.SetSurfaceData(polyData2)
threshold = vtk.vtkMultiThreshold()
outsideId = threshold.AddBandpassIntervalSet(
0, 0,
vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
0, 1)
insideId = threshold.AddBandpassIntervalSet(
1, 1,
vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
0, 1)
borderId = threshold.AddIntervalSet(
0, 1,
vtk.vtkMultiThreshold.OPEN, vtk.vtkMultiThreshold.OPEN,
vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
0, 0)
threshold.SetInputConnection(select.GetOutputPort())
threshold.OutputSet(outsideId)
threshold.OutputSet(insideId)
threshold.OutputSet(borderId)
threshold.Update()
colors = vtk.vtkNamedColors()
outsideColor = colors.GetColor3d("Crimson")
insideColor = colors.GetColor3d("Banana")
borderColor = colors.GetColor3d("Mint")
surfaceColor = colors.GetColor3d("Peacock")
backgroundColor = colors.GetColor3d("Silver")
outsideMapper = vtk.vtkDataSetMapper()
outsideMapper.SetInputData(threshold.GetOutput().GetBlock(outsideId).GetBlock(0))
outsideMapper.ScalarVisibilityOff()
outsideActor = vtk.vtkActor()
outsideActor.SetMapper(outsideMapper)
outsideActor.GetProperty().SetDiffuseColor(outsideColor)
outsideActor.GetProperty().SetSpecular(.6)
outsideActor.GetProperty().SetSpecularPower(30)
insideMapper = vtk.vtkDataSetMapper()
insideMapper.SetInputData(threshold.GetOutput().GetBlock(insideId).GetBlock(0))
insideMapper.ScalarVisibilityOff()
insideActor = vtk.vtkActor()
insideActor.SetMapper(insideMapper)
insideActor.GetProperty().SetDiffuseColor(insideColor)
insideActor.GetProperty().SetSpecular(.6)
insideActor.GetProperty().SetSpecularPower(30)
insideActor.GetProperty().EdgeVisibilityOn()
borderMapper = vtk.vtkDataSetMapper()
borderMapper.SetInputData(threshold.GetOutput().GetBlock(borderId).GetBlock(0))
borderMapper.ScalarVisibilityOff()
borderActor = vtk.vtkActor()
borderActor.SetMapper(borderMapper)
borderActor.GetProperty().SetDiffuseColor(borderColor)
borderActor.GetProperty().SetSpecular(.6)
borderActor.GetProperty().SetSpecularPower(30)
borderActor.GetProperty().EdgeVisibilityOn()
surfaceMapper = vtk.vtkDataSetMapper()
surfaceMapper.SetInputData(polyData2)
surfaceMapper.ScalarVisibilityOff()
surfaceActor = vtk.vtkActor()
surfaceActor.SetMapper(surfaceMapper)
surfaceActor.GetProperty().SetDiffuseColor(surfaceColor)
surfaceActor.GetProperty().SetOpacity(.1)
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindow.SetSize(640, 480)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.SetBackground(backgroundColor)
renderer.UseHiddenLineRemovalOn()
renderer.AddActor(surfaceActor)
renderer.AddActor(outsideActor)
renderer.AddActor(insideActor)
renderer.AddActor(borderActor)
renderWindow.SetWindowName('CellsInsideObject')
renderWindow.Render()
renderer.GetActiveCamera().Azimuth(30)
renderer.GetActiveCamera().Elevation(30)
renderer.GetActiveCamera().Dolly(1.25)
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
2.2、执行
python ./PolyData/CellsInsideObject.py ../Testing/Data/cow.g
3、检查polydata1在polydata2内
3.1、函数代码
def judge_polydata_One_in_another(self, polyData1, polyData2, tolerance=1e-3):
print("polyData1: \n", polyData1)
select = vtk.vtkSelectEnclosedPoints()
select.SetInputData(polyData1)
select.SetSurfaceData(polyData2)
select.Update()
inside_arr = select.GetOutput().GetPointData().GetArray("SelectedPoints")
print("inside_arr \n", inside_arr)
in_count = 0
out_count = 0
all_count = inside_arr.GetNumberOfTuples()
print("all_count \n", all_count)
for i in range(inside_arr.GetNumberOfTuples()):
if inside_arr.GetComponent(i, 0):
in_count += 1
else:
out_count += 1
print("in_count \n", in_count)
print("out_count \n", out_count)
3.2、输入polydata
3.3、打印信息
下面只截取了我认为有用的重要信息:
polyData1:
vtkPolyData (000001E8A33E1680)
Debug: Off
Modified Time: 2908271
Reference Count: 3
Registered Events:
Registered Observers:
vtkObserver (000001E8A3B3C1A0)
Event: 36
EventName: ModifiedEvent
Command: 000001E8A3B3C260
Priority: 0
Tag: 1
Information: 000001E8A3AD23A0
Data Released: False
Global Release Data: Off
UpdateTime: 2908667
Field Data:
Debug: Off
Modified Time: 2908096
Reference Count: 1
Registered Events: (none)
Number Of Arrays: 0
Number Of Components: 0
Number Of Tuples: 0
Number Of Points: 1894
Number Of Cells: 3892
inside_arr
vtkUnsignedCharArray (000001E8A39160A0)
Debug: Off
Modified Time: 2912431
Reference Count: 3
Registered Events: (none)
Name: SelectedPoints
Data type: unsigned char
Size: 1894
MaxId: 1893
NumberOfComponents: 1
Information: 0000000000000000
Name: SelectedPoints
Number Of Components: 1
Number Of Tuples: 1894
Size: 1894
MaxId: 1893
LookupTable: (none)
all_count
1894
in_count
1833
out_count
61
3.4、输出分析
通过上述打印信息与图片可以知道,polydata1只有极小的一部分点在polydata2之外。 如果polydata1的所有点都在polydata2之内,则可以判断 polydata1在polydata2之内。 当只有极小一部分点在外面时,可以调整polydata1的位置,使其全部包含在polydata2之内。
通过上述打印信息还可以知道,判断时实际上时遍历了polydata1的左右点数据,并对在polydata2内的数据标记了1,在polydata2外的数据标记了0,如果polydata1的点数据是有序的并且可以获取到,那么就可以找到在polydata2外的点,然后就可以根据这些点的相对与polydata1和polydata2的位置,调整polydata1的姿态,使polydata1完全包含在polydata2之内。
|