def plot_triangulation(self): plt.triplot(self.Xdeformed(), self.Ydeformed(), self.tri.simplices.copy()) plt.plot(self.Xdeformed(), self.Ydeformed(), "or", label="Data") plt.grid() plt.legend() plt.title("triangulation") plt.xlabel("x") plt.ylabel("y") plt.show()
def plot_mesh(mesh,savefig = False,show = False): n = mesh.num_vertices() d = mesh.geometry().dim() # Create the triangulation mesh_coordinates = mesh.coordinates().reshape((n, d)) triangles = np.asarray([cell.entities(0) for cell in df.cells(mesh)]) triangulation = tri.Triangulation(mesh_coordinates[:, 0], mesh_coordinates[:, 1], triangles) triangulation.x *=1e6 triangulation.y *=1e6 # Plot the mesh fig = plt.figure(figsize=(7.0, 7.0)) plt.triplot(triangulation) plt.xlabel(r'$x(\mu m)$') plt.ylabel(r'$y(\mu m)$') if savefig != False: plt.savefig(savefig) if show != False: plt.show() return None
def main_Normalization(path): recognised_points_set_A, width_of_image = FR.face_Recognition(path) image_points = np.array( [ recognised_points_set_A[30], # Nose tip recognised_points_set_A[8], # Chin recognised_points_set_A[36], # Left eye left corner recognised_points_set_A[45], # Right eye right corne recognised_points_set_A[48], # Left Mouth corner recognised_points_set_A[54] # Right mouth corner ], dtype="double") # PE.PoseEstimation(path, image_points) if not recognised_points_set_A == False: flipped_image = flip_Horizonally(path) recognised_points_set_A_flipped, useless_Var = FR.new_face_Recognition( flipped_image) X, Y = seperate_XY(recognised_points_set_A_flipped) print(str(X)) print(str(Y)) triangles = tri.Triangulation(X, Y) plt.triplot(triangles, 'r--') plt.xticks(X, ()) plt.yticks(Y, ()) plt.show() # print('recognised_points_set_A_flipped :' + str(recognised_points_set_A_flipped) + # '\n' + 'and width_of_image: ' + str(width_of_image)) # if DRAW_IMAGE_BUTTON == True: # plt.imshow(flipped_image) # plt.show() # Merge both images # merged_image = FM.new_merge(generate_points_Set( # recognised_points_set_A, flip_Points_set(recognised_points_set_A, width_of_image)), generate_images_Matrix(cv2.imread(path), flipped_image), width_of_image) if bool(recognised_points_set_A_flipped) and bool( width_of_image) == True: merged_image = FM.new_merge( generate_points_Set(recognised_points_set_A, recognised_points_set_A_flipped), generate_images_Matrix(cv2.imread(path), flipped_image)) # Normalise the matrix of merged image. normalised_image = cv2.normalize(merged_image, None, 0, 255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC3) # Show image if request. if DRAW_IMAGE_BUTTON == True: plt.imshow(normalised_image) plt.show() recognised_points_set_B = FR.new_face_Recognition( normalised_image[:, :, [2, 1, 0]]) # A function of numpy that shows all the content of a tensor. np.set_printoptions(threshold=np.inf) logging.info(str(normalised_image[:, :, [2, 1, 0]])) logging.info( 'File ' + path + ' has been successfully merged and recognised. Process code: 3101 in ImagesNormailzation.py' ) if recognised_points_set_B == False: logging.warning( 'File ' + path + ' cannot be recognised after merged! Error code:301 in ImagesNormailzation.py' ) else: return recognised_points_set_B else: logging.warning( 'File ' + path + ' cannot be recognised after flipped! Error code:304 in ImagesNormailzation.py' ) return False else: logging.warning( 'File ' + path + ' cannot be recognised before flipped! Error code:302 in ImagesNormailzation.py' ) return False
import matplotlib.pylab as plt import numpy as np # 삼각 그리드 지원 패키지 import matplotlib.tri as mtri # 삼각 그리드 생성 # Triangulation 클래스 # Triangulation(x, y, triangles) # triangles(위치정보) 생략하면 자동생성 x = np.array([0,1,2]) y = np.array([0,np.sqrt(3),0]) triangles=[[0,1,2]] triang = mtri.Triangulation(x,y,triangles) plt.triplot(triang,'ro-') plt.xlim(-0.1,2.1) plt.ylim(-0.1,1.8) plt.grid(True) plt.show() # 삼각형 여러 개 그리기 x = np.array([0,1,2,3,4,2]) y = np.array([0,np.sqrt(3),0,np.sqrt(3),0,2*np.sqrt(3)]) triangles=[[0,1,2],[2,3,4],[1,2,3],[1,3,5]] # 삼각형에 선택할 index 들 triang = mtri.Triangulation(x,y,triangles) plt.triplot(triang,'bo-') plt.grid(True) plt.show()
eigenvectors = [] for i, value in enumerate(values): eigenvalues.append(value[0]) eigenvectors.append(value[1]) eigenvalues = asarray(eigenvalues) eigenvectors = asarray(eigenvectors) n = 2 barycenters = sc[-1].points.mean(1).real from matplotlib import tri from matplotlib import pylab fig = pylab.figure(figsize=(10, 10)) pylab.triplot(tri.Triangulation(sc.vertices[:, 0].real, sc.vertices[:, 1].real, sc[-1].simplices), figure=fig) if p == 0: z = zeros(sc[0].num_simplices) z[interior] = eigenvectors[n].real kahler.scalar_field2d(barycenters, sc[0].sharpen(z).real, 1000, fig) if p == 1: z = zeros(sc[1].num_simplices) z[interior] = eigenvectors[n].real kahler.vector_field2d(barycenters, sc[1].sharpen(z).real, 20, fig) show()
def _triangulate_ltrs(self, slam_ts, dirs, check_triangulation, manual_lms): """ Triangulate the landmarks to define the LTRs. """ # Isolate the landmarks from mean. last_estimate = slam_ts[-1] filename = "mean-" + last_estimate[1] + ".npy" last_mean = np.load(dirs["slam"] + filename) dof = 7 # robot state dof last_lms = last_mean[dof:] N_lm = int((last_mean.size - dof) / 3) lm_ids = np.arange(N_lm) # Find only the landmarks which were observed valid_lms = [] for i in range(N_lm): if last_lms[3 * i] != 0: valid_lms.append(i) valid_lms_arr = np.array(valid_lms) last_lms = last_lms.reshape((int(last_lms.size / 3), 3)) last_lms = last_lms[:, :2] not_happy = True if check_triangulation: print("Valid landmarks:", valid_lms) plt.ion() not_happy = True else: plt.ioff() fig = plt.figure() plt.axis("equal") while not_happy: last_lms_valid = last_lms[valid_lms, :] # Remove invalids if (last_lms_valid.size / 2) < 3: logger.error(f"Too few landmarks in SLAM estimates: {last_lms_valid.size / 2} < 3") exit() if manual_lms != []: for tri in manual_lms: if len(tri) != 3: raise ValueError( "Invalid manual landmarks. Incorrect size: %s" % str(manual_lms) ) valid_lms_set = set([i for i in valid_lms]) manual_lms_set = set([j for i in manual_lms for j in i]) if not (manual_lms_set <= valid_lms_set): raise ValueError( "Invalid manual landmarks. Not subset of valid landmark set. %s !<= %s" % (str(manual_lms_set), str(valids_lms_set)) ) self.simplices = manual_lms not_happy = False elif (last_lms_valid.size / 2) == 3: # If there are only 3 landmarks don't need user input self.simplices = np.array([valid_lms]) not_happy = False else: triangles = Delaunay(last_lms_valid, incremental=True) self.simplices = triangles.simplices # Indices of the points in each triangulation # Remap simplices to valid landmark ids remap = lambda x: valid_lms_arr[x] self.simplices = np.apply_along_axis(remap, 0, self.simplices) # Visual check for triangulation plt.gca().clear() plt.triplot(last_lms[:, 0], last_lms[:, 1], self.simplices.copy()) for i in valid_lms: plt.text(*last_lms[i, :], s=str(i)) if check_triangulation and not_happy: plt.draw() plt.pause(0.01) remove_str = input("Enter the IDs of landmarks to be removed (comma seperated): ") try: remove = ast.literal_eval(remove_str) except Exception: logger.exception("Error understanding input") remove = () not_happy = False # If only one number entered if type(remove) is int: remove = (remove,) new_valid = sorted(list(set(valid_lms) - set(remove))) valid_lms = new_valid valid_lms_arr = np.array(valid_lms) else: break plt.savefig(dirs["main"] + "/triangulation.pdf") plt.close(fig) plt.ioff()
exit() if (last_lms_valid.size / 2) == 3: # If there are only 3 landmarks don't need user input simplices = np.array([valid_lms]) notHappy = False break else: triangles = Delaunay(last_lms_valid, incremental=True) simplices = triangles.simplices # Indices of the points in each triangulation # Remap simplices to valid landmark ids remap = lambda x: valid_lms_arr[x] simplices = np.apply_along_axis(remap, 0, simplices) # Visual check for triangulation plt.gca().clear() plt.triplot(last_lms[:, 0], last_lms[:, 1], simplices.copy()) for i in valid_lms: plt.text(*last_lms[i, :], s=str(i)) plt.draw() plt.pause(0.01) if check_triangulation: remove_str = input("Enter the IDs of landmarks to be removed: ") try: remove = ast.literal_eval(remove_str) except Exception as e: print("Error understanding input:", e) remove = () notHappy = False # If only one number entered
def extract_pseudo_lms(pos_list): """Determine pseudo-landmarks Calculate the landmarks using the positions of the robot as anchor points. NOTE For now this is only a nice approach for square datasets. pos_list : list. List of robot positions. """ pos_arr = np.hstack(pos_list).T fig = plt.figure() plt.ion() plt.axis("equal") hull = ConvexHull(pos_arr[:, :2]) indices = hull.vertices indices = np.hstack((indices, indices[0])) # Visual check for triangulation plt.gca().clear() plt.scatter(*pos_arr[:, :2].T) plt.plot(*pos_arr[indices, :2].T) for i in indices: plt.text(*pos_arr[i, :2].T, s=str(i)) plt.draw() plt.pause(0.01) while 1: keep_str = input( "Enter the IDs of landmarks to be keep (comma seperated, blank continues, order matters!): " ) try: keep_new = ast.literal_eval(keep_str) # XXX incase something wrong is entered, just restart loop if type(keep_new) is int: continue elif len(keep_new) != 3: continue else: keep = keep_new except Exception: logger.exception("Error understanding input") break plt.gca().clear() plt.scatter(*pos_arr[:, :2].T) plt.plot(*pos_arr[keep[:2], :2].T) plt.plot(*pos_arr[keep[::2], :2].T) for i in indices: plt.text(*pos_arr[i.T, :2], s=str(i)) plt.draw() plt.pause(0.01) if len(keep) != 3: raise ValueError("Can only keep 3 landmarks") lms = pos_arr[keep, :].reshape(3, 3, 1) # (N, d, 1) # Enforce all lms in the same plane lms[1:, 2] = 1 * lms[0, 2] # Axis vectors vec_x = lms[1, :] - lms[0, :] axis_x = vec_x / np.linalg.norm(vec_x) axis_z = np.array([[0, 0, 1]]).T axis_y = np.cross(axis_x.flatten(), axis_z.flatten()).reshape(3, 1) vec_2 = lms[2, :] - lms[0, :] vec_y = axis_y.T.dot(vec_2) * axis_y vec_x = vec_x.flatten() vec_y = vec_y.flatten() tri = Delaunay(lms[:, :2, 0]) simplices = tri.simplices # Visual check for triangulation plt.gca().clear() plt.triplot(*lms[:, :2, 0].T, simplices) plt.scatter(*pos_arr[:, :2].T) plt.draw() plt.pause(0.01) indices = np.arange(0, lms.shape[1]) valid_indices = np.arange(0, lms.shape[1]) while 1: div_str = input("Enter the number of divisions (>= 1): ") try: div = ast.literal_eval(div_str) if (type(div) is not int) or (div < 0): raise ValueError("Divisons must be integer and >=1.") except Exception: logger.exception("Error understanding input") div = 0 break N_lms = (div + 1)**2 spacing = np.linspace(0, 1, div + 1) x, y = np.meshgrid(spacing, spacing) coords = np.hstack( (x.reshape(N_lms, 1), y.reshape(N_lms, 1), np.zeros( (N_lms, 1)))) # (N_lms, 3) pseudo_lms = np.zeros((N_lms, 3, 1), dtype=float) pseudo_lms[:, :, 0] = coords[:, 0, None] * vec_x + coords[:, 1, None] * vec_y pseudo_lms += lms[0, :] triangulation = Delaunay(pseudo_lms[:, :2, 0]) # Check number of regions from triangulation matches the divisions N = triangulation.simplices.shape[0] # This shouldn't be an issue anymore # assert (N == 2*div**2) , "Number of triangulation regions is # inconsistent with number of divisions." simplices = triangulation.simplices # Visual check for triangulation plt.gca().clear() plt.triplot(*pseudo_lms[:, :2, 0].T, simplices) plt.scatter(*pos_arr[:, :2].T) plt.draw() plt.pause(0.01) plt.close(fig) plt.ioff() return pseudo_lms, triangulation
""" Reads ascii vertex and element files, writes a pydec mesh and displays it """ import scipy from pydec import SimplicialMesh, write_mesh, read_mesh from matplotlib.pylab import triplot, show vertices = scipy.loadtxt("v.txt") elements = scipy.loadtxt("s.txt", dtype='int32') - 1 mymesh = SimplicialMesh(vertices=vertices, indices=elements) write_mesh("square_8.xml", mymesh, format='basic') rmesh = read_mesh("square_8.xml") triplot(rmesh.vertices[:, 0], rmesh.vertices[:, 1], rmesh.indices) show()
""" Reads ascii vertex and element files, writes a pydec mesh and displays it """ import scipy from pydec import SimplicialMesh, write_mesh, read_mesh from matplotlib.pylab import triplot, show vertices = scipy.loadtxt("v.txt") elements = scipy.loadtxt("s.txt",dtype='int32') - 1 mymesh = SimplicialMesh(vertices=vertices,indices=elements) write_mesh("square_8.xml",mymesh,format='basic') rmesh = read_mesh("square_8.xml") triplot(rmesh.vertices[:,0], rmesh.vertices[:,1], rmesh.indices) show()