为您推荐:
精华内容
最热下载
问答
  • 2KB weixin_42131785 2021-05-18 07:11:52
  • 64KB weixin_38727798 2020-09-18 03:20:56
  • 本文整理汇总了Pythonvtk.vtkRenderer方法的典型用法代码示例。如果您正苦于以下问题:Python vtk.vtkRenderer方法的具体用法?Python vtk.vtkRenderer怎么用?Python vtk.vtkRenderer使用的例子?那么恭喜您, ...

    本文整理汇总了Python中vtk.vtkRenderer方法的典型用法代码示例。如果您正苦于以下问题:Python vtk.vtkRenderer方法的具体用法?Python vtk.vtkRenderer怎么用?Python vtk.vtkRenderer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块vtk的用法示例。

    在下文中一共展示了vtk.vtkRenderer方法的27个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

    示例1: vis_segments

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def vis_segments(ind=1):

    renderer = vtk.vtkRenderer()

    seg_folder = os.path.join(params['base_dir'], "output/pcd_seg/" + str(ind).zfill(params["file_name_digits"])) + "/"

    seg_list = os.listdir(seg_folder)

    for seg in seg_list:

    if seg.split(".")[-1] == "txt":

    color_tup = (np.random.randint(1, 255, 3)).tolist()

    points_ls = list()

    jdcs_collection = cPickle.load(open(os.path.abspath(seg_folder + seg), 'rb'))

    if len(jdcs_collection) > 0: # filter

    for jdc in jdcs_collection:

    points_ls.extend(jdc)

    # print points_ls

    actor = vis_pcd_color_arr(np.array(points_ls), color_tup)

    renderer.AddActor(actor)

    vis_with_renderer(renderer)

    开发者ID:mfxox,项目名称:ILCC,代码行数:18,

    示例2: vis_segments_only_chessboard_color

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def vis_segments_only_chessboard_color(ind=1):

    renderer = vtk.vtkRenderer()

    seg_folder = os.path.join(params['base_dir'], "output/pcd_seg/" + str(ind).zfill(params["file_name_digits"])) + "/"

    seg_list = os.listdir(seg_folder)

    chessboard_file_name = \

    cPickle.load(open(os.path.join(params['base_dir'], "output/pcd_seg/") + str(ind).zfill(

    params["file_name_digits"]) + "_pcd_result.pkl", "r"))[

    -1].split("/")[-1]

    for seg in seg_list:

    if seg.split(".")[-1] == "txt":

    if seg == chessboard_file_name:

    color_tup = np.array([0, 255, 0])

    else:

    color_tup = np.array([0, 0, 0])

    points_ls = list()

    jdcs_collection = cPickle.load(open(os.path.abspath(seg_folder + seg), 'rb'))

    if len(jdcs_collection) > 0: # filter

    for jdc in jdcs_collection:

    points_ls.extend(jdc)

    # print points_ls

    actor = vis_pcd_color_arr(np.array(points_ls), color_tup)

    renderer.AddActor(actor)

    vis_with_renderer(renderer)

    开发者ID:mfxox,项目名称:ILCC,代码行数:26,

    示例3: __init__

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self):

    self.renderer = vtk.vtkRenderer()

    self.renderer.SetBackground(0.5, 0.5, 0.5)

    self.renderer.ResetCamera()

    axes_actor = vtk.vtkAxesActor()

    axes_actor.AxisLabelsOff()

    self.renderer.AddActor(axes_actor)

    self.window = vtk.vtkRenderWindow()

    self.window.AddRenderer(self.renderer)

    self.interactor = vtk.vtkRenderWindowInteractor()

    self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

    self.interactor.SetRenderWindow(self.window)

    self.camera = vtk.vtkCamera()

    self.camera.SetViewUp(0.0, -1.0, 0.0)

    self.camera.SetPosition(0.0, 0.0, -5)

    self.camera.SetFocalPoint(0.0, 0.0, 0.0)

    # self.camera.SetClippingRange(0.0, 100000)

    self.renderer.SetActiveCamera(self.camera)

    开发者ID:tobiasfshr,项目名称:MOTSFusion,代码行数:25,

    示例4: viewer

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def viewer(pointclouds):

    assert all([isinstance(p, VtkPointCloud) for p in pointclouds])

    # Renderer

    renderer = vtk.vtkRenderer()

    renderer.SetBackground(1.0, 1.0, 1.0)

    for p in pointclouds:

    renderer.AddActor(p.vtkActor)

    renderer.ResetCamera()

    # Render Window

    renderWindow = vtk.vtkRenderWindow()

    renderWindow.AddRenderer(renderer)

    # Interactor

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()

    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Begin Interaction

    renderWindow.Render()

    renderWindow.SetWindowName("XYZ Data Viewer")

    renderWindowInteractor.Start()

    开发者ID:moberweger,项目名称:deep-prior-pp,代码行数:26,

    示例5: make_render_window

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def make_render_window():

    #cone actor

    cone = vtk.vtkConeSource()

    coneMapper = vtk.vtkPolyDataMapper()

    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()

    coneActor.SetMapper(coneMapper)

    #text actor following camera

    text = vtk.vtkVectorText()

    text.SetText("Origin")

    textMapper = vtk.vtkPolyDataMapper()

    textMapper.SetInputConnection(text.GetOutputPort())

    textActor = vtk.vtkFollower()

    textActor.SetMapper(textMapper)

    ren = vtk.vtkRenderer()

    ren.AddActor(coneActor)

    ren.AddActor(textActor)

    textActor.SetCamera(ren.GetActiveCamera())

    renWin = vtk.vtkRenderWindow()

    renWin.AddRenderer(ren)

    return renWin

    开发者ID:holoviz,项目名称:panel,代码行数:27,

    示例6: create_ren_list

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def create_ren_list(self):

    """

    Create a list of the 4 renderers we use. One general view and 3 cartersian projections

    Returns:

    list: list of renderers

    """

    # viewport dimensions setup

    xmins = [0, 0.6, 0.6, 0.6]

    xmaxs = [0.6, 1, 1, 1]

    ymins = [0, 0, 0.33, 0.66]

    ymaxs = [1, 0.33, 0.66, 1]

    # create list of renderers, set vieport values

    ren_list = []

    for i in range(self.n_ren):

    # append each renderer to list of renderers

    ren_list.append(vtk.vtkRenderer())

    # add each renderer to window

    self.renwin.AddRenderer(ren_list[-1])

    # set viewport for each renderer

    ren_list[-1].SetViewport(xmins[i], ymins[i], xmaxs[i], ymaxs[i])

    return ren_list

    开发者ID:cgre-aachen,项目名称:gempy,代码行数:26,

    示例7: vis_csv_pcd

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def vis_csv_pcd(ind=1, color_style="monochrome"):

    pcd_arr = np.genfromtxt(

    os.path.join(params['base_dir'], "pcd/" + str(ind).zfill(params["file_name_digits"])) + ".csv", delimiter=",",

    skip_header=1)

    # actor = vis_3D_points(pcd_arr, color_style="intens")

    actor = vis_3D_points(pcd_arr, color_style=color_style)

    renderer = vtk.vtkRenderer()

    renderer.AddActor(actor)

    vis_with_renderer(renderer)

    开发者ID:mfxox,项目名称:ILCC,代码行数:11,

    示例8: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, parent, opt_engine):

    QVTKRenderWindowInteractor.__init__(self, parent)

    self.opt_engine = opt_engine

    self.renderer = vtk.vtkRenderer()

    self.GetRenderWindow().AddRenderer(self.renderer)

    self.interactor = self.GetRenderWindow().GetInteractor()

    self.create_actor()

    self.renderer.AddActor(self.actor)

    self.renderer.SetBackground(0, 0, 0)

    开发者ID:maxorange,项目名称:pix2vox,代码行数:13,

    示例9: QVTKRenderWidgetConeExample

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def QVTKRenderWidgetConeExample():

    """A simple example that uses the QVTKRenderWindowInteractor class."""

    # every QT app needs an app

    app = QtGui.QApplication(['QVTKRenderWindowInteractor'])

    # create the widget

    widget = QVTKRenderWindowInteractor()

    widget.Initialize()

    widget.Start()

    # if you dont want the 'q' key to exit comment this.

    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtkRenderer()

    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtkConeSource()

    cone.SetResolution(8)

    coneMapper = vtkPolyDataMapper()

    coneMapper.SetInput(cone.GetOutput())

    coneActor = vtkActor()

    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget

    widget.show()

    # start event processing

    app.exec_()

    开发者ID:mmolero,项目名称:pcloudpy,代码行数:33,

    示例10: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, parent=None):

    super(QVTKWidget, self).__init__(parent)

    self._enable_axis = False

    self._Iren.SetInteractorStyle (vtkInteractorStyleTrackballCamera ())

    self.renderer = vtkRenderer()

    self.renderer.GradientBackgroundOn()

    self.renderer.SetBackground2(255.0,255.0,255.0)

    self.renderer.SetBackground(37/255.0, 85/255.0,152/255.0)

    self.GetRenderWindow().AddRenderer(self.renderer)

    self.Initialize()

    self.Start()

    self.add_axes()

    开发者ID:mmolero,项目名称:pcloudpy,代码行数:16,

    示例11: display_from_actor

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def display_from_actor(actor):

    renderer = vtkRenderer()

    renderWindow = vtkRenderWindow()

    renderWindow.AddRenderer(renderer)

    renderer.AddActor(actor)

    # enable user interface interactor

    iren = vtkRenderWindowInteractor()

    iren.SetRenderWindow(renderWindow)

    iren.Initialize()

    renderWindow.Render()

    iren.Start()

    开发者ID:mmolero,项目名称:pcloudpy,代码行数:14,

    示例12: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, background=(0.15, 0.15, 0.15), total_time_steps=None, timer_rate=60, gif_file=None):

    self.ren = vtk.vtkRenderer()

    self.ren.SetBackground(background[0], background[1], background[2])

    self.ren_win = vtk.vtkRenderWindow()

    self.ren_win.AddRenderer(self.ren)

    self.iren = vtk.vtkRenderWindowInteractor()

    self.iren.SetRenderWindow(self.ren_win)

    self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

    self.actor_list = []

    self.mapper_list = []

    self.source_list = []

    self.screenshot_count = 0

    self.timer_rate = timer_rate

    self.gif_data = []

    if gif_file is not None:

    try:

    assert type(gif_file) is str

    except AssertionError:

    gif_file = str(gif_file)

    self.gif_file = gif_file

    else:

    self.gif_file = None

    if total_time_steps is not None:

    assert type(total_time_steps) is int

    self.timer_count = 0

    self.total_time_steps = total_time_steps

    开发者ID:adityadua24,项目名称:robopy,代码行数:29,

    示例13: check_depth_peeling

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def check_depth_peeling(number_of_peels=100, occlusion_ratio=0.0):

    """Check if depth peeling is available.

    Attempts to use depth peeling to see if it is available for the current

    environment. Returns ``True`` if depth peeling is available and has been

    successfully leveraged, otherwise ``False``.

    """

    # Try Depth Peeling with a basic scene

    source = vtk.vtkSphereSource()

    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(source.GetOutputPort())

    actor = vtk.vtkActor()

    actor.SetMapper(mapper)

    # requires opacity < 1

    actor.GetProperty().SetOpacity(0.5)

    renderer = vtk.vtkRenderer()

    renderWindow = vtk.vtkRenderWindow()

    renderWindow.AddRenderer(renderer)

    renderWindow.SetOffScreenRendering(True)

    renderWindow.SetAlphaBitPlanes(True)

    renderWindow.SetMultiSamples(0)

    renderer.AddActor(actor)

    renderer.SetUseDepthPeeling(True)

    renderer.SetMaximumNumberOfPeels(number_of_peels)

    renderer.SetOcclusionRatio(occlusion_ratio)

    renderWindow.Render()

    return renderer.GetLastRenderingUsedDepthPeeling() == 1

    开发者ID:pyvista,项目名称:pyvista,代码行数:30,

    示例14: QVTKRenderWidgetConeExample

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def QVTKRenderWidgetConeExample():

    """A simple example that uses the QVTKRenderWindowInteractor class."""

    # every QT app needs an app

    app = QApplication(['QVTKRenderWindowInteractor'])

    # create the widget

    widget = QVTKRenderWindowInteractor()

    widget.Initialize()

    widget.Start()

    # if you don't want the 'q' key to exit comment this.

    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtk.vtkRenderer()

    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()

    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()

    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()

    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget

    widget.show()

    # start event processing

    app.exec_()

    开发者ID:pyCGNS,项目名称:pyCGNS,代码行数:33,

    示例15: visualize_prediction

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def visualize_prediction(pointcloud, colors, poses=None, renwin=None):

    """ render point cloud and cameras """

    renderer = vtk.vtkRenderer()

    renderer.SetBackground(0, 0, 0)

    pointcloud_actor = create_pointcloud_actor(points=pointcloud, colors=colors)

    pointcloud_actor.GetProperty().SetPointSize(2)

    renderer.AddActor(pointcloud_actor)

    for pose in poses:

    R, t = pose[:3, :3], pose[:3, 3]

    cam_actor = create_camera_actor(R,t)

    cam_actor.GetProperty().SetColor((255, 255, 0))

    renderer.AddActor(cam_actor)

    camera = vtk.vtkCamera()

    camera.SetPosition((1, -1, -2));

    camera.SetViewUp((0, -1, 0));

    camera.SetFocalPoint((0, 0, 2));

    renderer.SetActiveCamera(camera)

    renwin = vtk.vtkRenderWindow()

    renwin.SetWindowName("Point Cloud Viewer")

    renwin.SetSize(800,600)

    renwin.AddRenderer(renderer)

    # An interactor

    interactor = vtk.vtkRenderWindowInteractor()

    interstyle = vtk.vtkInteractorStyleTrackballCamera()

    interactor.SetInteractorStyle(interstyle)

    interactor.SetRenderWindow(renwin)

    # Render and interact

    renwin.Render()

    interactor.Initialize()

    interactor.Start()

    开发者ID:princeton-vl,项目名称:DeepV2D,代码行数:40,

    示例16: run

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def run(self):

    renderer = vtk.vtkRenderer()

    renderer.SetBackground(0, 0, 0)

    camera = vtk.vtkCamera()

    camera.SetPosition((1, -1, -2));

    camera.SetViewUp((0, -1, 0));

    camera.SetFocalPoint((0, 0, 2));

    renderer.SetActiveCamera(camera)

    renwin = vtk.vtkRenderWindow()

    renwin.SetWindowName("Point Cloud Viewer")

    renwin.SetSize(800,600)

    renwin.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()

    interstyle = vtk.vtkInteractorStyleTrackballCamera()

    interactor.SetInteractorStyle(interstyle)

    interactor.SetRenderWindow(renwin)

    interactor.Initialize()

    cb = vtkTimerCallback(self.cinematic, self.render_path, self.clear_points)

    cb.queue = self.queue

    interactor.AddObserver('TimerEvent', cb.execute)

    timerId = interactor.CreateRepeatingTimer(100);

    #start the interaction and timer

    interactor.Start()

    开发者ID:princeton-vl,项目名称:DeepV2D,代码行数:32,

    示例17: make_ren_win

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def make_ren_win(self):

    import vtk

    ren = vtk.vtkRenderer()

    ren_win = vtk.vtkRenderWindow()

    ren_win.AddRenderer(ren)

    return ren_win

    开发者ID:holoviz,项目名称:panel,代码行数:8,

    示例18: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self):

    self.ren = vtk.vtkRenderer()

    self.renWin = vtk.vtkRenderWindow()

    self.renWin.AddRenderer(self.ren)

    self.iren = vtk.vtkRenderWindowInteractor()

    self.iren.SetRenderWindow(self.renWin)

    self.lut = vtk.vtkLookupTable()

    self.lut.SetHueRange(0.6, 0.6)

    self.lut.SetSaturationRange(.5, .5)

    self.lut.SetValueRange(0.2, 1.0)

    self.lut.SetNumberOfColors(256)

    self.lut.Build()

    开发者ID:cwant,项目名称:tessagon,代码行数:15,

    示例19: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, threadLock, actorWrapper, axis=True,):

    super(VTKVisualisation, self).__init__()

    self.threadLock = threadLock

    self.ren = vtk.vtkRenderer()

    self.ren.AddActor(actorWrapper.actor)

    self.axesActor = vtk.vtkAxesActor()

    self.axesActor.AxisLabelsOff()

    self.axesActor.SetTotalLength(1, 1, 1)

    self.ren.AddActor(self.axesActor)

    self.renWin = vtk.vtkRenderWindow()

    self.renWin.AddRenderer(self.ren)

    ## IREN

    self.iren = vtk.vtkRenderWindowInteractor()

    self.iren.SetRenderWindow(self.renWin)

    self.iren.Initialize()

    self.style = vtk.vtkInteractorStyleTrackballCamera()

    self.iren.SetInteractorStyle(self.style)

    self.iren.AddObserver("TimerEvent", self.update_visualisation)

    dt = 30 # ms

    timer_id = self.iren.CreateRepeatingTimer(dt)

    开发者ID:toinsson,项目名称:pyrealsense,代码行数:29,

    示例20: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, h=800, w=600):

    self.renderer = vtk.vtkRenderer()

    self.renderer.SetBackground(0.1, 0.1, 0.1)

    # Add axes

    axes = vtk.vtkAxesActor()

    axes.GetXAxisCaptionActor2D().SetHeight(0.05)

    axes.GetYAxisCaptionActor2D().SetHeight(0.05)

    axes.GetZAxisCaptionActor2D().SetHeight(0.05)

    axes.SetCylinderRadius(0.03)

    axes.SetShaftTypeToCylinder()

    self.renderer.AddActor(axes)

    # Add render window

    self.renwin = vtk.vtkRenderWindow()

    self.renwin.SetWindowName("Point Cloud Viewer")

    self.renwin.SetSize(h, w)

    self.renwin.AddRenderer(self.renderer)

    # An interactor

    self.interactor = vtk.vtkRenderWindowInteractor()

    interstyle = vtk.vtkInteractorStyleTrackballCamera()

    self.interactor.SetInteractorStyle(interstyle)

    self.interactor.SetRenderWindow(self.renwin)

    self.camera_actors = []

    开发者ID:sfu-gruvi-3dv,项目名称:sanet_relocal_demo,代码行数:28,

    示例21: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, parent, opt_engine):

    QVTKRenderWindowInteractor.__init__(self, parent)

    self.opt_engine = opt_engine

    self.resetCamera = True

    self.renderer = vtk.vtkRenderer()

    self.GetRenderWindow().AddRenderer(self.renderer)

    self.interactor = self.GetRenderWindow().GetInteractor()

    self.create_actor()

    self.renderer.AddActor(self.actor)

    self.renderer.SetBackground(0, 0, 0)

    开发者ID:maxorange,项目名称:voxel-dcgan,代码行数:14,

    示例22: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, renderer=None, parent=None):

    # Every QT app needs a QApplication

    self.app = QApplication.instance()

    if self.app is None:

    self.app = QApplication(sys.argv)

    # Create the widget

    if renderer is None:

    self.renderer = vtk.vtkRenderer()

    else:

    self.renderer = renderer

    self.widget = QVTKRenderWindowInteractor(parent)

    self.widget.Initialize

    self.widget.Start()

    # Set the interactor style

    self.widget.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

    # Get the render window from the widget

    self.renderWindow = self.widget.GetRenderWindow()

    self.renderWindow.AddRenderer(self.renderer)

    # show the widget

    self.widget.show()

    开发者ID:poodarchu,项目名称:Det3D,代码行数:29,

    示例23: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def __init__(self, parent=None):

    "Create a wiget with a VTK Visualizer Control in it"

    self.pointObjects = []

    self.renderer = vtk.vtkRenderer()

    self.renderWidget = RenderWidget(self.renderer, parent)

    self.renderWindow = self.renderWidget.renderWindow

    self.widget = self.renderWidget.widget

    开发者ID:poodarchu,项目名称:Det3D,代码行数:9,

    示例24: QVTKRenderWidgetConeExample

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def QVTKRenderWidgetConeExample():

    """A simple example that uses the QVTKRenderWindowInteractor class."""

    # every QT app needs an app

    app = QApplication(["QVTKRenderWindowInteractor"])

    # create the widget

    widget = QVTKRenderWindowInteractor()

    widget.Initialize()

    widget.Start()

    # if you dont want the 'q' key to exit comment this.

    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtk.vtkRenderer()

    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()

    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()

    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()

    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget

    widget.show()

    # start event processing

    app.exec_()

    开发者ID:poodarchu,项目名称:Det3D,代码行数:33,

    示例25: create_render_window

    ​点赞 4

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def create_render_window(actors, callbacks, **kwargs):

    """ Creates VTK render window with an interactor.

    :param actors: list of VTK actors

    :type actors: list, tuple

    :param callbacks: callback functions for registering custom events

    :type callbacks: dict

    """

    # Get keyword arguments

    figure_size = kwargs.get('figure_size', (800, 600))

    camera_position = kwargs.get('camera_position', (0, 0, 100))

    # Find camera focal point

    center_points = []

    for actor in actors:

    center_points.append(actor.GetCenter())

    camera_focal_point = linalg.vector_mean(*center_points)

    # Create camera

    camera = vtk.vtkCamera()

    camera.SetPosition(*camera_position)

    camera.SetFocalPoint(*camera_focal_point)

    # Create renderer

    renderer = vtk.vtkRenderer()

    renderer.SetActiveCamera(camera)

    renderer.SetBackground(1.0, 1.0, 1.0)

    # Add actors to the scene

    for actor in actors:

    renderer.AddActor(actor)

    # Render window

    render_window = vtk.vtkRenderWindow()

    render_window.AddRenderer(renderer)

    render_window.SetSize(*figure_size)

    # Render window interactor

    window_interactor = vtk.vtkRenderWindowInteractor()

    window_interactor.SetRenderWindow(render_window)

    # Add event observers

    for cb in callbacks:

    window_interactor.AddObserver(cb, callbacks[cb][0], callbacks[cb][1]) # cb name, cb function ref, cb priority

    # Render actors

    render_window.Render()

    # Set window name after render() is called

    render_window.SetWindowName("geomdl")

    # Use trackball camera

    interactor_style = vtk.vtkInteractorStyleTrackballCamera()

    window_interactor.SetInteractorStyle(interactor_style)

    # Start interactor

    window_interactor.Start()

    # Return window interactor instance

    return window_interactor

    开发者ID:orbingol,项目名称:NURBS-Python,代码行数:62,

    示例26: show_pcd_ndarray

    ​点赞 4

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def show_pcd_ndarray(array_data, color_arr=[0, 255, 0]):

    all_rows = array_data.shape[0]

    Colors = vtk.vtkUnsignedCharArray()

    Colors.SetNumberOfComponents(3)

    Colors.SetName("Colors")

    Points = vtk.vtkPoints()

    Vertices = vtk.vtkCellArray()

    for k in xrange(all_rows):

    point = array_data[k, :]

    id = Points.InsertNextPoint(point[0], point[1], point[2])

    Vertices.InsertNextCell(1)

    Vertices.InsertCellPoint(id)

    if vtk.VTK_MAJOR_VERSION > 6:

    Colors.InsertNextTuple(color_arr)

    else:

    Colors.InsertNextTupleValue(color_arr)

    dis_tmp = np.sqrt((point ** 2).sum(0))

    # Colors.InsertNextTupleValue([0,255-dis_tmp/max_dist*255,0])

    # Colors.InsertNextTupleValue([255-abs(point[0]/x_max*255),255-abs(point[1]/y_max*255),255-abs(point[2]/z_max*255)])

    # Colors.InsertNextTupleValue([255-abs(point[0]/x_max*255),255,255])

    polydata = vtk.vtkPolyData()

    polydata.SetPoints(Points)

    polydata.SetVerts(Vertices)

    polydata.GetPointData().SetScalars(Colors)

    polydata.Modified()

    mapper = vtk.vtkPolyDataMapper()

    if vtk.VTK_MAJOR_VERSION <= 5:

    mapper.SetInput(polydata)

    else:

    mapper.SetInputData(polydata)

    mapper.SetColorModeToDefault()

    actor = vtk.vtkActor()

    actor.SetMapper(mapper)

    actor.GetProperty().SetPointSize(5)

    # Renderer

    renderer = vtk.vtkRenderer()

    renderer.AddActor(actor)

    renderer.SetBackground(.2, .3, .4)

    renderer.ResetCamera()

    # Render Window

    renderWindow = vtk.vtkRenderWindow()

    renderWindow.AddRenderer(renderer)

    # Interactor

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()

    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Begin Interaction

    renderWindow.Render()

    renderWindowInteractor.Start()

    # determine whether a segment is the potential chessboard's point cloud

    开发者ID:mfxox,项目名称:ILCC,代码行数:62,

    示例27: vtk_basic

    ​点赞 4

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkRenderer [as 别名]

    def vtk_basic( actors, embed=False, magnification=1.0 ):

    """

    Create a window, renderer, interactor, add the actors and start the thing

    Parameters

    ----------

    actors : list of vtkActors

    Returns

    -------

    nothing

    """

    # create a rendering window and renderer

    ren = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()

    renWin.AddRenderer(ren)

    renWin.SetSize(600,600)

    # ren.SetBackground( 1, 1, 1)

    # create a renderwindowinteractor

    iren = vtk.vtkRenderWindowInteractor()

    iren.SetRenderWindow(renWin)

    for a in actors:

    move( a, np.dot(Ry(-180),Rx(-180)) )

    # assign actor to the renderer

    ren.AddActor(a )

    # render

    renWin.Render()

    if embed:

    renWin.SetSize(300,300)

    grabber = vtk.vtkWindowToImageFilter()

    grabber.SetInput( renWin )

    grabber.SetMagnification( magnification )

    grabber.Update()

    writer = vtk.vtkPNGWriter()

    writer.SetInput( grabber.GetOutput() )

    writer.SetFileName( "screenshot.png" )

    writer.Write()

    return display.Image("screenshot.png")

    else:

    # enable user interface interactor

    iren.Initialize()

    iren.Start()

    开发者ID:curiale,项目名称:Medical-Image-Analysis-IPython-Tutorials,代码行数:52,

    注:本文中的vtk.vtkRenderer方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

    展开全文
    weixin_39517797 2020-11-24 04:20:11
  • 本文整理汇总了Pythonvtk.vtkTransform方法的典型用法代码示例。如果您正苦于以下问题:Python vtk.vtkTransform方法的具体用法?Python vtk.vtkTransform怎么用?Python vtk.vtkTransform使用的例子?那么恭喜您,...

    本文整理汇总了Python中vtk.vtkTransform方法的典型用法代码示例。如果您正苦于以下问题:Python vtk.vtkTransform方法的具体用法?Python vtk.vtkTransform怎么用?Python vtk.vtkTransform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块vtk的用法示例。

    在下文中一共展示了vtk.vtkTransform方法的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

    示例1: getDepthMapData

    ​点赞 7

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getDepthMapData(self, viewId):

    mapId = self.reader.GetCurrentMapId(viewId)

    if mapId < 0:

    return None, None

    depthImage = vtk.vtkImageData()

    transform = vtk.vtkTransform()

    self.reader.GetDataForMapId(viewId, mapId, depthImage, transform)

    dims = depthImage.GetDimensions()

    d = vnp.getNumpyFromVtk(depthImage, 'ImageScalars')

    d = d.reshape(dims[1], dims[0])

    t = np.array([[transform.GetMatrix().GetElement(r, c) for c in range(4)] for r in range(4)])

    return d, t

    开发者ID:RobotLocomotion,项目名称:director,代码行数:18,

    示例2: set_scale

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True):

    """Scale all the datasets in the scene.

    Scaling in performed independently on the X, Y and Z axis.

    A scale of zero is illegal and will be replaced with one.

    """

    if xscale is None:

    xscale = self.scale[0]

    if yscale is None:

    yscale = self.scale[1]

    if zscale is None:

    zscale = self.scale[2]

    self.scale = [xscale, yscale, zscale]

    # Update the camera's coordinate system

    transform = vtk.vtkTransform()

    transform.Scale(xscale, yscale, zscale)

    self.camera.SetModelTransformMatrix(transform.GetMatrix())

    self.parent.render()

    if reset_camera:

    self.update_bounds_axes()

    self.reset_camera()

    self.Modified()

    开发者ID:pyvista,项目名称:pyvista,代码行数:26,

    示例3: CameraModeToObjectAxis

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def CameraModeToObjectAxis(self, axis):

    camera = self._parent._vtkren.GetActiveCamera()

    transform = vtk.vtkTransform()

    transform.Identity()

    (pt, center) = self.ComputeDisplayCenter()

    transform.Translate(center[0], center[1], center[2])

    dx = self._parent._iren.GetLastEventPosition()[0] - self._parent._iren.GetEventPosition()[0]

    dy = self._parent._iren.GetLastEventPosition()[1] - self._parent._iren.GetEventPosition()[1]

    camera.OrthogonalizeViewUp()

    size = self._parent._vtkren.GetSize()

    transform.RotateWXYZ(360.0 * dx / size[0], axis[0], axis[1], axis[2])

    transform.RotateWXYZ(360.0 * dy / size[1], axis[0], axis[1], axis[2])

    transform.Translate(-center[0], -center[1], -center[2])

    camera.ApplyTransform(transform)

    camera.OrthogonalizeViewUp()

    self._parent._vtkren.ResetCameraClippingRange()

    self._parent._vtkren.GetRenderWindow().Render()

    开发者ID:pyCGNS,项目名称:pyCGNS,代码行数:19,

    示例4: CameraModeToObjectAllAxis

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def CameraModeToObjectAllAxis(self):

    camera = self._parent._vtkren.GetActiveCamera()

    transform = vtk.vtkTransform()

    transform.Identity()

    (pt, center) = self.ComputeDisplayCenter()

    transform.Translate(center[0], center[1], center[2])

    dx = self._parent._iren.GetLastEventPosition()[0] - self._parent._iren.GetEventPosition()[0]

    dy = self._parent._iren.GetLastEventPosition()[1] - self._parent._iren.GetEventPosition()[1]

    camera.OrthogonalizeViewUp()

    viewUp = camera.GetViewUp()

    size = self._parent._vtkren.GetSize()

    transform.RotateWXYZ(360.0 * dx / size[0], viewUp[0], viewUp[1], viewUp[2])

    v2 = [0, 0, 0]

    vtk.vtkMath().Cross(camera.GetDirectionOfProjection(), viewUp, v2)

    transform.RotateWXYZ(-360.0 * dy / size[1], v2[0], v2[1], v2[2])

    transform.Translate(-center[0], -center[1], -center[2])

    camera.ApplyTransform(transform)

    camera.OrthogonalizeViewUp()

    self._parent._vtkren.ResetCameraClippingRange()

    self._parent._vtkren.GetRenderWindow().Render()

    开发者ID:pyCGNS,项目名称:pyCGNS,代码行数:22,

    示例5: Roll

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def Roll(self, *args):

    camera = self._parent._vtkren.GetActiveCamera()

    transform = vtk.vtkTransform()

    pos = camera.GetPosition()

    fp = camera.GetFocalPoint()

    axis = [fp[i] - pos[i] for i in range(3)]

    (DisplayCenter, Center) = self.ComputeDisplayCenter()

    x1 = self._parent._iren.GetLastEventPosition()[0] - int(DisplayCenter[0])

    x2 = self._parent._iren.GetEventPosition()[0] - int(DisplayCenter[0])

    y1 = self._parent._iren.GetLastEventPosition()[1] - int(DisplayCenter[1])

    y2 = self._parent._iren.GetEventPosition()[1] - int(DisplayCenter[1])

    zCross = x1 * y2 - y1 * x2

    zCross = float(zCross)

    angle = vtk.vtkMath().DegreesFromRadians(zCross / (math.sqrt(float(x1 * x1 + y1 * y1)) *

    math.sqrt(float(x2 * x2 + y2 * y2))))

    transform.Identity()

    transform.Translate(Center[0], Center[1], Center[2])

    transform.RotateWXYZ(angle, axis[0], axis[1], axis[2])

    transform.Translate(-Center[0], -Center[1], -Center[2])

    camera.ApplyTransform(transform)

    camera.OrthogonalizeViewUp()

    self._parent._vtkren.ResetCameraClippingRange()

    self._parent._iren.Render()

    # -----------------------------------------------------------------------------

    开发者ID:pyCGNS,项目名称:pyCGNS,代码行数:27,

    示例6: RequestData

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def RequestData(self, request, inInfo, outInfo):

    """Used by pipeline to generate output"""

    # Get input/output of Proxy

    pdi = self.GetInputData(inInfo, 0, 0)

    # Get number of points

    pdo = self.GetOutputData(outInfo, 0)

    #### Perfrom task ####

    filt = vtk.vtkTransformFilter()

    trans = vtk.vtkTransform()

    trans.Scale(self.get_conversion(), self.get_conversion(), self.get_conversion())

    filt.SetTransform(trans)

    filt.SetInputDataObject(pdi)

    filt.Update()

    scaled = filt.GetOutputDataObject(0)

    pdo.DeepCopy(scaled)

    return 1

    开发者ID:OpenGeoVis,项目名称:PVGeo,代码行数:18,

    示例7: getFootFramesFromReferenceFrame

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getFootFramesFromReferenceFrame(referenceFrame, stanceWidth, stanceRotation, stanceOffset):

    footHeight=0.0745342

    ref = vtk.vtkTransform()

    ref.SetMatrix(referenceFrame.GetMatrix())

    stanceFrame = vtk.vtkTransform()

    stanceFrame.PostMultiply()

    stanceFrame.RotateZ(stanceRotation)

    stanceFrame.Translate(stanceOffset)

    stanceFrame.Concatenate(ref)

    lfootFrame = vtk.vtkTransform()

    lfootFrame.PostMultiply()

    lfootFrame.Translate(0, stanceWidth/2.0, footHeight)

    lfootFrame.Concatenate(stanceFrame)

    rfootFrame = vtk.vtkTransform()

    rfootFrame.PostMultiply()

    rfootFrame.Translate(0, -stanceWidth/2.0, footHeight)

    rfootFrame.Concatenate(stanceFrame)

    return stanceFrame, lfootFrame, rfootFrame

    开发者ID:RobotLocomotion,项目名称:director,代码行数:26,

    示例8: getDrillMesh

    ​点赞 6

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getDrillMesh(applyBitOffset=False):

    button = np.array([0.007, -0.035, -0.06])

    drillMesh = ioUtils.readPolyData(os.path.join(app.getDRCBase(), 'software/models/otdf/dewalt_button.obj'))

    if applyBitOffset:

    t = vtk.vtkTransform()

    t.Translate(0.01, 0.0, 0.0)

    drillMesh = transformPolyData(drillMesh, t)

    d = DebugData()

    d.addPolyData(drillMesh)

    d.addSphere(button, radius=0.005, color=[0,1,0])

    d.addLine([0.0,0.0,0.155], [0.0, 0.0, 0.14], radius=0.001, color=[0,1,0])

    return shallowCopy(d.getPolyData())

    开发者ID:RobotLocomotion,项目名称:director,代码行数:18,

    示例9: test_translate_should_match_vtk_transformation

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def test_translate_should_match_vtk_transformation(rotate_amounts, translate_amounts, grid):

    trans = vtk.vtkTransform()

    trans.RotateWXYZ(0, *rotate_amounts)

    trans.Translate(translate_amounts)

    trans.Update()

    grid_a = grid.copy()

    grid_b = grid.copy()

    grid_c = grid.copy()

    grid_a.transform(trans)

    grid_b.transform(trans.GetMatrix())

    grid_c.transform(pyvista.trans_from_matrix(trans.GetMatrix()))

    assert np.allclose(grid_a.points, grid_b.points, equal_nan=True)

    assert np.allclose(grid_a.points, grid_c.points, equal_nan=True)

    开发者ID:pyvista,项目名称:pyvista,代码行数:16,

    示例10: test_rotate_should_match_vtk_rotation

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def test_rotate_should_match_vtk_rotation(angle, axis, grid):

    trans = vtk.vtkTransform()

    getattr(trans, 'Rotate{}'.format(axis.upper()))(angle)

    trans.Update()

    trans_filter = vtk.vtkTransformFilter()

    trans_filter.SetTransform(trans)

    trans_filter.SetInputData(grid)

    trans_filter.Update()

    grid_a = pyvista.UnstructuredGrid(trans_filter.GetOutput())

    grid_b = grid.copy()

    getattr(grid_b, 'rotate_{}'.format(axis))(angle)

    assert np.allclose(grid_a.points, grid_b.points, equal_nan=True)

    开发者ID:pyvista,项目名称:pyvista,代码行数:16,

    示例11: transform

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def transform(self, trans):

    """Compute a transformation in place using a 4x4 transform.

    Parameters

    ----------

    trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray

    Accepts a vtk transformation object or a 4x4 transformation matrix.

    """

    if isinstance(trans, vtk.vtkMatrix4x4):

    t = pyvista.trans_from_matrix(trans)

    elif isinstance(trans, vtk.vtkTransform):

    t = pyvista.trans_from_matrix(trans.GetMatrix())

    elif isinstance(trans, np.ndarray):

    if trans.ndim != 2:

    raise ValueError('Transformation array must be 4x4')

    elif trans.shape[0] != 4 or trans.shape[1] != 4:

    raise ValueError('Transformation array must be 4x4')

    t = trans

    else:

    raise TypeError('Input transform must be either:\n'

    '\tvtk.vtkMatrix4x4\n'

    '\tvtk.vtkTransform\n'

    '\t4x4 np.ndarray\n')

    x = (self.points*t[0, :3]).sum(1) + t[0, -1]

    y = (self.points*t[1, :3]).sum(1) + t[1, -1]

    z = (self.points*t[2, :3]).sum(1) + t[2, -1]

    # overwrite points

    self.points[:, 0] = x

    self.points[:, 1] = y

    self.points[:, 2] = z

    开发者ID:pyvista,项目名称:pyvista,代码行数:35,

    示例12: getActorCircle

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getActorCircle(radius_inner=100, radius_outer=99, color=(1,0,0)):

    """"""

    # create source

    source = vtk.vtkDiskSource()

    source.SetInnerRadius(radius_inner)

    source.SetOuterRadius(radius_outer)

    source.SetRadialResolution(100)

    source.SetCircumferentialResolution(100)

    # Transformer

    transform = vtk.vtkTransform()

    transform.RotateWXYZ(90, 1, 0, 0)

    transformFilter = vtk.vtkTransformPolyDataFilter()

    transformFilter.SetTransform(transform)

    transformFilter.SetInputConnection(source.GetOutputPort())

    transformFilter.Update()

    # mapper

    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(transformFilter.GetOutputPort())

    # actor

    actor = vtk.vtkActor()

    actor.GetProperty().SetColor(color)

    actor.SetMapper(mapper)

    return actor

    开发者ID:VisualComputingInstitute,项目名称:3d-semantic-segmentation,代码行数:29,

    示例13: _repr

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def _repr(self, indent=4):

    if isinstance(self, FieldContainer):

    return _fields_repr(self, indent)

    if isinstance(self, vtk.vtkTransform):

    return _transform_repr(self, indent)

    if isinstance(self, dict):

    return _dict_repr(self, indent)

    if isinstance(self, list) and len(self) and not isinstance(self[0], (int, float)):

    return _list_repr(self, indent)

    else:

    return repr(self)

    开发者ID:RobotLocomotion,项目名称:director,代码行数:13,

    示例14: computeAToB

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def computeAToB(a,b):

    t = vtk.vtkTransform()

    t.PostMultiply()

    t.Concatenate(b)

    t.Concatenate(a.GetLinearInverse())

    tt = vtk.vtkTransform()

    tt.SetMatrix(t.GetMatrix())

    return tt

    开发者ID:RobotLocomotion,项目名称:director,代码行数:11,

    示例15: lockAffordanceToHand

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def lockAffordanceToHand(aff, hand='l_hand'):

    linkFrame = getLinkFrame(hand)

    affT = aff.actor.GetUserTransform()

    if not hasattr(aff, 'handToAffT') or not aff.handToAffT:

    aff.handToAffT = computeAToB(linkFrame, affT)

    t = vtk.vtkTransform()

    t.PostMultiply()

    t.Concatenate(aff.handToAffT)

    t.Concatenate(linkFrame)

    aff.actor.GetUserTransform().SetMatrix(t.GetMatrix())

    开发者ID:RobotLocomotion,项目名称:director,代码行数:15,

    示例16: applyICP

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def applyICP(source, target):

    icp = vtk.vtkIterativeClosestPointTransform()

    icp.SetSource(source)

    icp.SetTarget(target)

    icp.GetLandmarkTransform().SetModeToRigidBody()

    icp.Update()

    t = vtk.vtkTransform()

    t.SetMatrix(icp.GetMatrix())

    return t

    开发者ID:RobotLocomotion,项目名称:director,代码行数:12,

    示例17: addDrillAffordance

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def addDrillAffordance():

    drillMesh = getDrillMesh()

    aff = showPolyData(drillMesh, 'drill', cls=FrameAffordanceItem, visible=True)

    t = vtk.vtkTransform()

    t.PostMultiply()

    aff.actor.SetUserTransform(t)

    showFrame(t, 'drill frame', parent=aff, visible=False).addToView(app.getDRCView())

    params = getDrillAffordanceParams(np.array(t.GetPosition()), [1,0,0], [0,1,0], [0,0,1])

    aff.setAffordanceParams(params)

    aff.updateParamsFromActorTransform()

    aff.addToView(app.getDRCView())

    return aff

    开发者ID:RobotLocomotion,项目名称:director,代码行数:17,

    示例18: getLinkFrame

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getLinkFrame(linkName):

    robotStateModel = om.findObjectByName('robot state model')

    assert robotStateModel

    t = vtk.vtkTransform()

    robotStateModel.model.getLinkToWorld(linkName, t)

    return t

    开发者ID:RobotLocomotion,项目名称:director,代码行数:8,

    示例19: getDrillInHandOffset

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getDrillInHandOffset(zRotation=0.0, zTranslation=0.0, xTranslation=0.0, yTranslation=0.0,flip=False):

    drillOffset = vtk.vtkTransform()

    drillOffset.PostMultiply()

    if flip:

    drillOffset.RotateY(180)

    drillOffset.RotateZ(zRotation)

    drillOffset.RotateY(-90)

    #drillOffset.Translate(0, 0.09, zTranslation - 0.015)

    #drillOffset.Translate(zTranslation - 0.015, 0.035 + xTranslation, 0.0)

    drillOffset.Translate(zTranslation, xTranslation, 0.0 + yTranslation)

    return drillOffset

    开发者ID:RobotLocomotion,项目名称:director,代码行数:14,

    示例20: segmentDebrisWallManual

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def segmentDebrisWallManual(point1, point2):

    p1, p2 = point1, point2

    d = DebugData()

    d.addSphere(p1, radius=0.01)

    d.addSphere(p2, radius=0.01)

    d.addLine(p1, p2)

    edgeObj = updatePolyData(d.getPolyData(), 'debris plane edge', visible=True)

    edgeObj.points = [p1, p2]

    xaxis = p2 - p1

    xaxis /= np.linalg.norm(xaxis)

    zaxis = np.array([0.0, 0.0, 1.0])

    yaxis = np.cross(zaxis, xaxis)

    t = getTransformFromAxes(xaxis, yaxis, zaxis)

    t.PostMultiply()

    t.Translate(p1)

    updateFrame(t, 'debris plane frame', parent=edgeObj, visible=False)

    refFrame = vtk.vtkTransform()

    refFrame.PostMultiply()

    refFrame.SetMatrix(t.GetMatrix())

    refFrame.Translate(-xaxis + yaxis + zaxis*20.0)

    updateFrame(refFrame, 'debris reference frame', parent=edgeObj, visible=False)

    开发者ID:RobotLocomotion,项目名称:director,代码行数:29,

    示例21: getFrame

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getFrame(self, name, relativeTo='local'):

    t = vtk.vtkTransform()

    self.reader.GetTransform(name, relativeTo, self.reader.GetCurrentScanTime(), t)

    return t

    开发者ID:RobotLocomotion,项目名称:director,代码行数:6,

    示例22: getActorCircle

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def getActorCircle(radius_inner=100, radius_outer=99, color=(1, 0, 0)):

    """"""

    # create source

    source = vtk.vtkDiskSource()

    source.SetInnerRadius(radius_inner)

    source.SetOuterRadius(radius_outer)

    source.SetRadialResolution(100)

    source.SetCircumferentialResolution(100)

    # Transformer

    transform = vtk.vtkTransform()

    transform.RotateWXYZ(90, 1, 0, 0)

    transformFilter = vtk.vtkTransformPolyDataFilter()

    transformFilter.SetTransform(transform)

    transformFilter.SetInputConnection(source.GetOutputPort())

    transformFilter.Update()

    # mapper

    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(transformFilter.GetOutputPort())

    # actor

    actor = vtk.vtkActor()

    actor.GetProperty().SetColor(color)

    actor.SetMapper(mapper)

    return actor

    开发者ID:lightaime,项目名称:deep_gcns_torch,代码行数:29,

    示例23: __init__

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def __init__(self, viewID=0, orientation=None):

    slicer.app.processEvents()

    widget = slicer.app.layoutManager().threeDWidget(viewID)

    view = widget.threeDView()

    if orientation is not None:

    camera = view.interactorStyle().GetCameraNode().GetCamera()

    cameraToWorld = vtk.vtkTransform()

    cameraToWorld.RotateX(90)

    cameraToWorld.RotateY(180)

    cameraToWorld.RotateY(orientation[2])

    cameraToWorld.RotateX(orientation[1])

    cameraToWorld.RotateZ(orientation[0])

    cameraToWorld.Translate(0, 0, camera.GetDistance())

    viewUp = [0,1,0,0]

    slicer.vtkAddonMathUtilities.GetOrientationMatrixColumn(cameraToWorld.GetMatrix(), 1, viewUp)

    position = cameraToWorld.GetPosition()

    focalPoint = camera.GetFocalPoint()

    camera.SetPosition(focalPoint[0]+position[0], focalPoint[1]+position[1], focalPoint[2]+position[2])

    camera.SetViewUp(viewUp[0:3])

    camera.OrthogonalizeViewUp()

    view.forceRender()

    screenshot = view.grab()

    bArray = qt.QByteArray()

    buffer = qt.QBuffer(bArray)

    buffer.open(qt.QIODevice.WriteOnly)

    #screenshot.save(buffer, "PNG")

    screenshot.save(buffer, "JPG")

    self.dataValue = bArray.toBase64().data().decode()

    #dataType = "image/png"

    self.dataType = "image/jpeg"

    开发者ID:Slicer,项目名称:SlicerJupyter,代码行数:32,

    示例24: _array2vtkTransform

    ​点赞 5

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def _array2vtkTransform(self, arr):

    T = vtk.vtkTransform()

    matrix = vtk.vtkMatrix4x4()

    for i in range(0, 4):

    for j in range(0, 4):

    matrix.SetElement(i, j, arr[i, j])

    T.SetMatrix(matrix)

    return T

    开发者ID:poodarchu,项目名称:Det3D,代码行数:10,

    示例25: vis_with_renderer

    ​点赞 4

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def vis_with_renderer(renderer):

    # Renderer

    # renderer.SetBackground(.2, .3, .4)

    renderer.SetBackground(1, 1, 1)

    renderer.ResetCamera()

    transform = vtk.vtkTransform()

    transform.Translate(1.0, 0.0, 0.0)

    axes = vtk.vtkAxesActor()

    renderer.AddActor(axes)

    # Render Window

    renderWindow = vtk.vtkRenderWindow()

    renderWindow.AddRenderer(renderer)

    # Interactor

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()

    renderWindowInteractor.SetRenderWindow(renderWindow)

    def get_camera_info(obj, ev):

    if renderWindowInteractor.GetKeyCode() == "s":

    w2if = vtk.vtkWindowToImageFilter()

    w2if.SetInput(renderWindow)

    w2if.Update()

    writer = vtk.vtkPNGWriter()

    writer.SetFileName("screenshot.png")

    if vtk.VTK_MAJOR_VERSION == 5:

    writer.SetInput(w2if.GetOutput())

    else:

    writer.SetInputData(w2if.GetOutput())

    writer.Write()

    print "screenshot saved"

    style = vtk.vtkInteractorStyleSwitch()

    renderWindowInteractor.SetInteractorStyle(style)

    # style.SetCurrentStyleToTrackballActor()

    style.SetCurrentStyleToTrackballCamera()

    # Begin Interaction

    renderWindowInteractor.AddObserver(vtk.vtkCommand.KeyPressEvent, get_camera_info, 1)

    renderWindow.Render()

    renderWindowInteractor.Start()

    开发者ID:mfxox,项目名称:ILCC,代码行数:46,

    示例26: segmentTruss

    ​点赞 4

    # 需要导入模块: import vtk [as 别名]

    # 或者: from vtk import vtkTransform [as 别名]

    def segmentTruss(point1, point2):

    edge = point2 - point1

    edgeLength = np.linalg.norm(edge)

    stanceOffset = [-0.42, 0.0, 0.0]

    stanceYaw = 0.0

    d = DebugData()

    p1 = [0.0, 0.0, 0.0]

    p2 = -np.array([0.0, -1.0, 0.0]) * edgeLength

    d.addSphere(p1, radius=0.02)

    d.addSphere(p2, radius=0.02)

    d.addLine(p1, p2)

    stanceTransform = vtk.vtkTransform()

    stanceTransform.PostMultiply()

    stanceTransform.Translate(stanceOffset)

    #stanceTransform.RotateZ(stanceYaw)

    geometry = transformPolyData(d.getPolyData(), stanceTransform.GetLinearInverse())

    yaxis = edge/edgeLength

    zaxis = [0.0, 0.0, 1.0]

    xaxis = np.cross(yaxis, zaxis)

    xaxis /= np.linalg.norm(xaxis)

    yaxis = np.cross(zaxis, xaxis)

    yaxis /= np.linalg.norm(yaxis)

    xwidth = 0.1

    ywidth = edgeLength

    zwidth = 0.1

    t = getTransformFromAxes(xaxis, yaxis, zaxis)

    t.PreMultiply()

    t.Concatenate(stanceTransform)

    t.PostMultiply()

    t.Translate(point1)

    name = 'truss'

    otdfType = 'robot_knees'

    obj = showPolyData(geometry, name, cls=FrameAffordanceItem, parent='affordances')

    obj.actor.SetUserTransform(t)

    obj.addToView(app.getDRCView())

    params = dict(origin=t.GetPosition(), xwidth=xwidth, ywidth=ywidth, zwidth=zwidth, xaxis=xaxis, yaxis=yaxis, zaxis=zaxis, friendly_name=name, otdf_type=otdfType)

    obj.setAffordanceParams(params)

    obj.updateParamsFromActorTransform()

    frameObj = showFrame(obj.actor.GetUserTransform(), name + ' frame', parent=obj, visible=False)

    frameObj.addToView(app.getDRCView())

    开发者ID:RobotLocomotion,项目名称:director,代码行数:57,

    注:本文中的vtk.vtkTransform方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

    展开全文
    weixin_39758618 2020-12-16 04:09:52
  • Python的3D图像处理中,通常用numpy array来进行非常方便的计算或者转化,这里记录一下numpy数据的VTK可视化基本流程,包括面绘制(Surfase Rendering)和体绘制(Volume Rendering)。除去数据格式转化,面绘制和...

    在Python的3D图像处理中,通常用numpy array来进行非常方便的计算或者转化,这里记录一下numpy数据的VTK可视化基本流程,包括面绘制(Surfase Rendering)和体绘制(Volume Rendering)。除去数据格式转化,面绘制和体绘制在C++中也是类似的处理方法。

    numpy数据转成vtkImageData

    首先得把numpy数据转成vtk里可以用的格式:numpy array -> vtkIImageData。这里的numpy array是一个离散的三维空间数据场,0代表背景,非0代表前景点。

    方法一:numpy_to_vtk

    可以直接使用vtk.util.numpy_support里的转换方法,非常方便。这是它的说明文档:

    numpy_to_vtk(num_array, deep=0, array_type=None)
        Converts a contiguous real numpy Array to a VTK array object.
    
        This function only works for real arrays that are contiguous.
        Complex arrays are NOT handled.  It also works for multi-component
        arrays.  However, only 1, and 2 dimensional arrays are supported.
        This function is very efficient, so large arrays should not be a
        problem.
    
        If the second argument is set to 1, the array is deep-copied from
        from numpy. This is not as efficient as the default behavior
        (shallow copy) and uses more memory but detaches the two arrays
        such that the numpy array can be released.
    
        WARNING: You must maintain a reference to the passed numpy array, if
        the numpy data is gc'd and VTK will point to garbage which will in
        the best case give you a segfault.
    
        Parameters
        ----------
    
        - num_array :  a contiguous 1D or 2D, real numpy array.
    

    对于3D array,可以用flatten或者ravel先转成1D array就可以使用了。这里的1D array得是C order(row-major order),最好使用deep copy以免出现一些内存管理的问题。

    import numpy as np
    import vtk
    from vtk.util import numpy_support
    
    # numpy_data is a 3D numpy array
    shape = numpy_data.shape[::-1]
    vtk_data = numpy_support.numpy_to_vtk(numpy_data.ravel(), 1, vtk.VTK_SHORT)
    
    vtk_image_data = vtk.vtkImageData()
    vtk_image_data.SetDimensions(shape)
    vtk_image_data.SetSpacing(spacing)
    vtk_image_data.SetOrigin(origin)
    vtk_image_data.GetPointData().SetScalars(vtk_data)
    
    # vtk_image_data: ready to use
    

    方法二:vtkImageImport

    使用Python也可以用vtkImageImport来直接导入C array,就是要先把numpy array变成string。

    import numpy as np
    import vtk
    
    numpy_str = numpy_data.astype(np.int16).tostring()
    x_extent = numpy_data.shape[2]
    y_extent = numpy_data.shape[1]
    z_extent = numpy_data.shape[0]
    
    image_import = vtk.vtkImageImport()
    image_import.SetImportVoidPointer(numpy_str, len(numpy_str))
    # 也可以使用CopyImportVoidPointer() 会copy一份numpy_str
    image_import.SetWholeExtent(0, x_extent-1, 0, y_extent-1, 0, z_extent-1)
    image_import.SetDataExtent(0, x_extent-1, 0, y_extent-1, 0, z_extent-1)
    image_import.SetDataScalarTypeToShort() # 根据需求指定数据类型
    image_import.SetNumberOfScalarComponents(1)
    # 如果是RGB数据的话,SetNumberOfScalarComponents(3)
    image_import.Update()
    
    vtk_image_data = vtk.vtkImageData()
    vtk_image_data.SetSpacing(spacing)
    vtk_image_data.SetOrigin(origin)
    
    # vtk_image_data: ready to use
    

    绘制

    参考:https://www.cnblogs.com/XDU-Lakers/p/10822840.html
    这个作者总结的很全面,还有代码示例👍

    面绘制

    面绘制的意思是根据数据建立三角网格模型,再渲染网格。通俗来讲就是根据算法进行轮廓识别和提取,生成了三维物体的表面,这个表面本质是由非常多的小三角面构成。
    如何抽取物体表面(轮廓/等值面)?VTK提供了一些算法(filter):

    • vtkMarchingCubes
      • 必须指定一个或多个轮廓值
      • 2D版本是vtkMarchingSquares
      • 多标签图像是vtkDiscreteMarchingCubdes,这个filter会给每个cell生成对应的scalar值,可以用vtkThreshold来得到不同的标签
    • vtkContourFilter
      • 3D生成轮廓面,2D生成轮廓线,1D生成轮廓点
      • 必须指定一个或多个轮廓值
      • 不会自动生成normal,可以用vtkPolyDataNormals得到
    • vtkFlyingEdges3D
      • 提速版轮廓提取算法,适用于较大的数据
      • 2D版本是vtkFlyingEdges2D

    什么是轮廓值?其实就是根据这个值来提取轮廓。比如对于一个二值图像,所有值为1的点是前景点(要显示的物体),所有值为0的点是背景点。此时轮廓值是1,算法会找到值为1的点所构成物体的轮廓。如果是多标签图像,可以把多个标签的值当作轮廓值。如果是其它医学图像,可以根据需求取不同的值,比如人体皮肤所对应的value值为500,人体骨骼所对应的value值为1150。设置多个轮廓值,这样多个等值面都可以被提取出来。

    经过这些filter,数据就被处理成了表现三维物体表面的vtkPolyData,再经过vtkPolyDataMappervtkActorvtkRenderervtkRenderWindowvtkRenderWindowInteractor显示出来。

    官方使用范例:(多标签数据 面绘制 上色 / multilabel data)

    # https://kitware.github.io/vtk-examples/site/Python/Modelling/SmoothDiscreteMarchingCubes/
    import vtk
    
    def main():
        n = 20
        radius = 8
        blob = make_blob(n, radius)
    
        discrete = vtk.vtkDiscreteMarchingCubes()
        discrete.SetInputData(blob)
        discrete.GenerateValues(n, 1, n)
    
        smoothing_iterations = 15
        pass_band = 0.001
        feature_angle = 120.0
    
        smoother = vtk.vtkWindowedSincPolyDataFilter()
        smoother.SetInputConnection(discrete.GetOutputPort())
        smoother.SetNumberOfIterations(smoothing_iterations)
        smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOff()
        smoother.SetFeatureAngle(feature_angle)
        smoother.SetPassBand(pass_band)
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()
        smoother.Update()
    
        lut = make_colors(n)
    
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(smoother.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarRange(0, lut.GetNumberOfColors())
    
        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        ren_win = vtk.vtkRenderWindow()
        ren_win.AddRenderer(ren)
        ren_win.SetWindowName('SmoothDiscreteMarchingCubes')
    
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(ren_win)
    
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
    
        ren.AddActor(actor)
    
        colors = vtk.vtkNamedColors()
        ren.SetBackground(colors.GetColor3d('Burlywood'))
    
        ren_win.Render()
    
        iren.Start()
    
    
    def make_blob(n, radius):
        blob_image = vtk.vtkImageData()
    
        max_r = 50 - 2.0 * radius
        random_sequence = vtk.vtkMinimalStandardRandomSequence()
        random_sequence.SetSeed(5071)
        for i in range(0, n):
    
            sphere = vtk.vtkSphere()
            sphere.SetRadius(radius)
    
            x = random_sequence.GetRangeValue(-max_r, max_r)
            random_sequence.Next()
            y = random_sequence.GetRangeValue(-max_r, max_r)
            random_sequence.Next()
            z = random_sequence.GetRangeValue(-max_r, max_r)
            random_sequence.Next()
    
            sphere.SetCenter(int(x), int(y), int(z))
    
            sampler = vtk.vtkSampleFunction()
            sampler.SetImplicitFunction(sphere)
            sampler.SetOutputScalarTypeToFloat()
            sampler.SetSampleDimensions(100, 100, 100)
            sampler.SetModelBounds(-50, 50, -50, 50, -50, 50)
    
            thres = vtk.vtkImageThreshold()
            thres.SetInputConnection(sampler.GetOutputPort())
            thres.ThresholdByLower(radius * radius)
            thres.ReplaceInOn()
            thres.ReplaceOutOn()
            thres.SetInValue(i + 1)
            thres.SetOutValue(0)
            thres.Update()
            if i == 0:
                blob_image.DeepCopy(thres.GetOutput())
    
            max_value = vtk.vtkImageMathematics()
            max_value.SetInputData(0, blob_image)
            max_value.SetInputData(1, thres.GetOutput())
            max_value.SetOperationToMax()
            max_value.Modified()
            max_value.Update()
    
            blob_image.DeepCopy(max_value.GetOutput())
    
        return blob_image
    
    
    def make_colors(n):
        """
        Generate some random colors
        :param n: The number of colors.
        :return: The lookup table.
        """
    
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(n)
        lut.SetTableRange(0, n - 1)
        lut.SetScaleToLinear()
        lut.Build()
        lut.SetTableValue(0, 0, 0, 0, 1)
    
        random_sequence = vtk.vtkMinimalStandardRandomSequence()
        random_sequence.SetSeed(5071)
        for i in range(1, n):
            r = random_sequence.GetRangeValue(0.4, 1)
            random_sequence.Next()
            g = random_sequence.GetRangeValue(0.4, 1)
            random_sequence.Next()
            b = random_sequence.GetRangeValue(0.4, 1)
            random_sequence.Next()
            lut.SetTableValue(i, r, g, b, 1.0)
    
        return lut
    
    
    if __name__ == '__main__':
        main()
    

    体绘制

    体绘制是为每一个体素指定一个不透明度,并考虑每一个体素对光线的透射、发射和反射作用,实现三维重建。简单来说就是能够更完整的展示出整个物体,而不仅仅是表面。
    VTK采用的是光线投射算法。光线投射算法(Ray-casting)原理:从图像平面的每个像素都沿着视线方向发出一条射线,此射线穿过体数据集,按一定步长进行采样,由内插计算每个采样点的颜色值和不透明度,然后由前向后或由后向前逐点计算累计的颜色值和不透明度值,直至光线完全被吸收或穿过物体。该方法能很好地反映物质边界的变化,使用Phong模型,引入镜面反射、漫反射和环境反射能得到很好的光照效果,在医学上可将各组织器官的性质属性、形状特征及相互之间的层次关系表现出来,从而丰富了图像的信息。(百度百科)
    这个算法集成在vtkVolumeMapper,包括vtkVolumeRayCastMappervtkFixedPointVolumeRayCastMappervtkGPUVolumeRayCastMapper等。把vtkImageData经过volumeMapper,再放入vtkVolume,经过vtkRenderervtkRenderWindowvtkRenderWindowInteractor显示出体绘制图像。

    官方使用范例:

    # https://kitware.github.io/vtk-examples/site/Python/VolumeRendering/SimpleRayCast/
    import vtk
    
    
    def main():
        fileName = get_program_parameters()
    
        colors = vtk.vtkNamedColors()
    
        # This is a simple volume rendering example that
        # uses a vtkFixedPointVolumeRayCastMapper
    
        # Create the standard renderer, render window
        # and interactor.
        ren1 = vtk.vtkRenderer()
    
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren1)
    
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)
    
        # Create the reader for the data.
        reader = vtk.vtkStructuredPointsReader()
        reader.SetFileName(fileName)
    
        # Create transfer mapping scalar value to opacity.
        opacityTransferFunction = vtk.vtkPiecewiseFunction()
        opacityTransferFunction.AddPoint(20, 0.0)
        opacityTransferFunction.AddPoint(255, 0.2)
    
        # Create transfer mapping scalar value to color.
        colorTransferFunction = vtk.vtkColorTransferFunction()
        colorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
        colorTransferFunction.AddRGBPoint(64.0, 1.0, 0.0, 0.0)
        colorTransferFunction.AddRGBPoint(128.0, 0.0, 0.0, 1.0)
        colorTransferFunction.AddRGBPoint(192.0, 0.0, 1.0, 0.0)
        colorTransferFunction.AddRGBPoint(255.0, 0.0, 0.2, 0.0)
    
        # The property describes how the data will look.
        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(colorTransferFunction)
        volumeProperty.SetScalarOpacity(opacityTransferFunction)
        volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
    
        # The mapper / ray cast function know how to render the data.
        volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volumeMapper.SetInputConnection(reader.GetOutputPort())
    
        # The volume holds the mapper and the property and
        # can be used to position/orient the volume.
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
    
        ren1.AddVolume(volume)
        ren1.SetBackground(colors.GetColor3d('Wheat'))
        ren1.GetActiveCamera().Azimuth(45)
        ren1.GetActiveCamera().Elevation(30)
        ren1.ResetCameraClippingRange()
        ren1.ResetCamera()
    
        renWin.SetSize(600, 600)
        renWin.SetWindowName('SimpleRayCast')
        renWin.Render()
    
        iren.Start()
    
    
    def get_program_parameters():
        import argparse
        description = 'Volume rendering of a high potential iron protein.'
        epilogue = '''
        This is a simple volume rendering example that uses a vtkFixedPointVolumeRayCastMapper.
        '''
        parser = argparse.ArgumentParser(description=description, epilog=epilogue,
                                         formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument('filename', help='ironProt.vtk.')
        args = parser.parse_args()
        return args.filename
    
    
    if __name__ == '__main__':
        main()
    
    展开全文
    weixin_43854380 2021-08-23 17:22:25
  • 昨天整理了 VTK 基础知识点,今天着重从代码分析学习。 1. VTK 柱体 首先看一个 VTK 画柱体的代码: import vtk # 数据源 cylinder = vtk.vtkCylinderSource() cylinder.SetHeight(3.0) cylinder.SetRadius(1.0) ...

    昨天整理了 VTK 基础知识点,今天着重从代码分析学习。

    1. VTK 柱体

    首先看一个 VTK 画柱体的代码:

    import vtk
    
    # 数据源
    cylinder = vtk.vtkCylinderSource()
    cylinder.SetHeight(3.0)
    cylinder.SetRadius(1.0)
    cylinder.SetResolution(360)
    print("高、半径、面:",cylinder.GetHeight(),cylinder.GetRadius(),cylinder.GetResolution())
    # 映射
    cylinderMapper = vtk.vtkPolyDataMapper()
    cylinderMapper.SetInputConnection(cylinder.GetOutputPort())
    
    # 绘制对象/演员
    cylinderActor = vtk.vtkActor()
    # 绘制对象添加映射器
    cylinderActor.SetMapper(cylinderMapper)
    # 绘制器
    renderer = vtk.vtkRenderer()
    # 绘制器添加对象
    renderer.AddActor(cylinderActor)
    # 绘制器设置背景
    renderer.SetBackground(0.1,0.2,0.4)
    print("Renderer bg:",renderer.GetBackground())
    # 绘制窗口
    renWin = vtk.vtkRenderWindow()
    # 绘制窗口添加绘制器
    renWin.AddRenderer(renderer)
    renWin.SetSize(1200,1200)
    print("Window size:",renWin.GetSize())
    # 绘制窗口内所有绘制器同步渲染绘制
    renWin.Render()
    # 交互器
    i_ren = vtk.vtkRenderWindowInteractor()
    # 交互器绑定绘制窗口
    i_ren.SetRenderWindow(renWin)
    # 交互器初始化
    i_ren.Initialize()
    # 交互器启动
    i_ren.Start()
    

    效果图:
    VTK柱体效果图

    2. VTK 柱体进阶

    在刚代码上加个渐变色,再配合文档添加更详细的随行注释

    import vtk
    
    # *************柱体****************
    # 生成一个中心在渲染场景原点的柱体,柱体的长轴沿着Y轴,柱体的高度、截面半径等都可以任意指定
    cylinder = vtk.vtkCylinderSource()
    # 高
    cylinder.SetHeight(3.0)
    # 截面半径
    cylinder.SetRadius(1.0)
    # 横截面边数
    cylinder.SetResolution(360)
    print(f"高:{cylinder.GetHeight()}、半径:{cylinder.GetRadius()}、面:{cylinder.GetResolution()}")
    # 映射,将输入的数据转换为几何图元(点、线、多边形)进行渲染
    cylinderMapper = vtk.vtkPolyDataMapper()
    # 设置 VTK 可视化管线的输入数据接口,对应的可视化管线输出数据的接口为 GetOutputPort()
    cylinderMapper.SetInputConnection(cylinder.GetOutputPort())
    
    # 三维空间中渲染对象最常用的 vtkProp 子类是 vtkActor(表达场景中的几何数据)和 vtkVolume(表达场景中的体数据)
    """vtkProp子类负责确定渲染场景中对象的位置、大小和方向信息。
    Prop依赖于两个对象(Prop一词来源于戏剧里的“道具”,在VTK里表示的是渲染场景中可以看得到的对象。)
    一个是Mapper(vtkMapper)对象,负责存放数据和渲染信息,另一个是属性(vtkProperty)对象,负责控制颜色、不透明度等参数。
    """
    cylinderActor = vtk.vtkActor()
    # 绘制对象添加映射器,设置生成几何图元的Mapper,即连接一个Actor到可视化管线的末端(可视化管线的末端就是Mapper)
    cylinderActor.SetMapper(cylinderMapper)
    
    # 绘制器,负责管理场景的渲染过程。
    # 组成场景的所有对象包括Prop,照相机(Camera)和光照(Light)都被集中在一个vtkRenderer对象中。
    # 一个vtkRenderWindow中可以有多个vtkRenderer对象,而这些vtkRenderer可以渲染在窗口中不同的矩形区域中(即视口),或者覆盖整个窗口区域。
    renderer = vtk.vtkRenderer()
    # 绘制器添加对象,添加vtkProp类型的对象到渲染场景中
    renderer.AddActor(cylinderActor)
    # 绘制器设置背景,设置渲染场景的背景颜色
    renderer.SetBackground(0.1,0.2,0.4)
    print("Renderer bg:",renderer.GetBackground())
    # SetBackground2()用于设置渐变的另外一种颜色
    renderer.SetBackground2(1.0,1.0,1.0)
    # 打开背景颜色渐变效果,相当于调用方法 GradientBackgroundOn()
    renderer.SetGradientBackground(1)
    
    
    # 绘制窗口,将操作系统与VTK渲染引擎连接到一起
    renWin = vtk.vtkRenderWindow()
    # 绘制窗口添加绘制器,加入 vtkRenderer 对象
    renWin.AddRenderer(renderer)
    # 设置窗口的大小,以像素为单位
    renWin.SetSize(1200,1200)
    print("Window size:",renWin.GetSize())
    # 绘制窗口内所有绘制器同步渲染绘制
    #renWin.Render()
    # 交互器,提供平台独立的响应鼠标、键盘和时钟事件的交互机制
    """vtkRenderWindowInteractor自动建立一个默认的3D场景交互器样式(Interactor Style):vtkInteractorStyleSwitch,
    当然你也可以选择其他的交互器样式,或者是创建自己的交互器样式"""
    i_ren = vtk.vtkRenderWindowInteractor()
    # 交互器绑定绘制窗口,设置渲染窗口,消息是通过渲染窗口捕获到的,所以必须要给交互器对象设置渲染窗口
    i_ren.SetRenderWindow(renWin)
    # 为处理窗口事件做准备,交互器工作之前必须先调用这个方法进行初始化
    i_ren.Initialize()
    # 开始进入事件响应循环,交互器处于等待状态,等待用户交互事件的发生
    i_ren.Start()
    

    效果图:
    效果图
    配合注释,效果图中对应实例:

    图例说明

    3. VTK 星空柱体

    刚代码基础上,修改背景色,并为柱体贴图:

    import vtk
    
    # *************柱体****************
    # 生成一个中心在渲染场景原点的柱体,柱体的长轴沿着Y轴,柱体的高度、截面半径等都可以任意指定
    cylinder = vtk.vtkCylinderSource()
    # 高
    cylinder.SetHeight(3.0)
    # 截面半径
    cylinder.SetRadius(1.0)
    # 横截面边数
    cylinder.SetResolution(360)
    print(f"高:{cylinder.GetHeight()}、半径:{cylinder.GetRadius()}、面:{cylinder.GetResolution()}")
    # 映射,将输入的数据转换为几何图元(点、线、多边形)进行渲染
    cylinderMapper = vtk.vtkPolyDataMapper()
    # 设置 VTK 可视化管线的输入数据接口,对应的可视化管线输出数据的接口为 GetOutputPort()
    cylinderMapper.SetInputConnection(cylinder.GetOutputPort())
    
    # 三维空间中渲染对象最常用的 vtkProp 子类是 vtkActor(表达场景中的几何数据)和 vtkVolume(表达场景中的体数据)
    """vtkProp子类负责确定渲染场景中对象的位置、大小和方向信息。
    Prop依赖于两个对象(Prop一词来源于戏剧里的“道具”,在VTK里表示的是渲染场景中可以看得到的对象。)
    一个是Mapper(vtkMapper)对象,负责存放数据和渲染信息,另一个是属性(vtkProperty)对象,负责控制颜色、不透明度等参数。
    """
    cylinderActor = vtk.vtkActor()
    print(f"位置:{cylinderActor.GetPosition()}")
    
    # 改变属性颜色
    cylinderProperty = vtk.vtkProperty()
    cylinderProperty.SetColor(0.6,0.96,1)
    print("颜色:",cylinderProperty.GetColor())
    
    # 读取 bmp 背景图片
    bmpReader = vtk.vtkBMPReader()
    bmpReader.SetFileName("sky.bmp")
    # 纹理
    texture = vtk.vtkTexture()
    # 数据接口联通纹理
    texture.SetInputConnection(bmpReader.GetOutputPort())
    # 插入纹理
    texture.InterpolateOn()
    # 绘制对象添加映射器,设置定义Actor几何形状的Mapper
    cylinderActor.SetMapper(cylinderMapper)
    # 设置Actor的属性
    cylinderActor.SetProperty(cylinderProperty)
    # 设置纹理属性
    cylinderActor.SetTexture(texture)
    
    # 绘制器,负责管理场景的渲染过程。
    # 组成场景的所有对象包括Prop,照相机(Camera)和光照(Light)都被集中在一个vtkRenderer对象中。
    # 一个vtkRenderWindow中可以有多个vtkRenderer对象,而这些vtkRenderer可以渲染在窗口中不同的矩形区域中(即视口),或者覆盖整个窗口区域。
    renderer = vtk.vtkRenderer()
    # 绘制器添加对象,添加vtkProp类型的对象到渲染场景中
    renderer.AddActor(cylinderActor)
    # 绘制器设置背景,设置渲染场景的背景颜色
    renderer.SetBackground(1.0,0.87,0.68)
    print("Renderer bg:",renderer.GetBackground())
    # SetBackground2()用于设置渐变的另外一种颜色
    renderer.SetBackground2(1.0,1.0,1.0)
    # 打开背景颜色渐变效果,相当于调用方法 GradientBackgroundOn()
    renderer.SetGradientBackground(1)
    
    
    # 绘制窗口,将操作系统与VTK渲染引擎连接到一起
    renWin = vtk.vtkRenderWindow()
    # 绘制窗口添加绘制器,加入 vtkRenderer 对象
    renWin.AddRenderer(renderer)
    # 设置窗口的大小,以像素为单位
    renWin.SetSize(1200,1200)
    print("Window size:",renWin.GetSize())
    # 绘制窗口内所有绘制器同步渲染绘制
    #renWin.Render()
    # 交互器,提供平台独立的响应鼠标、键盘和时钟事件的交互机制
    """vtkRenderWindowInteractor自动建立一个默认的3D场景交互器样式(Interactor Style):vtkInteractorStyleSwitch,
    当然你也可以选择其他的交互器样式,或者是创建自己的交互器样式"""
    i_ren = vtk.vtkRenderWindowInteractor()
    # 交互器绑定绘制窗口,设置渲染窗口,消息是通过渲染窗口捕获到的,所以必须要给交互器对象设置渲染窗口
    i_ren.SetRenderWindow(renWin)
    # 为处理窗口事件做准备,交互器工作之前必须先调用这个方法进行初始化
    i_ren.Initialize()
    # 开始进入事件响应循环,交互器处于等待状态,等待用户交互事件的发生
    i_ren.Start()
    

    代码中的贴图是自己转化的一张星空图 sky.bmp

    sky.bmp
    贴完图后柱体效果演示:

    星空柱体
    参考链接:
    https://blog.csdn.net/www_doling_net/article/details/8536376

    展开全文
    weixin_40796925 2020-07-22 16:04:14
  • xujia0 2021-12-20 13:53:47
  • weixin_40796925 2020-08-17 19:29:01
  • weixin_39754915 2020-11-24 04:20:12
  • 408KB seing128 2019-02-15 09:33:09
  • xujia0 2021-12-20 09:24:04
  • weixin_40796925 2020-07-23 17:24:00
  • 2KB weixin_42669344 2021-10-02 11:54:38
  • 3.69MB weixin_42674361 2021-10-01 12:09:38
  • weixin_39851914 2020-11-24 04:20:14
  • xujia0 2021-12-23 13:42:26
  • xujia0 2021-12-21 14:24:22
  • weixin_42046845 2021-03-12 10:53:59
  • weixin_42046845 2021-03-12 10:30:20
  • weixin_43854380 2021-07-29 11:39:22
  • BLvren_ 2021-05-25 14:59:24
  • weixin_42046845 2021-04-01 16:13:27
  • qq_45363979 2019-10-16 19:40:30
  • weixin_39917791 2020-12-06 05:21:25
  • weixin_42046845 2021-03-12 10:25:26
  • 2KB weixin_45873809 2021-04-16 23:23:29
  • xujia0 2021-12-22 13:59:06
  • qq_35346390 2018-08-20 20:13:55
  • 34.01MB orangefish8_zz 2017-04-06 13:56:00

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 6,364
精华内容 2,545
关键字:

pythonvtk

python 订阅