def test_read_write_read(self):
     mesh1 = openmesh.read_trimesh("TestFiles/cube-minimal.obj")
     openmesh.write_mesh('OutFiles/test_read_write_read.om', mesh1)
     mesh2 = openmesh.read_trimesh('OutFiles/test_read_write_read.om')
     self.assertTrue(np.allclose(mesh1.points(), mesh2.points()))
     self.assertTrue(
         np.array_equal(mesh1.face_vertex_indices(),
                        mesh2.face_vertex_indices()))
Example #2
0
    def setUp(self) -> None:
        MESH_BASEPATH = "./meshes"

        self.meshes = {
            'genus0': om.read_trimesh(f"{MESH_BASEPATH}/Genus0.obj"),
            'genus1': om.read_trimesh(f"{MESH_BASEPATH}/Genus1.obj")
        }

        logging.basicConfig(level=logging.DEBUG)
def write_align_mesh(src, tar, filename, index = None):
	src_mesh=om.read_trimesh(src)
	tar_mesh=om.read_trimesh(tar)
	point_array_src = src_mesh.points()
	point_array_tar = tar_mesh.points()
	R, t = rigid_registeration(point_array_src, point_array_tar, index)
	register_array_src = np.dot(R, point_array_src.T).T + np.tile(t,point_array_src.shape[0]).reshape(-1,3)
	new_V = igl.eigen.MatrixXd(register_array_src.astype(np.float64))
	V = igl.eigen.MatrixXd()
	F = igl.eigen.MatrixXi()
	igl.readOBJ(src, V,F)
	igl.writeOBJ(filename, new_V, F)
def compute_distance_whole(src, tar, index):
	'''
	compute the L2 distance of average distance between 2 meshes on each vertice
	'''
	src_mesh = om.read_trimesh(src)
	tar_mesh = om.read_trimesh(tar)
	point_array_src = src_mesh.points()
	point_array_tar = tar_mesh.points()
	R, t = rigid_registeration(point_array_src, point_array_tar, index)
	register_src = np.dot(R, point_array_src.T).T + np.tile(t,point_array_src.shape[0]).reshape(-1,3)
	# distance = np.mean(np.square(point_array_tar - register_src ))
	distance_mean = np.mean(np.sqrt(np.sum(np.square(point_array_tar-register_src),axis=1)))
	distance_max = np.max(np.sqrt(np.sum(np.square(point_array_tar-register_src),axis=1)))
	distance_no_rigid = np.mean(np.sqrt(np.sum(np.square(point_array_tar-point_array_src),axis=1)))
	return distance_mean, distance_max,distance_no_rigid
def cal_exp_disentanglement_in_file(file_format, use_registeration = True, vis = True):
    index = None
    loss_log = []
    for j in range(0, 47):
        data_array=[]
        for i in range(141,151):
            mesh=om.read_trimesh(file_format.format(i,j))
            point_array=mesh.points()
            if use_registeration:
                if j > 0:
                    R, t = rigid_registeration(point_array, fix, index)
                    register_src = np.dot(R, point_array.T).T + np.tile(t,point_array.shape[0]).reshape(-1,3)
                    point_array = register_src
                else:
                    fix = point_array
            data_array.append(point_array.reshape(1,-1))
        data_array=np.concatenate(data_array,axis=0)
        # store exp std to a file
        dis = np.sqrt(np.sum(np.square(np.std(data_array.reshape((10,11510,3)), axis = 0)),axis = -1))
        #dis.tofile('exp_var_for_expression_{}.dat'.format(j))
        loss_log.append(np.mean(dis))
        #loss_log.append(compute_variance(data_array))
        if vis:
            print('Exp: {}, var: {}'.format(j, loss_log[-1]))
    print('our exp Average variance: {}'.format(np.mean(loss_log)))
    print('our exp Median variance: {}'.format(np.median(loss_log)))
    print('extreme var: {}'.format(max(np.max(loss_log)-np.mean(loss_log), np.mean(loss_log)- np.min(loss_log))))
    return loss_log
Example #6
0
def main():
    global mesh
    mesh = om.read_trimesh('plyFile/cone.ply',vertex_color=True)
    
    # 使用glut初始化OpenGL
    glutInit()
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)

    # 建立視窗
    glutInitWindowPosition(0,0)
    glutInitWindowSize(1024, 768)
    glutCreateWindow(b"first")

    # 初始化
    glShadeModel(GL_SMOOTH)
    glClearColor(0.0, 0.0, 0.0, 0.5)
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LEQUAL)

    # 視角
    gluPerspective(80, 1024/768, 0.1, 1000)
    gluLookAt(0, 0, 10,             # eye
        0, 0 , 0,                   # center
        0, 1, 0)                    # Top

    # 顯示函數
    glutDisplayFunc(drawFunc)
    glutIdleFunc(drawFunc)
    glutMainLoop()
Example #7
0
def sphere_with_feature():
    fn_mesh = folder + 'sphere.obj'
    mesh = om.read_trimesh(fn_mesh)

    # split
    field = mesh.points()[:, 0]

    isocurve = mu.pyisocurve.isocurve(mesh.points(),
                                      mesh.face_vertex_indices(), field)
    pts, on_edges, ratios, isocurve_indices = isocurve.extract(0.0, 1.e-5)
    mu.write_obj_lines(folder + 'curve.obj', pts, isocurve_indices)
    mesh, curve_idx = mu.split_mesh(mesh.points(), mesh.face_vertex_indices(),
                                    on_edges, ratios)
    # print(curve_idx)
    # om.write_mesh('../data/mesh_split.obj', mesh)
    curve = [curve_idx[v] for v in isocurve_indices[0]]
    feature = np.empty((len(curve) - 1, 2), 'i')
    feature[:, 0] = curve[:-1]
    feature[:, 1] = curve[1:]

    remesher = mu.pyremesh.remesher()
    remesher.init_mesh(mesh.points(), mesh.face_vertex_indices())
    remesher.set_features(feature)

    feat_edges = remesher.get_features()
    feat_verts = remesher.get_feature_vertices()
    # write_obj_lines(folder+'feature_detect_e.obj', mesh.points(), feat_edges)
    # write_obj_lines(folder+'feature_detect_v.obj', mesh.points()[feat_verts], [])

    remesher.remesh(0.1, 15)
    verts, faces = remesher.get_mesh()
    mesh = om.TriMesh(verts, faces)
    om.write_mesh(folder + 'sphere_split.obj', mesh)
Example #8
0
    def __init__(self, filepath: str = None, vertices: torch.Tensor = None, faces: torch.Tensor = None):
        self.vs = vertices
        self.fs = faces
        self.vn = None
        self.fn = None

        if (self.vs is not None and self.fs is not None):
            if filepath is not None:
                logger.warn("Using provided vertices and faces, ignore filepath")
            assert(self.vs.ndim == 2 and self.fs.ndim ==2)
            assert(self.vs.shape[-1] == 3)
            assert(self.fs.shape[-1] == 3)
        elif filepath is not None:
            mesh = om.read_trimesh(filepath)
            self.vs = torch.from_numpy(mesh.points()).to(dtype=torch.float32)

            face_lists = []
            for f in mesh.face_vertex_indices():
                face_lists.append(f)
            self.fs = torch.from_numpy(np.stack(face_lists, axis=0)).to(dtype=torch.int64)
            mesh.request_face_normals()
            if not mesh.has_vertex_normals():
                mesh.request_vertex_normals()
                mesh.update_normals()
            v_normals = mesh.vertex_normals()
            f_normals = mesh.face_normals()
            self.vn = torch.from_numpy(v_normals.astype(np.float32))
            self.fn = torch.from_numpy(f_normals.astype(np.float32))
        else:
            logger.error("[{}] Must provide a mesh".format(__class__))

        # build_gemm(self, self.fs)
        self.farea = compute_face_normals_and_areas(self.vs, self.fs)[1]
        self.features = ['vs', 'fs', 'vn', 'fn', 'farea']
Example #9
0
    def __init__(self, pca_npz):
        super(GarmentPcaDecodeLayer, self).__init__()
        datas = np.load(pca_npz)
        self.register_buffer(
            'mean', torch.from_numpy(datas['mean'].astype(np.float32)))
        self.register_buffer(
            'components',
            torch.from_numpy(datas['components'].astype(np.float32)))
        self.register_buffer(
            'std',
            torch.from_numpy(datas['singular_values'].astype(np.float32)))
        self.type = osp.splitext(osp.basename(pca_npz))[0]
        mesh = om.read_trimesh(
            osp.join(osp.dirname(pca_npz), 'garment_tmp.obj'))
        self.register_buffer(
            'edge_index',
            torch.from_numpy(mesh.hv_indices().transpose()).to(torch.long))
        self.register_buffer(
            'face_index',
            torch.from_numpy(mesh.face_vertex_indices()).to(torch.long))

        vf_fid = torch.zeros(0, dtype=torch.long)
        vf_vid = torch.zeros(0, dtype=torch.long)
        for vid, fids in enumerate(mesh.vertex_face_indices()):
            fids = torch.from_numpy(fids[fids >= 0]).to(torch.long)
            vf_fid = torch.cat((vf_fid, fids), dim=0)
            vf_vid = torch.cat((vf_vid, fids.new_ones(fids.shape) * vid),
                               dim=0)
        self.register_buffer('vf_findex', vf_fid)
        self.register_buffer('vf_vindex', vf_vid)
        self.vnum = mesh.n_vertices()
        self.fnum = mesh.n_faces()
    def test_write_triangle(self):
        self.mesh = openmesh.TriMesh()

        # Generate data
        v1 = self.mesh.add_vertex(np.array([1.0, 0.0, 0.0]))
        v2 = self.mesh.add_vertex(np.array([0.0, 1.0, 0.0]))
        v3 = self.mesh.add_vertex(np.array([0.0, 0.0, 1.0]))
        self.mesh.add_face(v1, v2, v3)

        # Save
        filename = "OutFiles/triangle-minimal.om"
        openmesh.write_mesh(filename, self.mesh)

        # Load
        self.mesh = openmesh.read_trimesh(filename)

        # Compare
        self.assertEqual(self.mesh.n_vertices(), 3)
        self.assertEqual(self.mesh.n_edges(), 3)
        self.assertEqual(self.mesh.n_faces(), 1)

        self.assertTrue(
            np.allclose(self.mesh.point(v1), np.array([1.0, 0.0, 0.0])))
        self.assertTrue(
            np.allclose(self.mesh.point(v2), np.array([0.0, 1.0, 0.0])))
        self.assertTrue(
            np.allclose(self.mesh.point(v3), np.array([0.0, 0.0, 1.0])))

        # Cleanup
        os.remove(filename)
Example #11
0
def test_split_rect_1():
    # two functions from https://stackoverflow.com/a/9997374
    def ccw(A,B,C):
        return (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0])

    # Return true if line segments AB and CD intersect
    def intersect(A,B,C,D):
        return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)

    mesh = om.read_trimesh('../data/rect.obj')
    mesh_pts = mesh.points()
    mesh_edges = mesh.ev_indices()
    
    x = np.linspace(-1, 1, 101)
    y = T.basis(5)(x)
    
    # export Chebyshev polynomial
    pts = np.zeros((x.size, 3))
    pts[:, 0] = x
    pts[:, 1] = y
    mu.write_obj_lines('../data/curve_Chebyshev.obj', pts, [np.arange(pts.shape[0])])

    edges = [np.array([0,0], 'i')]
    ratios = [0.0]
    for i in range(1, x.size-2):
        A = np.array([x[i], y[i]])
        B = np.array([x[i+1], y[i+1]])
        temp_x = []
        temp_e = []
        temp_u = []
        for e in mesh_edges:
            C = mesh_pts[e[0], :2]
            D = mesh_pts[e[1], :2]
            if intersect(A, B, C, D):
                # A = (x1, y1), B = (x2, y2)    
                # C = (x3, y3), D = (x4, y4)
                u = ((A[0]-C[0])*(A[1]-B[1])-(A[1]-C[1])*(A[0]-B[0]))/((A[0]-B[0])*(C[1]-D[1])-(A[1]-B[1])*(C[0]-D[0]))
                temp_e.append(e)
                temp_u.append(u)
                temp_x.append(C[0]*(1-u)+D[0]*u)
        order = np.argsort(np.array(temp_x))
        edges.extend([temp_e[i] for i in order])
        ratios.extend([temp_u[i] for i in order])
    edges.append(np.array([2,2], 'i'))
    ratios.append(0.0)
    edges = np.array(edges, 'i')
    #print(ratios)
    ratios = np.array(ratios, 'd')
    
    pts0 = mesh_pts[edges[:, 0], :]
    pts1 = mesh_pts[edges[:, 1], :]
    pts = np.multiply(pts0, 1.-ratios[:, np.newaxis]) + \
        np.multiply(pts1, ratios[:, np.newaxis])
    mu.write_obj_lines('../data/curve.obj', pts, [np.arange(pts.shape[0])])
    # print(on_edges, ratios)
    mesh, curve_idx = mu.split_mesh_complete(mesh.points(),
                                    mesh.face_vertex_indices(),
                                    edges, ratios)
    # print(curve_idx)
    om.write_mesh('../data/mesh_split.obj', mesh)
    def test_load_simple_om_with_vertex_colors(self):
        self.mesh = openmesh.read_trimesh(
            "TestFiles/cube-minimal-vertexColors.om", vertex_color=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 0.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 0.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()
Example #13
0
def read_datas(name_list, expand_corre=False):
    points_list = []
    meanpos_list = []
    norms_list = []
    vnums = []
    corre_ps = []
    for name in name_list:
        mesh = om.read_trimesh(name)
        temp = mesh.points().T
        vnums.append(temp.shape[1])
        points_list.append(temp)
        meanpos_list.append(temp.mean(1))
        mesh.request_face_normals()
        mesh.request_vertex_normals()
        mesh.update_normals()
        norms_list.append(mesh.vertex_normals().T)
        corre_ps.append(np.load(name[:-4] + '_farmarap10.npy').T)
    points = np.zeros((3 * len(vnums), max(vnums)), np.float32)
    meanpos = np.stack(meanpos_list).astype(np.float32)
    norms = np.zeros((3 * len(vnums), max(vnums)), np.float32)
    corre_ps = np.stack(corre_ps).astype(np.float32)
    corre_ps = corre_ps.reshape(-1, corre_ps.shape[-1])
    for i, (p, n) in enumerate(zip(points_list, norms_list)):
        points[3 * i:3 * i + 3, 0:vnums[i]] = p
        norms[3 * i:3 * i + 3, 0:vnums[i]] = n
    return points, meanpos, norms, np.array(vnums, np.int32), corre_ps
Example #14
0
def test_geodesic():
    # run python sphere_cvt.py to generate the mesh
    mesh = om.read_trimesh('../data/sphere_cvt.obj')
    # find source
    u, v = 0, 20
    path_edge, path_ratio = pygeodesic.find_path(mesh.points(),
                                                 mesh.face_vertex_indices(),
                                                 u, v)
    #source = split_along_curve(mesh, path_edge, path_ratio)
    mesh, source = split_mesh(mesh.points(), mesh.face_vertex_indices(),
                              path_edge, path_ratio)

    # compute geodesic distance field
    field = pygeodesic.distance_field(mesh.points(),
                                      mesh.face_vertex_indices(),
                                      source, 0.05)
    colormap_vertex_color('../data/field.off',
                          mesh.points(),
                          mesh.face_vertex_indices(),
                          field)

    field = pygeodesic.distance_field(mesh.points(),
                                      mesh.face_vertex_indices(),
                                      source, edge_split=0.05,
                                      max_propagation_distance=1.0)
    field[field>1.e10] = 2.0
    colormap_vertex_color('../data/field_1.off',
                          mesh.points(),
                          mesh.face_vertex_indices(),
                          field)
Example #15
0
    def process(self):
        print('Processing...')
        fps = self.data_files

        train_data_list, test_data_list = [], []
        for dx in fps:
            for tt in fps[dx]:
                for idx, fp in enumerate(tqdm(fps[dx][tt])):
                    mesh = om.read_trimesh(fp)
                    face = torch.from_numpy(mesh.face_vertex_indices()).T.type(
                        torch.long)
                    x = torch.tensor(mesh.points().astype('float32'))
                    edge_index = torch.cat([face[:2], face[1:], face[::2]],
                                           dim=1)
                    edge_index = to_undirected(edge_index)
                    if dx == 'ad':
                        data = Data(x=x,
                                    y=torch.Tensor([1, 0]),
                                    edge_index=edge_index,
                                    face=face)
                    elif dx == 'cn':
                        data = Data(x=x,
                                    y=torch.Tensor([0, 1]),
                                    edge_index=edge_index,
                                    face=face)
                    if self.pre_transform is not None:
                        data = self.pre_transform(data)

                    if tt == 'test':
                        test_data_list.append(data)
                    elif tt == 'train':
                        train_data_list.append(data)

        torch.save(self.collate(train_data_list), self.processed_paths[0])
        torch.save(self.collate(test_data_list), self.processed_paths[1])
Example #16
0
    def load(self):
        self.train_dataset = CoMA(self.root,
                                  train=True,
                                  split=self.split,
                                  test_exp=self.test_exp,
                                  transform=self.transform,
                                  pre_transform=self.pre_transform)
        self.test_dataset = CoMA(self.root,
                                 train=False,
                                 split=self.split,
                                 test_exp=self.test_exp,
                                 transform=self.transform,
                                 pre_transform=self.pre_transform)

        tmp_mesh = om.read_trimesh(self.template_fp)
        self.template_points = tmp_mesh.points()
        self.template_face = tmp_mesh.face_vertex_indices()
        self.num_nodes = self.train_dataset[0].num_nodes

        self.num_train_graph = len(self.train_dataset)
        self.num_test_graph = len(self.test_dataset)
        self.mean = self.train_dataset.data.x.view(self.num_train_graph, -1,
                                                   3).mean(dim=0)
        self.std = self.train_dataset.data.x.view(self.num_train_graph, -1,
                                                  3).std(dim=0)
        self.normalize()
Example #17
0
def read_mesh(path):
    mesh = om.read_trimesh(path)
    face = torch.from_numpy(mesh.face_vertex_indices()).T.type(torch.long)
    x = torch.tensor(mesh.points().astype('float32'))
    edge_index = torch.cat([face[:2], face[1:], face[::2]], dim=1)
    edge_index = to_undirected(edge_index)
    return Data(x=x, edge_index=edge_index, face=face)
    def test_load_simple_obj_with_vertex_colors_as_vc_lines(self):
        self.mesh = openmesh.read_trimesh(
            "TestFiles/cube-minimal-vertex-colors-as-vc-lines.obj",
            vertex_color=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 0.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 0.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.mesh.release_vertex_colors()
Example #19
0
def fill_from_file(mesh, file):
    mesh.filename = ntpath.split(file)[1]
    mesh.fullfilename = file
    vs, faces = [], []
    m = om.read_trimesh(file)
    vs = m.points()
    faces = m.face_vertex_indices()
    '''
    f = open(file)
    for line in f:
        line = line.strip()
        splitted_line = line.split()
        if not splitted_line:
            continue
        elif splitted_line[0] == 'v':
            vs.append([float(v) for v in splitted_line[1:4]])
        elif splitted_line[0] == 'f':
            face_vertex_ids = [int(c.split('/')[0]) for c in splitted_line[1:]]
            assert len(face_vertex_ids) == 3
            face_vertex_ids = [(ind - 1) if (ind >= 0) else (len(vs) + ind)
                               for ind in face_vertex_ids]
            faces.append(face_vertex_ids)
    f.close()
    vs = np.asarray(vs)
    faces = np.asarray(faces, dtype=int)
    '''
    assert np.logical_and(faces >= 0, faces < len(vs)).all()
    return vs, faces
    def test_load_ply_from_mesh_lab_with_vertex_colors(self):
        self.mesh = openmesh.read_trimesh("TestFiles/meshlab.ply",
                                          vertex_color=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()
    def test_load_simple_ply_with_texcoords(self):
        self.mesh = openmesh.read_trimesh(
            "TestFiles/cube-minimal-texCoords.ply", vertex_tex_coord=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(0))[0], 10.0)
        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(0))[1], 10.0)

        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(2))[0], 6.0)
        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(2))[1], 6.0)

        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(4))[0], 9.0)
        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(4))[1], 9.0)

        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(7))[0], 12.0)
        self.assertEqual(
            self.mesh.texcoord2D(self.mesh.vertex_handle(7))[1], 12.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertTrue(self.mesh.has_vertex_texcoords1D())
        self.assertTrue(self.mesh.has_vertex_texcoords2D())
        self.assertTrue(self.mesh.has_vertex_texcoords3D())
        self.assertFalse(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_texcoords2D()
Example #22
0
    def test_write_and_read_binary_float_vertex_colors_to_and_from_off_file(
            self):
        # Read the mesh
        self.mesh = openmesh.read_trimesh("TestFiles/meshlab.ply",
                                          vertex_color=True)

        # Write the mesh
        openmesh.write_mesh("OutFiles/cube_floating_binary.off",
                            self.mesh,
                            vertex_color=True,
                            binary=True,
                            color_float=True)

        # Read the mesh again
        self.mesh = openmesh.read_trimesh("OutFiles/cube_floating_binary.off",
                                          vertex_color=True,
                                          binary=True,
                                          color_float=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertFalse(self.mesh.has_face_colors())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()
Example #23
0
def decimate(obj: pyr.Object, verbose=False):
    """
    Decimates a mesh, reducing the number of faces by 2.
    This is EXTREMELY inefficient, and not differentiable - use it sparingly!
    Modifies the input mesh.
    """
    # Let's make a temporary directory
    intermediate_dir = tempfile.mkdtemp()

    orig_out = os.path.join(intermediate_dir, "orig.obj")
    new_out = os.path.join(intermediate_dir, "decim.obj")

    if verbose:
        print("Made temp dir:")
        print(intermediate_dir)

    # First, let's save the redner
    pyr.save_obj(obj, orig_out)
    # Now, let's load in openmesh
    mesh = openmesh.read_trimesh(orig_out)
    # Now, decimate by half
    orig_nfaces = mesh.n_faces()

    if verbose:
        print("Original # of faces:", orig_nfaces)

    decimator = openmesh.TriMeshDecimater(mesh)
    algorithm = openmesh.TriMeshModQuadricHandle()

    decimator.add(algorithm)
    decimator.initialize()
    decimator.decimate_to_faces(n_faces=round(orig_nfaces / 2))

    mesh.garbage_collection()

    if verbose:
        print("New # of faces:", mesh.n_faces())

    openmesh.write_mesh(new_out, mesh)

    # Now, we have it. Load it back into redner
    decim_obj = pyr.load_obj(new_out, return_objects=True)[0]
    # And set the faces/indices
    obj.vertices = decim_obj.vertices
    obj.indices = decim_obj.indices

    # Recompute normals - the face normals have been broken
    recompute_normals(obj)

    # Finally, clean up the dir
    files_to_delete = os.listdir(intermediate_dir)
    for each_file in files_to_delete:
        apath = os.path.join(intermediate_dir, each_file)
        if verbose:
            print("Deleting", apath)
        os.remove(apath)
    if verbose:
        print("Deleting", intermediate_dir)
    os.rmdir(intermediate_dir)
Example #24
0
def test_isocurve0():
    # run python sphere_cvt.py to generate the mesh
    mesh = om.read_trimesh('../data/sphere_cvt.obj')
    field = mesh.points()[:, 1]

    isocurve = IsoCurve(mesh.points(), mesh.face_vertex_indices(), field)
    pts, _, _, isocurve_indices = isocurve.extract(0.5)
    write_obj_lines('../data/curve.obj', pts, isocurve_indices)
Example #25
0
def read_mesh(path):
    mesh = om.read_trimesh(path)
    #TODO: hardcoded short
    face = torch.from_numpy(mesh.face_vertex_indices()).T.type(torch.short)
    x = torch.tensor(mesh.points().astype('float32'))
    edge_index = torch.cat([face[:2], face[1:], face[::2]], dim=1)
    edge_index = to_undirected(edge_index)
    #TODO: hardcoded short
    return Data(x=x, edge_index=edge_index, face=face, use_short=True)
Example #26
0
def read_ply(path):
    mesh = openmesh.read_trimesh(path)
    pos = torch.from_numpy(mesh.points()).to(torch.float)
    face = torch.from_numpy(mesh.face_vertex_indices())
    face = face.t().to(torch.long).contiguous()

    data = Data(pos=pos, face=face)

    return data
Example #27
0
def read_ply(path):
    if openmesh is None:
        raise ImportError('`read_ply` requires the `openmesh` package.')

    mesh = openmesh.read_trimesh(path)
    pos = torch.from_numpy(mesh.points()).to(torch.float)
    face = torch.from_numpy(mesh.face_vertex_indices())
    face = face.t().to(torch.long).contiguous()
    return Data(pos=pos, face=face)
Example #28
0
def load_training_pose(idx):
    ten = []
    template = os.path.join(path_prefix, 'Tester_{}'.format(idx),
                            'TrainingPose', 'pose_aligned_{}.obj')
    for i in range(n_training_pose):
        file_path = template.format(i)
        mesh = openmesh.read_trimesh(file_path)
        ten.append(mesh.points())
    ten = np.array(ten, dtype=np.float32)
    return ten
def compute_distance(src, tar, index = None):#np.loadtxt('src/front_part_v.txt', dtype=int)):
	'''
	compute the L2 distance of average distance between 2 meshes on each vertice
	'''
	src_mesh = om.read_trimesh(src)
	tar_mesh = om.read_trimesh(tar)
	point_array_src = src_mesh.points()
	point_array_tar = tar_mesh.points()
	R, t = rigid_registeration(point_array_src, point_array_tar, index)
	register_src = np.dot(R, point_array_src.T).T + np.tile(t,point_array_src.shape[0]).reshape(-1,3)
	# distance = np.mean(np.square(point_array_tar - register_src ))\

 	## new way for front face distance computation
	diff_array = (point_array_tar-register_src)[index]
	#print(np.shape(diff_array))
	distance_mean = np.mean(np.sqrt(np.sum(np.square(diff_array),axis=1)))
	distance_max = np.max(np.sqrt(np.sum(np.square(diff_array),axis=1)))
	distance_no_rigid = np.mean(np.sqrt(np.sum(np.square(diff_array),axis=1)))
	return distance_mean, distance_max,distance_no_rigid
Example #30
0
def cal_sted_loss_in_file(tar_file_format, src_file_format = '/raid/jzh/CVPR2019/alignpose/Tester_{}/AlignPose/pose_{}.obj',vis = False):
    average_p_loss = []
    for j in range(141,151):
        for i in range(47):
            tar_mesh = om.read_trimesh(tar_file_format.format(j,i))

            src_mesh = om.read_trimesh(src_file_format.format(j,i))
            src_point=src_mesh.points()
            tar_point=tar_mesh.points()
            p_loss, _ = sted_compute_advanced(src_point, tar_point)
            #print(np.array(sted_array).astype(np.float64)[:3])
            #np.savetxt((tar_file_format[:-4]+'.txt').format(j,i), sted_array)
            average_p_loss.append(p_loss)
            if vis:
                print('people:{} exp: {}, STED {:9.6f}'.format(j, i, p_loss))
    print('Average loss: {}'.format(np.mean(average_p_loss)))
    print('median loss: {}'.format(np.median(average_p_loss)))
    print('extreme differ: {}'.format(np.max(np.abs(np.array(average_p_loss) - np.mean(average_p_loss)))))
    return average_p_loss