IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> VTK学习笔记(二十八)ExtractEnclosedPoints python示例 -> 正文阅读

[Python知识库]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()
   # print pX,pY,pZ,select.IsInside(0)
    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 here since vtk is not required by the package
        import vtk
        from vtk.util.numpy_support import vtk_to_numpy

        # Construct the mesh grid from shape
        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))

        # Create polydata
        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()

        # Compute enclosed points
        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()

        # Convert result as a numpy array
        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、代码

#!/usr/bin/env python

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:
        # Return a None if the extension is unknown.
        poly_data = None
    return poly_data


def main():
    fn1, fn2 = get_program_parameters()
    polyData1 = ReadPolyData(fn1)
    if fn2:
        polyData2 = ReadPolyData(fn1)
    else:
        # If only one polydata is present, generate a second polydata by
        # rotating the original about its center.
        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()

    # Mark points inside with 1 and outside with a 0
    select = vtk.vtkSelectEnclosedPoints()
    select.SetInputData(polyData1)
    select.SetSurfaceData(polyData2)

    # Extract three meshes, one completely inside, one completely
    # outside and on the border between the inside and outside.

    threshold = vtk.vtkMultiThreshold()
    # Outside points have a 0 value in ALL points of a cell
    outsideId = threshold.AddBandpassIntervalSet(
        0, 0,
        vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
        0, 1)
    # Inside points have a 1 value in ALL points of a cell
    insideId = threshold.AddBandpassIntervalSet(
        1, 1,
        vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
        0, 1)
    # Border points have a 0 or a 1 in at least one point of a cell
    borderId = threshold.AddIntervalSet(
        0, 1,
        vtk.vtkMultiThreshold.OPEN, vtk.vtkMultiThreshold.OPEN,
        vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
        0, 0)

    threshold.SetInputConnection(select.GetOutputPort())

    # Select the intervals to be output
    threshold.OutputSet(outsideId)
    threshold.OutputSet(insideId)
    threshold.OutputSet(borderId)
    threshold.Update()

    # Visualize
    colors = vtk.vtkNamedColors()
    outsideColor = colors.GetColor3d("Crimson")
    insideColor = colors.GetColor3d("Banana")
    borderColor = colors.GetColor3d("Mint")
    surfaceColor = colors.GetColor3d("Peacock")
    backgroundColor = colors.GetColor3d("Silver")

    # Outside
    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)

    # Inside
    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()

    # Border
    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()

    # Surface of object containing cell
    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):
    # Mark points inside with 1 and outside with a 0
    print("polyData1: \n", polyData1)
    select = vtk.vtkSelectEnclosedPoints()
    select.SetInputData(polyData1)
    select.SetSurfaceData(polyData2)
    # select.SetTolerance(tolerance)
    # select.SetCheckSurface(1)
    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之内。

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-04-07 22:39:25  更:2022-04-07 22:41:14 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/28 23:13:23-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计