Skip to content
Snippets Groups Projects
Commit 749111c4 authored by Boman Romain's avatar Boman Romain
Browse files
parent dc80d4e9
No related branches found
No related tags found
No related merge requests found
Pipeline #7125 passed
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, os
print('sys.path=')
for d in sys.path:
print(d)
print(f"PYTHONPATH={os.environ['PYTHONPATH']}")
# newpath = sys.path
# newpath = [d for d in newpath if not 'gmsh' in d ]
# sys.path = newpath
print('sys.path=')
for d in sys.path:
print(d)
import gmsh
print('version =',gmsh.GMSH_API_VERSION)
\ No newline at end of file
[InternetShortcut]
URL=https://stackoverflow.com/questions/22354413/meshlab-get-ids-of-selected-vertices
# How to create/export selections?
In MeshLab:
from: https://stackoverflow.com/questions/22354413/meshlab-get-ids-of-selected-vertices
* Choose the vertex of interest with the standard MeshLab tool.
* Invert the selection.
* Delete all vertices, and get an 1-point pointcloud/mesh as result.
* Export this as an .off file.
* Open the exported file and read the coordinates of this unique point. One coordinate (e.g. X) is enough.
* Search in your original .off file or in the original mesh/pointcloud structure to find the point/vertex with this coordinate.
* There you have it, you have the ID of the chosen vertex in the original structure.
* Then (this is application specific, according to my needs), using PCL, I created a Kd-Tree for my pointcloud, used the selected points (red) as "query" to get some nearest neighbors (green).
This diff is collapsed.
# -*- coding: utf-8 -*-
import vtk
colors = vtk.vtkNamedColors()
class MyInteractorStyle(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
"""register to event listening
"""
self.AddObserver("LeftButtonPressEvent", self.leftButtonPressEvent)
self.selection = None
self.selected_mapper = vtk.vtkDataSetMapper()
self.selected_actor = vtk.vtkActor()
self.dataset = None
def select_one(self):
# get the mouse click position
clickPos = self.GetInteractor().GetEventPosition()
# crete a picker and pick at that position
picker = vtk.vtkCellPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
print("pick")
print(f"\tcell id = {picker.GetCellId()}")
print(f"\t3D pick position = {picker.GetPickPosition()}")
print(f"\t2D mouse position = {picker.GetSelectionPoint()[:2]}")
# the picking could be empty
# in that case, we leave the routine
if picker.GetDataSet():
print(f"\tdataset = {picker.GetDataSet().GetClassName()}")
else:
print(f"\tdataset = None")
return
# no cell has been picked => quit
if picker.GetCellId()==-1:
return
# cell type - we can pick triangles, but also tetras
cell_type = picker.GetDataSet().GetCellType( picker.GetCellId() )
print(f"\tcell type = { vtk.vtkCellTypes.GetClassNameFromTypeId( cell_type )}")
if(cell_type != vtk.VTK_TRIANGLE ):
print("\tWRONG CELL TYPE")
return
# we can pick the wrong ugrid (the red one)
# we store the right one at the first successful picking
if self.dataset == None:
self.dataset = picker.GetDataSet()
if picker.GetDataSet() != self.dataset:
print(f"\tPICKED WRONG DATASET!")
return
# -- cree un "vtkSelectionNode" (données de selection + type de selection)
ids = vtk.vtkIdTypeArray()
ids.SetNumberOfComponents(1)
ids.InsertNextValue(picker.GetCellId())
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
# CELL,POINT,FIELD,VERTEX,EDGE,ROW
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
# SELECTIONS,GLOBALIDS,PEDIGREEIDS,VALUES,INDICES,FRUSTUM,
# LOCATIONS,THRESHOLDS,BLOCKS,QUERY
selectionNode.SetSelectionList(ids)
# -- cree une "vtkSelection" (la sélection en elle-même)
# c'est un ensemble de "noeuds de selection"
if not self.selection:
self.selection = vtk.vtkSelection()
self.selection.AddNode(selectionNode)
else:
self.selection.Union(selectionNode)
print( f"\tThere are {self.selection.GetNumberOfNodes()} 'selection nodes'.")
# -- DISPLAY: cree une "vtkExtractSelection"
extractSelection = vtk.vtkExtractSelection()
extractSelection.SetInputData(0, picker.GetDataSet())
# extractSelection.SetInputConnection(0, filt.GetOutputPort()) # cas d'un filtre
extractSelection.SetInputData(1, self.selection)
extractSelection.Update()
# build a ugrid for display
selected = vtk.vtkUnstructuredGrid()
selected.ShallowCopy(extractSelection.GetOutput())
print( f"\tThere are {selected.GetNumberOfPoints()} points in the selection.")
print( f"\tThere are {selected.GetNumberOfCells()} cells in the selection.")
self.selected_mapper.SetInputData(selected)
self.selected_actor.SetMapper(self.selected_mapper)
self.selected_actor.GetProperty().EdgeVisibilityOn()
self.selected_actor.GetProperty().SetColor( colors.GetColor3d('red') )
self.selected_actor.GetProperty().SetLineWidth(3)
self.GetDefaultRenderer().AddActor(self.selected_actor) # global - n'est pas ajouté si il l'a deja été
print(f'nb of actors = {self.GetDefaultRenderer().GetActors().GetNumberOfItems()}')
def leftButtonPressEvent(self, obj, event):
"""custom event
"""
self.select_one()
self.OnLeftButtonDown() # calls vtk.vtkInteractorStyleTrackballCamera
# -*- coding: utf-8 -*-
import vtk
colors = vtk.vtkNamedColors()
class MyPickAreaCallBack:
def __init__(self):
pass
def __call__(self, object, eid):
print('pick')
print(f'\tobject = {object}') # object = vtkAreaPicker
print(f'\teid = {eid}') # eid = EndPickEvent
# -*- coding: utf-8 -*-
import vtk
def saveUGrid(ugrid, filename):
""" saves an unstructured grid into a .vtu file
"""
writer = vtk.vtkXMLUnstructuredGridWriter()
compressor = vtk.vtkZLibDataCompressor()
writer.SetCompressor(compressor)
writer.SetDataModeToAscii()
writer.SetInputData(ugrid)
writer.SetFileName(filename)
writer.Write()
def loadUGrid(filename):
""" loads an unstructured grid from a .vtu file
"""
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName(filename)
reader.Update()
return reader.GetOutput()
# -*- coding: utf-8 -*-
import vtk
from myinteractor import *
from myinteractor2 import *
colors = vtk.vtkNamedColors()
class BasicView:
"defines a basic renderer / window / interactor"
def __init__(self):
ren = vtk.vtkRenderer()
ren.SetBackground(colors.GetColor3d('cobalt') )
win = vtk.vtkRenderWindow()
win.SetSize(800, 800)
win.SetWindowName('Select faces')
win.AddRenderer(ren)
intor = vtk.vtkRenderWindowInteractor()
intor.SetRenderWindow(win)
# custom interactor style - sect one cell
# sw = MyInteractorStyle()
# sw.SetDefaultRenderer(ren)
# rubber band
istyle = vtk.vtkInteractorStyleRubberBandPick()
istyle.SetDefaultRenderer(ren)
areaPicker = vtk.vtkAreaPicker()
pick_callback = MyPickAreaCallBack()
areaPicker.AddObserver('EndPickEvent', pick_callback)
intor.SetPicker(areaPicker)
intor.SetInteractorStyle(istyle)
self.axes = ParaviewAxes(intor)
self.ren = ren
self.win = win
self.intor = intor
def add(self, actors):
for actor in actors:
self.ren.AddActor(actor)
def interact(self):
self.ren.ResetCamera() # camera en fct de l'objet (key = 'r')
# self.win.Render() # semble inutile
# self.intor.Initialize() # semble inutile (?)
self.intor.Start()
class ParaviewAxes:
"axes a la paraview"
def __init__(self, intor):
axes = vtk.vtkAxesActor()
axes.SetShaftTypeToCylinder()
axes.SetXAxisLabelText("x")
axes.SetYAxisLabelText("y")
axes.SetZAxisLabelText("z")
axes.SetTotalLength(1, 1, 1)
tprop = vtk.vtkTextProperty()
tprop.ItalicOn()
#tprop.ShadowOn()
#tprop.SetFontFamilyToTimes()
axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tprop)
axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tprop)
axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tprop)
marker = vtk.vtkOrientationMarkerWidget()
marker.SetOrientationMarker(axes)
marker.SetViewport(0.85, 0.8, 1.1, 1.1)
marker.SetInteractor(intor)
marker.SetEnabled(1)
marker.InteractiveOff()
# keep track of both main objects (otherwise, the display hangs!)
self.axes = axes
self.marker = marker
# -*- coding: utf-8 -*-
#
# inspired from:
# https://kitware.github.io/vtk-examples/site/Python/PolyData/ExtractSelection/
# https://vtk.org/Wiki/VTK/Examples/Cxx/Picking/CellPicking
import vtk
colors = vtk.vtkNamedColors()
# print(colors.GetColorNames())
# see also https://vtk.org/Wiki/VTK/Examples/Python/Visualization/VTKNamedColorPatches_html
from mytools import *
from myinteractor import *
from myview import *
def main():
# ugrid = loadUGrid('Dolicorhynchops_coarse.vtu')
ugrid = loadUGrid('grid.vtu')
# saveUGrid(ugrid, 'grid.vtu')
print('There are %s input points' % ugrid.GetNumberOfPoints())
print('There are %s input cells' % ugrid.GetNumberOfCells())
# mesh
meshMapper = vtk.vtkDataSetMapper()
meshMapper.SetInputData(ugrid)
meshActor = vtk.vtkActor()
meshActor.GetProperty().SetColor(colors.GetColor3d('white'))
meshActor.GetProperty().EdgeVisibilityOn()
meshActor.SetMapper(meshMapper)
# display mesh
view = BasicView()
view.add( [meshActor] )
# cubeAxesActor = vtk.vtkCubeAxesActor()
# cubeAxesActor.SetBounds(ugrid.GetBounds())
# cubeAxesActor.SetCamera(view.ren.GetActiveCamera())
# -- example of callback - rien a voir avec la selection
# print the camaera position for each render
if 0:
def start_callback(caller, ev):
# print('StartEvent')
position = view.ren.GetActiveCamera().GetPosition()
print('StartEvent ({:5.2f}, {:5.2f}, {:5.2f})'.format(*position))
view.ren.AddObserver('StartEvent', start_callback)
view.interact()
if __name__=="__main__":
main()
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkCellPicker.h>
#include <vtkCommand.h>
#include <vtkDataSetMapper.h>
#include <vtkExtractSelection.h>
#include <vtkIdTypeArray.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkNamedColors.h>
#include <vtkObjectFactory.h>
#include <vtkPlaneSource.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkRendererCollection.h>
#include <vtkSelection.h>
#include <vtkSelectionNode.h>
#include <vtkSmartPointer.h>
#include <vtkTriangleFilter.h>
#include <vtkUnstructuredGrid.h>
// Catch mouse events
class MouseInteractorStyle : public vtkInteractorStyleTrackballCamera
{
public:
static MouseInteractorStyle* New();
MouseInteractorStyle()
{
selectedMapper = vtkSmartPointer<vtkDataSetMapper>::New();
selectedActor = vtkSmartPointer<vtkActor>::New();
}
virtual void OnLeftButtonDown() override
{
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Get the location of the click (in window coordinates)
int* pos = this->GetInteractor()->GetEventPosition();
vtkSmartPointer<vtkCellPicker> picker =
vtkSmartPointer<vtkCellPicker>::New();
picker->SetTolerance(0.0005);
// Pick from this location.
picker->Pick(pos[0], pos[1], 0, this->GetDefaultRenderer());
double* worldPosition = picker->GetPickPosition();
std::cout << "Cell id is: " << picker->GetCellId() << std::endl;
if (picker->GetCellId() != -1)
{
std::cout << "Pick position is: " << worldPosition[0] << " "
<< worldPosition[1] << " " << worldPosition[2] << endl;
vtkSmartPointer<vtkIdTypeArray> ids =
vtkSmartPointer<vtkIdTypeArray>::New();
ids->SetNumberOfComponents(1);
ids->InsertNextValue(picker->GetCellId());
vtkSmartPointer<vtkSelectionNode> selectionNode =
vtkSmartPointer<vtkSelectionNode>::New();
selectionNode->SetFieldType(vtkSelectionNode::CELL);
selectionNode->SetContentType(vtkSelectionNode::INDICES);
selectionNode->SetSelectionList(ids);
vtkSmartPointer<vtkSelection> selection =
vtkSmartPointer<vtkSelection>::New();
selection->AddNode(selectionNode);
vtkSmartPointer<vtkExtractSelection> extractSelection =
vtkSmartPointer<vtkExtractSelection>::New();
extractSelection->SetInputData(0, this->Data);
extractSelection->SetInputData(1, selection);
extractSelection->Update();
// In selection
vtkSmartPointer<vtkUnstructuredGrid> selected =
vtkSmartPointer<vtkUnstructuredGrid>::New();
selected->ShallowCopy(extractSelection->GetOutput());
std::cout << "There are " << selected->GetNumberOfPoints()
<< " points in the selection." << std::endl;
std::cout << "There are " << selected->GetNumberOfCells()
<< " cells in the selection." << std::endl;
selectedMapper->SetInputData(selected);
selectedActor->SetMapper(selectedMapper);
selectedActor->GetProperty()->EdgeVisibilityOn();
selectedActor->GetProperty()->SetColor(
colors->GetColor3d("Red").GetData());
selectedActor->GetProperty()->SetLineWidth(3);
this->Interactor->GetRenderWindow()
->GetRenderers()
->GetFirstRenderer()
->AddActor(selectedActor);
}
// Forward events
vtkInteractorStyleTrackballCamera::OnLeftButtonDown();
}
vtkSmartPointer<vtkPolyData> Data;
vtkSmartPointer<vtkDataSetMapper> selectedMapper;
vtkSmartPointer<vtkActor> selectedActor;
};
vtkStandardNewMacro(MouseInteractorStyle);
int main(int, char*[])
{
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
vtkSmartPointer<vtkPlaneSource> planeSource =
vtkSmartPointer<vtkPlaneSource>::New();
planeSource->Update();
vtkSmartPointer<vtkTriangleFilter> triangleFilter =
vtkSmartPointer<vtkTriangleFilter>::New();
triangleFilter->SetInputConnection(planeSource->GetOutputPort());
triangleFilter->Update();
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(triangleFilter->GetOutputPort());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->GetProperty()->SetColor(colors->GetColor3d("Green").GetData());
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderWindowInteractor->Initialize();
// Set the custom stype to use for interaction.
vtkSmartPointer<MouseInteractorStyle> style =
vtkSmartPointer<MouseInteractorStyle>::New();
style->SetDefaultRenderer(renderer);
style->Data = triangleFilter->GetOutput();
renderWindowInteractor->SetInteractorStyle(style);
renderer->AddActor(actor);
renderer->ResetCamera();
renderer->SetBackground(colors->GetColor3d("Blue").GetData());
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
import vtk
NUMBER_OF_SPHERES = 10
class MouseInteractorHighLightActor(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self,parent=None):
self.AddObserver("LeftButtonPressEvent",self.leftButtonPressEvent)
self.LastPickedActor = None
self.LastPickedProperty = vtk.vtkProperty()
def leftButtonPressEvent(self,obj,event):
clickPos = self.GetInteractor().GetEventPosition()
picker = vtk.vtkPropPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
# get the new
self.NewPickedActor = picker.GetActor()
# If something was selected
if self.NewPickedActor:
# If we picked something before, reset its property
if self.LastPickedActor:
self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)
# Save the property of the picked actor so that we can
# restore it next time
self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
# Highlight the picked actor by changing its properties
self.NewPickedActor.GetProperty().SetColor(1.0, 0.0, 0.0)
self.NewPickedActor.GetProperty().SetDiffuse(1.0)
self.NewPickedActor.GetProperty().SetSpecular(0.0)
# save the last picked actor
self.LastPickedActor = self.NewPickedActor
self.OnLeftButtonDown()
return
# A renderer and render window
renderer = vtk.vtkRenderer()
renderer.SetBackground(.3, .4, .5 )
renwin = vtk.vtkRenderWindow()
renwin.AddRenderer(renderer)
# An interactor
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(renwin)
# add the custom style
style = MouseInteractorHighLightActor()
style.SetDefaultRenderer(renderer)
interactor.SetInteractorStyle(style)
# Add spheres to play with
for i in range(NUMBER_OF_SPHERES):
source = vtk.vtkSphereSource()
# random position and radius
x = vtk.vtkMath.Random(-5,5)
y = vtk.vtkMath.Random(-5,5)
z = vtk.vtkMath.Random(-5,5)
radius = vtk.vtkMath.Random(.5, 1.0)
source.SetRadius(radius)
source.SetCenter(x, y, z)
source.SetPhiResolution(11)
source.SetThetaResolution(21)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(source.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
r = vtk.vtkMath.Random(.4, 1.0)
g = vtk.vtkMath.Random(.4, 1.0)
b = vtk.vtkMath.Random(.4, 1.0)
actor.GetProperty().SetDiffuseColor(r, g, b)
actor.GetProperty().SetDiffuse(.8)
actor.GetProperty().SetSpecular(.5)
actor.GetProperty().SetSpecularColor(1.0,1.0,1.0)
actor.GetProperty().SetSpecularPower(30.0)
renderer.AddActor(actor)
# Start
interactor.Initialize()
interactor.Start()
\ No newline at end of file
#!/usr/bin/env python
# This example demonstrates cell picking using vtkCellPicker. It
# displays the results of picking using a vtkTextMapper.
from __future__ import print_function
import vtk
# create a sphere source, mapper, and actor
sphere = vtk.vtkSphereSource()
sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereMapper.GlobalImmediateModeRenderingOn()
sphereActor = vtk.vtkLODActor()
sphereActor.SetMapper(sphereMapper)
# create the spikes by glyphing the sphere with a cone. Create the
# mapper and actor for the glyphs.
cone = vtk.vtkConeSource()
glyph = vtk.vtkGlyph3D()
glyph.SetInputConnection(sphere.GetOutputPort())
glyph.SetSourceConnection(cone.GetOutputPort())
glyph.SetVectorModeToUseNormal()
glyph.SetScaleModeToScaleByVector()
glyph.SetScaleFactor(0.25)
spikeMapper = vtk.vtkPolyDataMapper()
spikeMapper.SetInputConnection(glyph.GetOutputPort())
spikeActor = vtk.vtkLODActor()
spikeActor.SetMapper(spikeMapper)
# Create a text mapper and actor to display the results of picking.
textMapper = vtk.vtkTextMapper()
tprop = textMapper.GetTextProperty()
tprop.SetFontFamilyToArial()
tprop.SetFontSize(10)
tprop.BoldOn()
tprop.ShadowOn()
tprop.SetColor(1, 0, 0)
textActor = vtk.vtkActor2D()
textActor.VisibilityOff()
textActor.SetMapper(textMapper)
# Create a cell picker.
picker = vtk.vtkCellPicker()
# Create a Python function to create the text for the text mapper used
# to display the results of picking.
def annotatePick(object, event):
print("pick")
global picker, textActor, textMapper
if picker.GetCellId() < 0:
textActor.VisibilityOff()
else:
selPt = picker.GetSelectionPoint()
pickPos = picker.GetPickPosition()
textMapper.SetInput("(%.6f, %.6f, %.6f)"%pickPos)
textActor.SetPosition(selPt[:2])
textActor.VisibilityOn()
# Now at the end of the pick event call the above function.
picker.AddObserver("EndPickEvent", annotatePick)
# Create the Renderer, RenderWindow, etc. and set the Picker.
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.SetPicker(picker)
# Add the actors to the renderer, set the background and size
ren.AddActor2D(textActor)
ren.AddActor(sphereActor)
ren.AddActor(spikeActor)
ren.SetBackground(1, 1, 1)
renWin.SetSize(300, 300)
# Get the camera and zoom in closer to the image.
ren.ResetCamera()
cam1 = ren.GetActiveCamera()
cam1.Zoom(1.4)
iren.Initialize()
# Initially pick the cell at this location.
picker.Pick(85, 126, 0, ren)
renWin.Render()
iren.Start()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment