def test_draco(): n_points = 12 img = sphere_tissue_image(size=100, n_points=n_points) draco = DracoMesh(img) assert draco.point_topomesh.nb_wisps(0) == n_points + 1 draco.delaunay_adjacency_complex(surface_cleaning_criteria=[]) image_tetrahedra = np.sort(draco.image_cell_vertex.keys()) image_tetrahedra = image_tetrahedra[image_tetrahedra[:, 0] != 1] draco_tetrahedra = np.sort([ list(draco.triangulation_topomesh.borders(3, t, 3)) for t in draco.triangulation_topomesh.wisps(3) ]) delaunay_consistency = jaccard_index(image_tetrahedra, draco_tetrahedra) draco.adjacency_complex_optimization(n_iterations=2) assert draco.triangulation_topomesh.nb_region_neighbors(0, 2) == n_points image_tetrahedra = np.sort(draco.image_cell_vertex.keys()) image_tetrahedra = image_tetrahedra[image_tetrahedra[:, 0] != 1] draco_tetrahedra = np.sort([ list(draco.triangulation_topomesh.borders(3, t, 3)) for t in draco.triangulation_topomesh.wisps(3) ]) draco_consistency = jaccard_index(image_tetrahedra, draco_tetrahedra) # print delaunay_consistency,' -> ',draco_consistency assert draco_consistency == 1 or (draco_consistency >= 0.9 and draco_consistency > delaunay_consistency) triangular = ['star', 'remeshed', 'projected', 'regular', 'flat'] image_dual_topomesh = draco.dual_reconstruction( reconstruction_triangulation=triangular, adjacency_complex_degree=3) image_volumes = array_dict( nd.sum(np.ones_like(img), img, index=np.unique(img)[1:]) * np.prod(img.voxelsize), np.unique(img)[1:]) compute_topomesh_property(image_dual_topomesh, 'volume', 3) draco_volumes = image_dual_topomesh.wisp_property('volume', 3) for c in image_dual_topomesh.wisps(3): assert np.isclose(image_volumes[c], draco_volumes[c], 0.33)
def test_draco(): n_points = 12 img = sphere_tissue_image(size=100,n_points=n_points) draco = DracoMesh(img) assert draco.point_topomesh.nb_wisps(0) == n_points+1 draco.delaunay_adjacency_complex(surface_cleaning_criteria = []) image_tetrahedra = np.sort(draco.image_cell_vertex.keys()) image_tetrahedra = image_tetrahedra[image_tetrahedra[:,0] != 1] draco_tetrahedra = np.sort([list(draco.triangulation_topomesh.borders(3,t,3)) for t in draco.triangulation_topomesh.wisps(3)]) delaunay_consistency = jaccard_index(image_tetrahedra, draco_tetrahedra) draco.adjacency_complex_optimization(n_iterations=2) assert draco.triangulation_topomesh.nb_region_neighbors(0,2) == n_points image_tetrahedra = np.sort(draco.image_cell_vertex.keys()) image_tetrahedra = image_tetrahedra[image_tetrahedra[:,0] != 1] draco_tetrahedra = np.sort([list(draco.triangulation_topomesh.borders(3,t,3)) for t in draco.triangulation_topomesh.wisps(3)]) draco_consistency = jaccard_index(image_tetrahedra, draco_tetrahedra) # print delaunay_consistency,' -> ',draco_consistency assert draco_consistency == 1 or (draco_consistency >= 0.9 and draco_consistency > delaunay_consistency) triangular = ['star','remeshed','projected','regular','flat'] image_dual_topomesh = draco.dual_reconstruction(reconstruction_triangulation = triangular, adjacency_complex_degree=3) image_volumes = array_dict(nd.sum(np.ones_like(img),img,index=np.unique(img)[1:])*np.prod(img.resolution),np.unique(img)[1:]) compute_topomesh_property(image_dual_topomesh,'volume',3) draco_volumes = image_dual_topomesh.wisp_property('volume',3) for c in image_dual_topomesh.wisps(3): assert np.isclose(image_volumes[c],draco_volumes[c],0.33)
def create_CGAL_topomesh(img, mesh_fineness=1.0): """ """ dirname = str(shared_data(openalea.cgal_meshing).parent.parent+'/') start_time = time() print "--> Input Image" img_graph = graph_from_image(img,spatio_temporal_properties=['volume','barycenter'],ignore_cells_at_stack_margins = False,property_as_real=False) img_labels = np.array(list(img_graph.vertices())) img_volumes = np.array([img_graph.vertex_property('volume')[v] for v in img_graph.vertices()]) print " --> ",img_labels.shape[0]," Objects, ", img_volumes[2:].mean()," microm3 per object" facet_distance = np.power(img_volumes[2:].mean(),1/3.)/(4.5*np.pi*mesh_fineness) print " --> Facet Distance : ",facet_distance print " --> Converting to 8bit" img_neighbors = np.array([list(img_graph.neighbors(v)) for v in img_graph.vertices()]) count_labels = np.zeros(256) img_graph.add_vertex_property('8bit_labels') if img_labels.shape[0] < 255: for i,v in enumerate(img_graph.vertices()): img_graph.vertex_property('8bit_labels')[v] = i+2 else: for v in img_graph.vertices(): possible_labels = np.array([]) select = 0 while possible_labels.size == 0: possible_labels = set(np.arange(2,256)) possible_labels = possible_labels.difference(set(np.where(count_labels>count_labels[2:].min()+select)[0])) #possible_labels = possible_labels.difference(set(np.where(count_labels>count_labels[2:].min()+1)[0])) neighbor_labels = set() for n in img_graph.neighbors(v): try: neighbor_label = {img_graph.vertex_property('8bit_labels')[n]} for n2 in img_graph.neighbors(n): if n2 != v: try: neighbor_label = {img_graph.vertex_property('8bit_labels')[n2]} except KeyError: neighbor_label = set() pass neighbor_labels = neighbor_labels.union(neighbor_label) except KeyError: neighbor_label = set() pass neighbor_labels = neighbor_labels.union(neighbor_label) possible_labels = np.array(list(possible_labels.difference(neighbor_labels)),np.uint8) if possible_labels.size == 0: select += 1 #print neighbor_labels new_label = possible_labels[np.random.randint(possible_labels.size)] img_graph.vertex_property('8bit_labels')[v] = new_label count_labels[new_label] += 1 #print v, ' -> ', new_label new_labels = np.ones(img.max()+1,np.uint8) new_labels[img_labels] = np.array([img_graph.vertex_property('8bit_labels')[v] for v in img_graph.vertices()],np.uint8) if np.unique(new_labels).shape[0]<255: label_index = np.ones(256) label_index[np.unique(new_labels)] = np.arange(new_labels.shape[0])+1 for v in img_graph.vertices(): img_graph.vertex_property('8bit_labels')[v] = label_index[img_graph.vertex_property('8bit_labels')[v]] new_labels = np.ones(img.max()+1,np.uint8) #new_labels[img_labels] = np.array([img_graph.vertex_property('8bit_labels')[v] for v in img_graph.vertices()],np.uint8) for v in img_graph.vertices(): new_labels[v] = img_graph.vertex_property('8bit_labels')[v] mod_img = np.array(new_labels[img],np.uint8) inrfile = dirname+"tmp/8bit_image.inr.gz" imsave(inrfile,SpatialImage(mod_img)) end_time = time() print "<-- Input Image [",end_time-start_time,"s]" facet_angle = 30.0 facet_size = 40.0 edge_ratio = 4.0 cell_size = 60.0 start_time = time() print "--> Building CGAL Mesh" outputfile = dirname+"tmp/CGAL_output_mesh.mesh" buildCGALMesh(inrfile,outputfile,facet_angle,facet_size,facet_distance,edge_ratio,cell_size) end_time = time() print "<-- Building CGAL Mesh [",end_time-start_time,"s]" mesh = CGALMesh() mesh.createMesh(outputfile) start_time = time() print "--> Re-Indexing Components" mesh.components = np.unique(mesh.tri_subdomains) new_mesh = CGALMesh() new_mesh.createMesh(outputfile) new_mesh.tri_subdomains = np.ones_like(mesh.tri_subdomains) new_mesh.tetra_subdomains = np.ones_like(mesh.tetra_subdomains) new_mesh.tri_subdomains[np.where(mesh.tri_subdomains == mesh.components[0])] = 1 new_mesh.tetra_subdomains[np.where(mesh.tetra_subdomains == mesh.components[0])] = 1 for c in mesh.components[1:]: cell_labels = np.where(new_labels == c)[0] n_cells = cell_labels.size if n_cells > 0: # print " --> Component ",c," -> ",n_cells," Cells" cell_tetrahedra = mesh.tetrahedra[np.where(mesh.tetra_subdomains==c)] #if n_cells == 1: if False: print " --> Component ",c," -> 1 Object (",n_cells," Cell) : ",cell_labels,"(",img_graph.vertex_property('8bit_labels')[cell_labels[0]],")" new_mesh.tetra_subdomains[np.where(mesh.tetra_subdomains == c)] = cell_labels[0] new_mesh.tri_subdomains[np.where(mesh.tri_subdomains == c)] = cell_labels[0] else: cell_tetrahedra_components = np.zeros(cell_tetrahedra.shape[0],int) tetrahedra_component_correspondance = {} tetra_centers = np.mean(mesh.vertices[cell_tetrahedra],axis=1) for t, tetra in enumerate(cell_tetrahedra): if cell_tetrahedra_components[t] == 0: neighbour_tetrahedra = np.unique(np.append(np.where(cell_tetrahedra==tetra[0])[0],np.append(np.where(cell_tetrahedra==tetra[1])[0],np.append(np.where(cell_tetrahedra==tetra[2])[0],np.where(cell_tetrahedra==tetra[3])[0])))) if (cell_tetrahedra_components[neighbour_tetrahedra].max()>0): neighbour_components = cell_tetrahedra_components[neighbour_tetrahedra][np.where(cell_tetrahedra_components[neighbour_tetrahedra]>0)] min_component = np.array([tetrahedra_component_correspondance[component] for component in neighbour_components]).min() for component in neighbour_components: tetrahedra_component_correspondance[tetrahedra_component_correspondance[component]] = min_component tetrahedra_component_correspondance[component] = min_component cell_tetrahedra_components[neighbour_tetrahedra] = min_component else: tetrahedra_component_correspondance[cell_tetrahedra_components.max()+1] = int(cell_tetrahedra_components.max()+1) cell_tetrahedra_components[neighbour_tetrahedra] = int(cell_tetrahedra_components.max()+1) for component in tetrahedra_component_correspondance: label = component while label != tetrahedra_component_correspondance[label]: label = tetrahedra_component_correspondance[label] tetrahedra_component_correspondance[component] = tetrahedra_component_correspondance[label] component_labels = np.unique([tetrahedra_component_correspondance[component] for component in cell_tetrahedra_components]) n_objects = component_labels.size # if n_objects != n_cells: # print tetrahedra_component_correspondance for component in tetrahedra_component_correspondance: tetrahedra_component_correspondance[component] = np.where(component_labels == tetrahedra_component_correspondance[component])[0][0] for component in tetrahedra_component_correspondance: cell_tetrahedra_components[np.where(cell_tetrahedra_components == component)] = tetrahedra_component_correspondance[component] tetrahedra_object_centers = np.zeros((n_objects,3)) tetrahedra_object_centers[:,0] = nd.sum(tetra_centers[:,0],cell_tetrahedra_components,index=xrange(n_objects))/nd.sum(np.ones_like(cell_tetrahedra_components),cell_tetrahedra_components,index=xrange(n_objects)) tetrahedra_object_centers[:,1] = nd.sum(tetra_centers[:,1],cell_tetrahedra_components,index=xrange(n_objects))/nd.sum(np.ones_like(cell_tetrahedra_components),cell_tetrahedra_components,index=xrange(n_objects)) tetrahedra_object_centers[:,2] = nd.sum(tetra_centers[:,2],cell_tetrahedra_components,index=xrange(n_objects))/nd.sum(np.ones_like(cell_tetrahedra_components),cell_tetrahedra_components,index=xrange(n_objects)) img_points = np.array([img_graph.vertex_property('barycenter')[v] for v in cell_labels]) tetrahedra_labels = cell_labels[vq(tetrahedra_object_centers,img_points)[0]] # img_points = np.array([img_graph.vertex_property('barycenter')[v] for v in img_labels]) # tetrahedra_labels = img_labels[vq(tetrahedra_object_centers,img_points)[0]] cell_triangles = mesh.triangles[np.where(mesh.tri_subdomains==c)] cell_triangles_components = np.array([np.unique(cell_tetrahedra_components[np.where(cell_tetrahedra==tri[0])[0]])[0] for tri in cell_triangles]) print " --> Component ",c," -> ",n_objects," Objects (",n_cells," Cells) : ",tetrahedra_labels new_mesh.tetra_subdomains[np.where(mesh.tetra_subdomains == c)] = tetrahedra_labels[cell_tetrahedra_components] new_mesh.tri_subdomains[np.where(mesh.tri_subdomains == c)] = tetrahedra_labels[cell_triangles_components] mesh.tri_subdomains = new_mesh.tri_subdomains mesh.tetra_subdomains = new_mesh.tetra_subdomains mesh.components = np.unique(mesh.tri_subdomains) print mesh.vertices.shape[0],"Vertices, ",mesh.triangles.shape[0],"Triangles, ",mesh.tetrahedra.shape[0],"Tetrahedra, ",mesh.components.shape[0]," Components" end_time = time() print "<-- Re-Indexing Components [",end_time-start_time,"s]" mesh.saveCGALfile(outputfile) start_time = time() print "--> Creating Topomesh" mesh = CGALMesh() mesh.createMesh(outputfile) mesh.generatePropertyTopomesh() positions = array_dict(mesh.vertex_positions.values()*np.array(img.resolution),keys=list(mesh.topo_mesh.wisps(0))) compute_topomesh_property(mesh.topo_mesh,'barycenter',degree=0,positions=positions) end_time = time() print "<-- Creating Topomesh [",end_time-start_time,"s]" return mesh.topo_mesh
figure = plt.figure(2) figure.clf() spider_plot(figure,np.array([dual_quality[c] for c in quality_criteria]),color1=np.array([0.3,0.6,1.]),color2=np.array([1.,0.,0.]),xlabels=quality_criteria,ytargets=0.8 * np.ones_like(quality_criteria,float),n_points=100*len(quality_criteria),linewidth=2,smooth_factor=0.0,spline_order=1) plt.show(block=False) raw_input() triangular_string = "" for t in triangular: triangular_string += t+"_" topomesh_filename = dirname+"/output_meshes/"+filename+"/"+filename+"_"+triangular_string+"topomesh.ply" save_ply_property_topomesh(image_dual_topomesh,topomesh_filename,color_faces=True) from openalea.mesh.property_topomesh_analysis import compute_topomesh_property, compute_topomesh_vertex_property_from_faces compute_topomesh_property(image_dual_topomesh,'eccentricity',2) compute_topomesh_vertex_property_from_faces(image_dual_topomesh,'eccentricity',weighting='uniform') world.add(image_dual_topomesh ,'actual_dual_reconstuction') raw_input() # raw_file = "/Users/gcerutti/Developpement/openalea/openalea_meshing_data/share/data/nuclei_images/olli01_lti6b_150421_sam01_t000/olli01_lti6b_150421_sam01_t000_PIN.inr.gz" # raw_img = imread(raw_file) # raw_img = SpatialImage(np.concatenate([raw_img[:,:,35:],np.ones((raw_img.shape[0],raw_img.shape[1],5))],axis=2).astype(np.uint16),resolution=raw_img.resolution) # world.add(raw_img,"raw_image") from openalea.draco_stem.stem.tissue_mesh_quality import evaluate_topomesh_quality quality_criteria=["Mesh Complexity","Triangle Area Deviation","Triangle Eccentricity","Cell Volume Error","Vertex Distance","Cell Convexity","Epidermis Cell Angle","Vertex Valence","Cell 2 Adjacency"] draco_quality = evaluate_topomesh_quality(image_dual_topomesh,quality_criteria,image=draco.segmented_image,image_cell_vertex=draco.image_cell_vertex,image_labels=draco.image_labels,image_cell_volumes=draco.image_cell_volumes)
def optimize_topomesh(input_topomesh,omega_forces={'regularization':0.00,'laplacian':1.0,'planarization':0.27,'epidermis_planarization':0.07},omega_regularization_max=None,iterations=20,edge_flip=False,**kwargs): """ """ topomesh = deepcopy(input_topomesh) preparation_start_time = time() # topomesh.update_wisp_property('barycenter',degree=0,values=initial_vertex_positions,keys=np.array(list(topomesh.wisps(0)))) compute_topomesh_property(topomesh,'valence',degree=0) compute_topomesh_property(topomesh,'borders',degree=1) compute_topomesh_property(topomesh,'vertices',degree=1) compute_topomesh_property(topomesh,'vertices',degree=2) compute_topomesh_property(topomesh,'vertices',degree=3) compute_topomesh_property(topomesh,'cells',degree=2) compute_topomesh_property(topomesh,'cells',degree=1) compute_topomesh_property(topomesh,'cells',degree=0) compute_topomesh_property(topomesh,'length',degree=1) compute_topomesh_property(topomesh,'barycenter',degree=3) compute_topomesh_property(topomesh,'barycenter',degree=2) compute_topomesh_property(topomesh,'barycenter',degree=1) triangular_mesh = kwargs.get('triangular_mesh',True) if triangular_mesh: compute_topomesh_triangle_properties(topomesh) compute_topomesh_property(topomesh,'normal',degree=2) compute_topomesh_property(topomesh,'angles',degree=2) compute_topomesh_property(topomesh,'epidermis',degree=0) compute_topomesh_property(topomesh,'epidermis',degree=1) # compute_topomesh_property(topomesh,'epidermis',degree=3) if omega_forces.has_key('planarization'): start_time = time() print "--> Computing interfaces" for cid in topomesh.wisps(3): for n_cid in topomesh.border_neighbors(3,cid): if (n_cid<cid) and (not (n_cid,cid) in topomesh._interface[3].values()): iid = topomesh._interface[3].add((n_cid,cid),None) end_time = time() print "<-- Computing interfaces[",end_time-start_time,"s]" preparation_end_time = time() print "--> Preparing topomesh [",preparation_end_time-preparation_start_time,"s]" display = kwargs.get('display',False) if display: pass optimization_start_time = time() if omega_forces.has_key('regularization'): if omega_regularization_max is None: omega_regularization_max = omega_forces['regularization'] gradient_derivatives = kwargs.get("gradient_derivatives",[]) cell_vertex_motion = kwargs.get("cell_vertex_motion",False) if cell_vertex_motion: image_cell_vertex = deepcopy(kwargs.get("image_cell_vertex",{})) for v in image_cell_vertex.keys(): image_cell_vertex[v] = image_cell_vertex[v]*np.array(kwargs.get("image_resolution",(1.0,1.0,1.0))) #image_cell_vertex[v] = image_cell_vertex[v] compute_topomesh_property(topomesh,'cells',degree=0) vertex_cell_neighbours = topomesh.wisp_property('cells',degree=0) epidermis_vertices = np.array(list(topomesh.wisps(0)))[np.where(topomesh.wisp_property('epidermis',degree=0).values())] start_time = time() print "--> Computing mesh cell vertices" mesh_cell_vertex = {} for v in topomesh.wisps(0): if len(vertex_cell_neighbours[v]) == 5: for k in xrange(5): vertex_cell_labels = tuple([c for c in vertex_cell_neighbours[v]][:k])+tuple([c for c in vertex_cell_neighbours[v]][k+1:]) if not mesh_cell_vertex.has_key(vertex_cell_labels): mesh_cell_vertex[vertex_cell_labels] = v if len(vertex_cell_neighbours[v]) == 4: vertex_cell_labels = tuple([c for c in vertex_cell_neighbours[v]]) mesh_cell_vertex[vertex_cell_labels] = v if v in epidermis_vertices: # and count_l1_cells(vertex_cell_neighbours[v]) == 4: for k in xrange(4): vertex_cell_labels = (1,) + tuple([c for c in vertex_cell_neighbours[v]][:k])+tuple([c for c in vertex_cell_neighbours[v]][k+1:]) if not mesh_cell_vertex.has_key(vertex_cell_labels): mesh_cell_vertex[vertex_cell_labels] = v if (len(vertex_cell_neighbours[v]) == 3) and (v in epidermis_vertices): # and (count_l1_cells(vertex_cell_neighbours[v]) == 3): vertex_cell_labels = (1,) + tuple([c for c in vertex_cell_neighbours[v]]) mesh_cell_vertex[vertex_cell_labels] = v end_time = time() print "<-- Computing mesh cell vertices [",end_time-start_time,"s]" cell_vertex_matching = vq(np.sort(array_dict(image_cell_vertex).keys()),np.sort(array_dict(mesh_cell_vertex).keys())) matched_image_index = np.where(cell_vertex_matching[1] == 0)[0] matched_mesh_index = cell_vertex_matching[0][np.where(cell_vertex_matching[1] == 0)[0]] matched_image_cell_vertex = np.array(image_cell_vertex.values())[matched_image_index] matched_keys = np.sort(np.array(image_cell_vertex.keys()))[matched_image_index] matched_mesh_vertices = np.array(mesh_cell_vertex.values())[cell_vertex_matching[0][np.where(cell_vertex_matching[1] == 0)[0]]] matched_keys = np.sort(np.array(mesh_cell_vertex.keys()))[matched_mesh_index] initial_vertex_positions = array_dict(topomesh.wisp_property('barycenter',0).values(list(topomesh.wisps(0))),list(topomesh.wisps(0))) final_vertex_positions = array_dict() fixed_vertex = array_dict(np.array([False for v in topomesh.wisps(0)]),np.array(list(topomesh.wisps(0)))) for i,v in enumerate(matched_mesh_vertices): if not np.isnan(matched_image_cell_vertex[i]).any(): final_vertex_positions[v] = matched_image_cell_vertex[i] print topomesh.wisp_property('barycenter',0)[v]," -> ",final_vertex_positions[v] fixed_vertex[v] = True matched_mesh_vertices = final_vertex_positions.keys() sigma_deformation_initial = kwargs.get("sigma_deformation",np.sqrt(3)/4.) sigma_deformation = sigma_deformation_initial*np.ones_like(np.array(list(topomesh.wisps(0))),float) if cell_vertex_motion: sigma_deformation[np.where(fixed_vertex.values())[0]] = 0. iterations_per_step = kwargs.get('iterations_per_step',1) for iteration in xrange(iterations/iterations_per_step+1): print "_____________________________" print "" print " Iteration ",iteration print "_____________________________" start_time = time() gaussian_sigma = kwargs.get('gaussian_sigma',10.0) target_areas = kwargs.get('target_areas',None) property_topomesh_vertices_deformation(topomesh,iterations=iterations_per_step,omega_forces=omega_forces,sigma_deformation=sigma_deformation,gradient_derivatives=gradient_derivatives,resolution=kwargs.get("image_resolution",(1.0,1.0,1.0)),gaussian_sigma=gaussian_sigma,target_areas=target_areas) if cell_vertex_motion: vertex_start_time = time() print "--> Moving cell vertices" if iteration <= (iterations/iterations_per_step+1)/1.: #topomesh.update_wisp_property('barycenter',degree=0,values=((iterations/iterations_per_step+1-(iteration+1))*initial_vertex_positions.values(matched_mesh_vertices) + (iteration+1)*final_vertex_positions.values(matched_mesh_vertices))/(iterations/iterations_per_step+1),keys=matched_mesh_vertices,erase_property=False) for v in matched_mesh_vertices: topomesh.wisp_property('barycenter',degree=0)[v] = ((iterations/iterations_per_step+1-(iteration+1))*initial_vertex_positions[v] + (iteration+1)*final_vertex_positions[v])/(iterations/iterations_per_step+1) vertex_end_time = time() print "<-- Moving cell vertices [",vertex_end_time-vertex_start_time,"s]" compute_topomesh_property(topomesh,'length',degree=1) compute_topomesh_property(topomesh,'barycenter',degree=3) compute_topomesh_property(topomesh,'barycenter',degree=2) if triangular_mesh: compute_topomesh_triangle_properties(topomesh) compute_topomesh_property(topomesh,'normal',degree=2) if edge_flip: # property_topomesh_edge_flip_optimization(topomesh,omega_energies=omega_forces,simulated_annealing=True,iterations=15,display=display) property_topomesh_edge_flip_optimization(topomesh,omega_energies=omega_forces,simulated_annealing=False,iterations=3,display=display) compute_topomesh_property(topomesh,'length',degree=1) compute_topomesh_property(topomesh,'barycenter',degree=3) compute_topomesh_property(topomesh,'barycenter',degree=2) if triangular_mesh: compute_topomesh_triangle_properties(topomesh) compute_topomesh_property(topomesh,'normal',degree=2) sigma_deformation = sigma_deformation_initial*np.power(0.95,(iteration+1)*iterations_per_step)*np.ones_like(np.array(list(topomesh.wisps(0))),float) if cell_vertex_motion: sigma_deformation[np.where(fixed_vertex.values())[0]] = 0. if omega_forces.has_key('regularization'): omega_forces['regularization'] = np.minimum(omega_forces['regularization']+(omega_regularization_max*iterations_per_step)/iterations,omega_regularization_max) if display: pass end_time = time() print "_____________________________" print "" print " [",end_time-start_time,"s]" #raw_input() print "_____________________________" optimization_end_time = time() print "--> Optimizing Topomesh [",optimization_end_time - optimization_start_time,"s]" return topomesh
cell_signals = dict(zip(df.Label.values[1:-4].astype(int),df.Value.values[1:-4])) cell_flat_barycenters = deepcopy(cell_barycenters) for c in cell_barycenters.keys(): cell_flat_barycenters[c][2] = 0. triangles = np.array(cell_barycenters.keys())[delaunay_triangulation(np.array([cell_flat_barycenters[c] for c in cell_barycenters.keys()]))] cell_topomesh = triangle_topomesh(triangles, cell_barycenters) cell_topomesh.update_wisp_property('signal',0,cell_signals) maximal_length = 15. compute_topomesh_property(cell_topomesh,'length',1) compute_topomesh_property(cell_topomesh,'triangles',1) boundary_edges = np.array(map(len,cell_topomesh.wisp_property('triangles',1).values()))==1 distant_edges = cell_topomesh.wisp_property('length',1).values() > maximal_length edges_to_remove = np.array(list(cell_topomesh.wisps(1)))[boundary_edges & distant_edges] while len(edges_to_remove) > 0: triangles_to_remove = np.concatenate(cell_topomesh.wisp_property('triangles',1).values(edges_to_remove)) for t in triangles_to_remove: cell_topomesh.remove_wisp(2,t) clean_topomesh(cell_topomesh) compute_topomesh_property(cell_topomesh,'triangles',1)
smooth_factor=0.0, spline_order=1) plt.show(block=False) raw_input() triangular_string = "" for t in triangular: triangular_string += t + "_" topomesh_filename = dirname + "/output_meshes/" + filename + "/" + filename + "_" + triangular_string + "topomesh.ply" save_ply_property_topomesh(image_dual_topomesh, topomesh_filename, color_faces=True) from openalea.mesh.property_topomesh_analysis import compute_topomesh_property, compute_topomesh_vertex_property_from_faces compute_topomesh_property(image_dual_topomesh, 'eccentricity', 2) compute_topomesh_vertex_property_from_faces(image_dual_topomesh, 'eccentricity', weighting='uniform') world.add(image_dual_topomesh, 'actual_dual_reconstuction') raw_input() # raw_file = "/Users/gcerutti/Developpement/openalea/openalea_meshing_data/share/data/nuclei_images/olli01_lti6b_150421_sam01_t000/olli01_lti6b_150421_sam01_t000_PIN.inr.gz" # raw_img = imread(raw_file) # raw_img = SpatialImage(np.concatenate([raw_img[:,:,35:],np.ones((raw_img.shape[0],raw_img.shape[1],5))],axis=2).astype(np.uint16),voxelsize=raw_img.voxelsize) # world.add(raw_img,"raw_image") from openalea.draco_stem.stem.tissue_mesh_quality import evaluate_topomesh_quality quality_criteria = [ "Mesh Complexity", "Triangle Area Deviation", "Triangle Eccentricity",
def optimize_topomesh(input_topomesh,omega_forces={'regularization':0.00,'laplacian':1.0,'planarization':0.27,'epidermis_planarization':0.07},omega_regularization_max=None,iterations=20,edge_flip=False,**kwargs): """ """ topomesh = deepcopy(input_topomesh) preparation_start_time = time() # topomesh.update_wisp_property('barycenter',degree=0,values=initial_vertex_positions,keys=np.array(list(topomesh.wisps(0)))) compute_topomesh_property(topomesh,'valence',degree=0) compute_topomesh_property(topomesh,'borders',degree=1) compute_topomesh_property(topomesh,'vertices',degree=1) compute_topomesh_property(topomesh,'vertices',degree=2) compute_topomesh_property(topomesh,'vertices',degree=3) compute_topomesh_property(topomesh,'cells',degree=2) compute_topomesh_property(topomesh,'cells',degree=1) compute_topomesh_property(topomesh,'cells',degree=0) compute_topomesh_property(topomesh,'length',degree=1) compute_topomesh_property(topomesh,'barycenter',degree=3) compute_topomesh_property(topomesh,'barycenter',degree=2) compute_topomesh_property(topomesh,'barycenter',degree=1) triangular_mesh = kwargs.get('triangular_mesh',True) if triangular_mesh: compute_topomesh_triangle_properties(topomesh) compute_topomesh_property(topomesh,'normal',degree=2) compute_topomesh_property(topomesh,'angles',degree=2) compute_topomesh_property(topomesh,'epidermis',degree=0) compute_topomesh_property(topomesh,'epidermis',degree=1) # compute_topomesh_property(topomesh,'epidermis',degree=3) if omega_forces.has_key('planarization'): start_time = time() print "--> Computing interfaces" for cid in topomesh.wisps(3): for n_cid in topomesh.border_neighbors(3,cid): if (n_cid<cid) and (not (n_cid,cid) in topomesh._interface[3].values()): iid = topomesh._interface[3].add((n_cid,cid),None) end_time = time() print "<-- Computing interfaces[",end_time-start_time,"s]" preparation_end_time = time() print "--> Preparing topomesh [",preparation_end_time-preparation_start_time,"s]" display = kwargs.get('display',False) if display: pass optimization_start_time = time() if omega_forces.has_key('regularization'): if omega_regularization_max is None: omega_regularization_max = omega_forces['regularization'] gradient_derivatives = kwargs.get("gradient_derivatives",[]) cell_vertex_motion = kwargs.get("cell_vertex_motion",False) if cell_vertex_motion: image_cell_vertex = deepcopy(kwargs.get("image_cell_vertex",{})) for v in image_cell_vertex.keys(): image_cell_vertex[v] = image_cell_vertex[v]*np.array(kwargs.get("image_voxelsize",(1.0,1.0,1.0))) #image_cell_vertex[v] = image_cell_vertex[v] compute_topomesh_property(topomesh,'cells',degree=0) vertex_cell_neighbours = topomesh.wisp_property('cells',degree=0) epidermis_vertices = np.array(list(topomesh.wisps(0)))[np.where(topomesh.wisp_property('epidermis',degree=0).values())] start_time = time() print "--> Computing mesh cell vertices" mesh_cell_vertex = {} for v in topomesh.wisps(0): if len(vertex_cell_neighbours[v]) == 5: for k in xrange(5): vertex_cell_labels = tuple([c for c in vertex_cell_neighbours[v]][:k])+tuple([c for c in vertex_cell_neighbours[v]][k+1:]) if not mesh_cell_vertex.has_key(vertex_cell_labels): mesh_cell_vertex[vertex_cell_labels] = v if len(vertex_cell_neighbours[v]) == 4: vertex_cell_labels = tuple([c for c in vertex_cell_neighbours[v]]) mesh_cell_vertex[vertex_cell_labels] = v if v in epidermis_vertices: # and count_l1_cells(vertex_cell_neighbours[v]) == 4: for k in xrange(4): vertex_cell_labels = (1,) + tuple([c for c in vertex_cell_neighbours[v]][:k])+tuple([c for c in vertex_cell_neighbours[v]][k+1:]) if not mesh_cell_vertex.has_key(vertex_cell_labels): mesh_cell_vertex[vertex_cell_labels] = v if (len(vertex_cell_neighbours[v]) == 3) and (v in epidermis_vertices): # and (count_l1_cells(vertex_cell_neighbours[v]) == 3): vertex_cell_labels = (1,) + tuple([c for c in vertex_cell_neighbours[v]]) mesh_cell_vertex[vertex_cell_labels] = v end_time = time() print "<-- Computing mesh cell vertices [",end_time-start_time,"s]" cell_vertex_matching = vq(np.sort(array_dict(image_cell_vertex).keys()),np.sort(array_dict(mesh_cell_vertex).keys())) matched_image_index = np.where(cell_vertex_matching[1] == 0)[0] matched_mesh_index = cell_vertex_matching[0][np.where(cell_vertex_matching[1] == 0)[0]] matched_image_cell_vertex = np.array(image_cell_vertex.values())[matched_image_index] matched_keys = np.sort(np.array(image_cell_vertex.keys()))[matched_image_index] matched_mesh_vertices = np.array(mesh_cell_vertex.values())[cell_vertex_matching[0][np.where(cell_vertex_matching[1] == 0)[0]]] matched_keys = np.sort(np.array(mesh_cell_vertex.keys()))[matched_mesh_index] initial_vertex_positions = array_dict(topomesh.wisp_property('barycenter',0).values(list(topomesh.wisps(0))),list(topomesh.wisps(0))) final_vertex_positions = array_dict() fixed_vertex = array_dict(np.array([False for v in topomesh.wisps(0)]),np.array(list(topomesh.wisps(0)))) for i,v in enumerate(matched_mesh_vertices): if not np.isnan(matched_image_cell_vertex[i]).any(): final_vertex_positions[v] = matched_image_cell_vertex[i] # print topomesh.wisp_property('barycenter',0)[v]," -> ",final_vertex_positions[v] fixed_vertex[v] = True matched_mesh_vertices = final_vertex_positions.keys() sigma_deformation_initial = kwargs.get("sigma_deformation",np.sqrt(3)/4.) sigma_deformation = sigma_deformation_initial*np.ones_like(np.array(list(topomesh.wisps(0))),float) if cell_vertex_motion: sigma_deformation[np.where(fixed_vertex.values())[0]] = 0. iterations_per_step = kwargs.get('iterations_per_step',1) for iteration in xrange(iterations/iterations_per_step+1): print "_____________________________" print "" print " Iteration ",iteration print "_____________________________" start_time = time() gaussian_sigma = kwargs.get('gaussian_sigma',10.0) target_areas = kwargs.get('target_areas',None) property_topomesh_vertices_deformation(topomesh,iterations=iterations_per_step,omega_forces=omega_forces,sigma_deformation=sigma_deformation,gradient_derivatives=gradient_derivatives,voxelsize=kwargs.get("image_voxelsize",(1.0,1.0,1.0)),gaussian_sigma=gaussian_sigma,target_areas=target_areas) if cell_vertex_motion: vertex_start_time = time() print "--> Moving cell vertices" if iteration <= (iterations/iterations_per_step+1)/1.: #topomesh.update_wisp_property('barycenter',degree=0,values=((iterations/iterations_per_step+1-(iteration+1))*initial_vertex_positions.values(matched_mesh_vertices) + (iteration+1)*final_vertex_positions.values(matched_mesh_vertices))/(iterations/iterations_per_step+1),keys=matched_mesh_vertices,erase_property=False) for v in matched_mesh_vertices: topomesh.wisp_property('barycenter',degree=0)[v] = ((iterations/iterations_per_step+1-(iteration+1))*initial_vertex_positions[v] + (iteration+1)*final_vertex_positions[v])/(iterations/iterations_per_step+1) vertex_end_time = time() print "<-- Moving cell vertices [",vertex_end_time-vertex_start_time,"s]" compute_topomesh_property(topomesh,'length',degree=1) compute_topomesh_property(topomesh,'barycenter',degree=3) compute_topomesh_property(topomesh,'barycenter',degree=2) if triangular_mesh: compute_topomesh_triangle_properties(topomesh) compute_topomesh_property(topomesh,'normal',degree=2) if edge_flip: # property_topomesh_edge_flip_optimization(topomesh,omega_energies=omega_forces,simulated_annealing=True,iterations=15,display=display) property_topomesh_edge_flip_optimization(topomesh,omega_energies=omega_forces,simulated_annealing=False,iterations=3,display=display) compute_topomesh_property(topomesh,'length',degree=1) compute_topomesh_property(topomesh,'barycenter',degree=3) compute_topomesh_property(topomesh,'barycenter',degree=2) if triangular_mesh: compute_topomesh_triangle_properties(topomesh) compute_topomesh_property(topomesh,'normal',degree=2) sigma_deformation = sigma_deformation_initial*np.power(0.95,(iteration+1)*iterations_per_step)*np.ones_like(np.array(list(topomesh.wisps(0))),float) if cell_vertex_motion: sigma_deformation[np.where(fixed_vertex.values())[0]] = 0. if omega_forces.has_key('regularization'): omega_forces['regularization'] = np.minimum(omega_forces['regularization']+(omega_regularization_max*iterations_per_step)/iterations,omega_regularization_max) if display: pass end_time = time() print "_____________________________" print "" print " [",end_time-start_time,"s]" #raw_input() print "_____________________________" optimization_end_time = time() print "--> Optimizing Topomesh [",optimization_end_time - optimization_start_time,"s]" return topomesh