def show_one_timestep(self, date): # Visualize the exposed zones for one time step date_to_vis = datetime.datetime.strptime(date, '%m/%d/%Y %H:%M:%S') print("You are visualizing: ", date_to_vis.strftime("%b %d %Y %H:%M:%S")) ind_date_to_vis = np.where( date_to_vis.strftime("%b %d %Y %H:%M:%S") == np.array( self.timeline))[0][0] ray_directions = self.directions[ind_date_to_vis] ray_directions = -np.ones( (self.posture.number_faces, 3)) * ray_directions ray_origins = self.posture.get_triangles_center - \ ray_directions*self.posture.get_max_bounds inf = self.posture.get_posture.ray.intersects_first( ray_origins=ray_origins, ray_directions=ray_directions) expo_mask = (inf == np.arange(self.posture.number_faces)) col = np.zeros((self.posture.number_faces, 3)) # Black color col[expo_mask] = [255, 255, 255] #White color vtkmeshes = trimesh2vtk(self.posture.get_posture) vtkmeshes.cellColors(col, cmap='Greys_r') show(vtkmeshes)
def plot_stl_vertices_curvature(struct_seg, num_segments, color_segmetns, surface_seg, vertices, Cmin, Cmax, title): """Функция для прорисовки вершин stl объекта, основанных на цвете по кривизне""" for j in range(struct_seg.shape[0]): for i in range(num_segments.shape[0]): faces = copy.deepcopy(surface_seg[j][i][0]) mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) vtkmeshes = trimesh2vtk(mesh) vtkmeshes1 = trimesh2vtk(mesh) # vtkmeshes.pointColors(Cmin, cmap='jet') Cmin1, Cmax1 = copy.deepcopy(Cmin), copy.deepcopy(Cmax) min_max_Cmin = np.array( [np.mean(Cmin) - np.std(Cmin), np.mean(Cmin) + np.std(Cmin)]) min_max_Cmax = np.array( [np.mean(Cmax) - np.std(Cmax), np.mean(Cmax) + np.std(Cmax)]) for i in range(Cmin.shape[0]): if Cmin1[i] > min_max_Cmin[1]: Cmin1[i] = min_max_Cmin[1] elif Cmin1[i] < min_max_Cmin[0]: Cmin1[i] = min_max_Cmin[0] if Cmax1[i] > min_max_Cmax[1]: Cmax1[i] = min_max_Cmax[1] elif Cmax1[i] < min_max_Cmax[0]: Cmax1[i] = min_max_Cmax[0] vtkmeshes.pointColors(Cmin1, cmap='jet') vtkmeshes1.pointColors(Cmax1, cmap='jet') vtkmeshes.addScalarBar(title="Cmin") vtkmeshes1.addScalarBar(title="Cmax") show([vtkmeshes, vtkmeshes1], N=2, bg='w', axes=1)
def plot_stl_vertices_klast(struct_seg, num_segments, color_segmetns, surface_seg, vertices, y_kmeans, title): """Функция для прорисовки вершин stl объекта, основанных на цвете по кривизне""" for j in range(struct_seg.shape[0]): for i in range(num_segments.shape[0]): faces = copy.deepcopy(surface_seg[j][i][0]) mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) vtkmeshes = trimesh2vtk(mesh) vtkmeshes.pointColors(y_kmeans, cmap='jet') vtkmeshes.addScalarBar(title="Cmin-Cmax_k_means") show(vtkmeshes)
def show_beta_coefficients(self, beta_coeff): """ beta_coeff can be diff or refl """ if (beta_coeff == 'diff'): this_beta = self.beta_coeff[:, 0] elif (beta_coeff == 'refl'): this_beta = self.beta_coeff[:, 1] else: raise TypeErro("Value not recognise! It can be 'diff' or 'refl'") this_beta = this_beta / pi vtkmeshes = trimesh2vtk(self.my_file) vtkmeshes.cellColors(this_beta, cmap='jet', vmin=0., vmax=1.) vtkmeshes.addScalarBar(title="Beta coefficients") show(vtkmeshes)
def show_one_timestep_received(self, one_timestep): #row is timestep #column is triangle file_out_full = "output/{}_fullBody.txt".format(self.output_name) total_body_output = np.loadtxt(file_out_full) if (one_timestep < 0 or one_timestep > np.shape(total_body_output)[0]): raise TypeError("Timestep must be smaller than {}".format( np.shape(total_body_output)[0])) col = total_body_output[one_timestep - 1, :] vtkmeshes = trimesh2vtk(self.posture.get_posture) vtkmeshes.cellColors(col, cmap='jet') vtkmeshes.addScalarBar(title="J/m^2") show(vtkmeshes)
def plot_stl_faces_color_curvature(struct_seg, num_segments, surface_seg, vertices, curvature_face_klast, title): """Функция для прорисовки фасет stl объекта, основанных на цвете по кривизне для каждой фасеты""" for j in range(struct_seg.shape[0]): for i in range(num_segments.shape[0]): faces = copy.deepcopy(surface_seg[j][i][0]) meshes = [ trimesh.Trimesh(vertices=vertices, faces=faces, process=False) for i in range(2) ] Cmin1, Cmax1 = copy.deepcopy( curvature_face_klast[:, 0]), copy.deepcopy( curvature_face_klast[:, 1]) #np.max(Cmin1)-np.min(Cmin1) meshes[0].visual.face_colors = trimesh.visual.interpolate( curvature_face_klast[:, 0], color_map='jet') meshes[1].visual.face_colors = trimesh.visual.interpolate( curvature_face_klast[:, 1], color_map='jet') # create a scene containing the mesh and colorbar # pyplot.pcolor(Cmin1) #pyplot.colorbar() #scene = trimesh.Scene([mesh]) # setup the normalization and the colormap normalize = mcolors.Normalize(vmin=np.min(Cmin1), vmax=np.max(Cmin1)) colormap = cm.jet scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap) scalarmappaple.set_array(Cmin1) pyplot.colorbar(scalarmappaple) vtkmeshes = [trimesh2vtk(m) for m in meshes] vtkmeshes[0].addScalarBar(title="Cmin") vtkmeshes[1].addScalarBar(title="Cmax") #vp = Plotter(title="Cmin", interactive=0, axes=3) #vp +=vtkmeshes #vp.show(resetcam=0) #vp.show() show([vtkmeshes[0], vtkmeshes[1]], interactive=0, N=2, bg='w', axes=1) #bg2='wheat',
""" trimesh to vtkplotter interoperability """ # Install trimesh with: # sudo apt install python3-rtree # pip install rtree shapely # conda install trimesh import trimesh import vtkplotter from vtkplotter import trimesh2vtk, vtk2trimesh url = 'https://raw.githubusercontent.com/mikedh/trimesh/master/models/' filename = vtkplotter.download(url + 'machinist.XAML') mesh = trimesh.load(filename) vmesh = trimesh2vtk(mesh) # returns a Mesh(vtkActor) object from Trimesh vtkplotter.show(mesh) # vtkplotter visualizer (conversion is on the fly) trimsh_reconverted = vtk2trimesh(vmesh) trimsh_reconverted.show() # this is the trimesh built-in visualizer
def test_isocell_ray_casting(): # Create source to ray trace # sphere = pv.Sphere(radius=0.85) sphere1 = vp.Sphere(r=0.85, c="r", alpha=0.1).lw(0.1) mesh = trimesh.Trimesh(vertices=sphere1.points(), faces=sphere1.faces(), process=False, use_embree=True) # mesh = trimesh.creation.icosphere() # Create isocell rays isocell = Isocell(rays=1000, div=5, isrand=0, draw_cells=True) drays = (( isocell.points @ r.vrrotvec2mat([0, 0, 1], [0, 0, 1]).T).T).reshape( -1, 3) # Define line segment start = [0, 0, 0] endPoints = drays # intersects_location requires origins to be the same shape as vectors origins = np.tile(np.expand_dims(start, 0), (len(drays), 1)) # do the actual ray- mesh queries points, index_ray, index_tri = mesh.ray.intersects_location( origins, drays, multiple_hits=False) # for each hit, find the distance along its vector # you could also do this against the single camera Z vector depth = trimesh.util.diagonal_dot(points - start, drays[index_ray]) locs = trimesh.points.PointCloud(points) # # stack rays into line segments for visualization as Path3D # ray_visualize = trimesh.load_path(np.hstack((origins, origins + drays * 1.2)).reshape(-1, 2, 3)) # render the result with vtkplotter axes = vp.addons.buildAxes(vp.trimesh2vtk(mesh), c='k', zxGrid2=True) # vp.show(mesh, ray_visualize, axes, locs, axes=4) lines = vp.Lines(origins, drays, c='b') vp.show(vp.trimesh2vtk(mesh).alpha(0.1).lw(0.1), lines, axes, locs, axes=4) # Render the result with pyvista sphere = pv.PolyData( mesh.vertices, np.hstack((np.full((len(mesh.faces), 1), 3), mesh.faces))) p = pv.Plotter() p.add_mesh(sphere, show_edges=True, opacity=0.5, color="w", lighting=False, label="Test Mesh") # p.add_arrows(origins[1,:], drays[1,:], mag=1, color=True, opacity=0.5, ) p.add_lines(np.hstack([origins, drays]).reshape(-1, 3), color='b') # intersections = pv.PolyData(points) # p.add_mesh(intersections, color="maroon", point_size=25, label="Intersection Points") # for i, stop in enumerate(drays): # # # Perform ray trace # points, ind = sphere.ray_trace(start, stop) # # # Create geometry to represent ray trace # ray = pv.Line(start, stop) # intersection = pv.PolyData(points) # # # # # pv.plot_arrows(np.array(start),np.array(stop)) # # pv.plot_arrows(np.array(start),np.array(stop)) # p.add_mesh(ray, color="blue", line_width=5, label="Ray Segment") # p.add_mesh(intersection, color="maroon", # point_size=25, label="Intersection Points") # p.add_legend() p.show()
calvis.calvis_clear() calvis.mesh_path(meshpath) calvis.load_trimesh() calvis.fit_SMPL_model_to_mesh(SMPL_basicModel, gender=genders[i]) calvis.segmentation(N=N) calvis.assemble_mesh_signatur(m=m) calvis.assemble_slice_statistics() cc = calvis.chest_circumference() ccslice_2D, to_3D = cc.to_planar() cc_actor = trimesh2vtk(cc).unpack()[0].lw(2) wc = calvis.waist_circumference() wcslice_2D, to_3D = wc.to_planar() wc_actor = trimesh2vtk(wc).unpack()[0].lw(2) pc = calvis.pelvis_circumference() pcslice_2D, to_3D = pc.to_planar() pc_actor = trimesh2vtk(pc).unpack()[0].lw(2) text = Text2D("Subject no. %s" % (i + 1)) # Print info #print("Chest circunference length is: %s" % ccslice_2D.length) #print("Waist circunference length is: %s" % wcslice_2D.length) #print("Pelvis circunference length is: %s" % pcslice_2D.length)
""" trimesh to vtkplotter interoperability """ # Install trimesh with: # sudo apt install python3-rtree # pip install rtree shapely # conda install trimesh import trimesh from vtkplotter import download, trimesh2vtk, show url = 'https://raw.githubusercontent.com/mikedh/trimesh/master/models/' filename = download(url + 'machinist.XAML') mesh = trimesh.load(filename) actor = trimesh2vtk(mesh) # returns a Actor(vtkActor) object from Trimesh # Any of these will work: show(mesh) # conversion is on the fly (don't need 'actor') # or #actor.show() # or #show(actor) # or mesh.show() # this is the trimesh built-in visualizer
def view_mesh( meshes: list, output_file: str, mesh_names: list = [], patient_data="", plid="", scan_path="", ): logging.info("Opening mesh viewer.") settings.useDepthPeeling = True vmeshes = [] def slider1(widget, event): value = widget.GetRepresentation().GetValue() vmeshes[index].color(value) def slider2(widget, event): value = widget.GetRepresentation().GetValue() vmeshes[index].opacity(value) def buttonfunc(): global index bu.switch() index = mesh_names.index(bu.status()) def background_swap(): bg_button.switch() vp.backgroundRenderer.SetBackground(colors.getColor( bg_button.status())) def ar_view(): save() holo_registration_wrapper.start_viewer(output_file, plid) def save(): write_mesh_as_glb_with_colour(vmeshes, output_file) def open_scan(): external_2d_viewer.start(scan_path) vp = Plotter( sharecam=False, bg="./core/client/images/hologram_icon2.png", bg2='black', shape=[1, 1], size=[640, 480], interactive=False, ) # pos = position corner number: horizontal [1-4] or vertical [11-14] vp.addSlider2D(slider1, -9, 9, value=0, pos=4, title="color number") left_side_x = 0.1 vp.addSlider2D( slider2, xmin=0.00, xmax=1.00, value=0.5, pos=14, c="blue", title="alpha value (opacity)", ) bu = vp.addButton( buttonfunc, pos=(0.5, 0.05), # x,y fraction from bottom left corner states=mesh_names, font=font_style, # arial, courier, times size=25, bold=True, italic=False, ) save_button = vp.addButton( save, pos=(left_side_x, 0.05), # x,y fraction from bottom left corner states=["Save"], font=font_style, # arial, courier, times size=25, bold=True, italic=False, ) if holo_registration_wrapper.is_supported(plid): ar_button = vp.addButton( ar_view, pos=(left_side_x, 0.20), states=["AR View"], font=font_style, size=25, bold=True, italic=False, ) if scan_path != "": scan_button = vp.addButton( open_scan, pos=(left_side_x, 0.15), states=["2D View"], font=font_style, size=25, bold=True, italic=False, ) bg_button = vp.addButton( background_swap, pos=(left_side_x, 0.10), # x,y fraction from bottom left corner states=["black", "white"], font=font_style, size=25, bold=True, italic=False, ) for i in range(0, len(meshes)): vmeshes.append(trimesh2vtk(meshes[i], alphaPerCell=True)) doc = Text2D(patient_data, pos=4, c=(0, 113, 197)) vp.show(doc) vp.backgroundRenderer.GetActiveCamera().Zoom(1.3) vp.show(vmeshes) interactive()
""" trimesh to vtkplotter interoperability """ # Install trimesh with: # sudo apt install python3-rtree # pip install rtree shapely # conda install trimesh import trimesh import vtkplotter from vtkplotter import trimesh2vtk, vtk2trimesh url = 'https://raw.githubusercontent.com/mikedh/trimesh/master/models/' filename = vtkplotter.download(url + 'machinist.XAML') mesh = trimesh.load(filename) vtkplotter.show(mesh) # vtkplotter visualizer (conversion is on the fly) # explicit conversion vmesh = trimesh2vtk(mesh) # returns a vtkplotter.Mesh(vtkActor) object trimsh_reconverted = vtk2trimesh(vmesh) trimsh_reconverted.show() # this is the trimesh built-in visualizer