def Decimate_mesh(meshvtk,name_vtkmesh,nvertices=2000): print 'test' stlWriter = vtk.vtkSTLWriter() stlWriter.SetFileName('meshdecimated.stl') stlWriter.SetInputData(meshvtk) stlWriter.Write() mesh_om = om.PolyMesh() Result=om.read_mesh(mesh_om, "meshdecimated.stl") print Result deci_om=om.PolyMeshDecimater(mesh_om) mh=om.PolyMeshModQuadricHandle() deci_om.add(mh) deci_om.initialize() deci_om.decimate_to(nvertices) mesh_om.garbage_collection() assert mesh_om.n_vertices()==nvertices, 'vertices goal not acomplished; nvertices={0:d}'.format(mesh_om.n_vertices()) print "Decimation to {0} vertices Sucessful".format(nvertices) om.write_mesh(mesh_om,'meshdecimated.stl') stlReader = vtk.vtkSTLReader() stlReader.SetFileName('meshdecimated.stl') stlReader.Update() vtkwrite=vtk.vtkPolyDataWriter() vtkwrite.SetInputData(stlReader.GetOutput()) vtkwrite.SetFileName(name_vtkmesh) vtkwrite.Write() print "enters"
def test_write_triangle(self): filename = "triangle-minimal.om"; # Generate data v1 = self.mesh.add_vertex(openmesh.Vec3d(1.0, 0.0, 0.0)) v2 = self.mesh.add_vertex(openmesh.Vec3d(0.0, 1.0, 0.0)) v3 = self.mesh.add_vertex(openmesh.Vec3d(0.0, 0.0, 1.0)) self.mesh.add_face(v1, v2, v3) # Save ok = openmesh.write_mesh(self.mesh, filename) self.assertTrue(ok) # Reset self.mesh.clear() # Load ok = openmesh.read_mesh(self.mesh, filename) self.assertTrue(ok) # Compare self.assertEqual(self.mesh.n_vertices(), 3) self.assertEqual(self.mesh.n_edges(), 3) self.assertEqual(self.mesh.n_faces(), 1) self.assertEqual(self.mesh.point(v1), openmesh.Vec3d(1.0, 0.0, 0.0)) self.assertEqual(self.mesh.point(v2), openmesh.Vec3d(0.0, 1.0, 0.0)) self.assertEqual(self.mesh.point(v3), openmesh.Vec3d(0.0, 0.0, 1.0)) # Cleanup os.remove(filename)
def test_write_and_read_vertex_colors_to_and_from_off_file(self): self.mesh.request_vertex_colors() self.mesh.add_vertex(openmesh.Vec3d(0, 0, 1)) self.mesh.add_vertex(openmesh.Vec3d(0, 1, 0)) self.mesh.add_vertex(openmesh.Vec3d(0, 1, 1)) self.mesh.add_vertex(openmesh.Vec3d(1, 0, 1)) # Using the default openmesh Python color type testColor = openmesh.Vec4f(1.0, 0.5, 0.25, 1.0) # Setting colors (different from black) for v in self.mesh.vertices(): self.mesh.set_color(v, testColor) # Check if the colors are correctly set count = 0 for v in self.mesh.vertices(): color = self.mesh.color(v) if color[0] != testColor[0] or color[1] != testColor[1] or color[2] != testColor[2]: count += 1 self.assertEqual(count, 0) options = openmesh.Options() options += openmesh.Options.VertexColor options += openmesh.Options.ColorFloat openmesh.write_mesh(self.mesh, "temp.off", options) openmesh.read_mesh(self.mesh, "temp.off", options) # Check if vertices still have the same color count = 0 for v in self.mesh.vertices(): color = self.mesh.color(v) if color[0] != testColor[0] or color[1] != testColor[1] or color[2] != testColor[2]: count += 1 self.assertEqual(count, 0) self.mesh.release_vertex_colors()
def test_write_and_read_binary_float_vertex_colors_to_and_from_off_file(self): self.mesh.request_vertex_colors() options = openmesh.Options(openmesh.Options.VertexColor) ok = openmesh.read_mesh(self.mesh, "meshlab.ply", options) self.assertTrue(ok) options.clear() options += openmesh.Options.VertexColor options += openmesh.Options.Binary options += openmesh.Options.ColorFloat # Write the mesh ok = openmesh.write_mesh(self.mesh, "cube_floating_binary.off", options) self.assertTrue(ok) self.mesh.clear() options.clear() options += openmesh.Options.VertexColor options += openmesh.Options.Binary options += openmesh.Options.ColorFloat ok = openmesh.read_mesh(self.mesh, "cube_floating_binary.off", options) self.assertTrue(ok) 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(options.vertex_has_normal()) self.assertFalse(options.vertex_has_texcoord()) self.assertFalse(options.face_has_color()) self.assertTrue(options.vertex_has_color()) self.assertTrue(options.color_is_float()) self.assertTrue(options.is_binary()) self.mesh.release_vertex_colors()
def test_write_and_read_binary_ply_with_float_vertex_colors(self): self.mesh.request_vertex_colors() options = openmesh.Options() options += openmesh.Options.VertexColor ok = openmesh.read_mesh(self.mesh, "meshlab.ply", options) self.assertTrue(ok) options += openmesh.Options.ColorFloat options += openmesh.Options.Binary ok = openmesh.write_mesh(self.mesh, "meshlab_binary_float.ply", options) self.assertTrue(ok) self.mesh.clear ok = openmesh.read_mesh(self.mesh, "meshlab_binary_float.ply", options) self.assertTrue(ok) 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(options.vertex_has_normal()) self.assertFalse(options.vertex_has_texcoord()) self.assertTrue(options.vertex_has_color()) self.assertTrue(options.color_is_float()) self.assertTrue(options.is_binary()) self.mesh.release_vertex_colors()
def test(net=None, save_subdir="test"): opt.phase = "test" dataset = build_dataset(opt) if opt.dim == 3: init_cage_V, init_cage_Fs = loadInitCage([opt.template]) cage_V_t = init_cage_V.transpose(1, 2).detach().cuda() else: init_cage_V = generatePolygon(0, 0, 1.5, 0, 0, 0, opt.cage_deg) init_cage_V = torch.tensor([(x, y) for x, y in init_cage_V], dtype=torch.float).unsqueeze(0) cage_V_t = init_cage_V.transpose(1, 2).detach().cuda() init_cage_Fs = [ torch.arange(opt.cage_deg, dtype=torch.int64).view(1, 1, -1).cuda() ] if net is None: # network net = networks.NetworkFull( opt, dim=opt.dim, bottleneck_size=opt.bottleneck_size, template_vertices=cage_V_t, template_faces=init_cage_Fs[-1], ).cuda() net.eval() load_network(net, opt.ckpt) else: net.eval() print(net) dataloader = torch.utils.data.DataLoader( dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=tolerating_collate, num_workers=0, worker_init_fn=lambda id: np.random.seed(np.random.get_state()[1][0] + id)) test_output_dir = os.path.join(opt.log_dir, save_subdir) os.makedirs(test_output_dir, exist_ok=True) with open(os.path.join(test_output_dir, "eval.txt"), "w") as f: with torch.no_grad(): for i, data in enumerate(dataloader): data = dataset.uncollate(data) ############# blending ############ # sample 4 different alpha if opt.blend_style: num_alpha = 4 blend_alpha = torch.linspace( 0, 1, steps=num_alpha, dtype=torch.float32).cuda().reshape(num_alpha, 1) data["source_shape"] = data["source_shape"].expand( num_alpha, -1, -1).contiguous() data["target_shape"] = data["target_shape"].expand( num_alpha, -1, -1).contiguous() else: blend_alpha = 1.0 data["alpha"] = blend_alpha ################################### source_shape_t = data["source_shape"].transpose( 1, 2).contiguous().detach() target_shape_t = data["target_shape"].transpose( 1, 2).contiguous().detach() outputs = net(source_shape_t, target_shape_t, blend_alpha) deformed = outputs["deformed"] ####################### evaluation ######################## s_filename = os.path.splitext(data["source_file"][0])[0] t_filename = os.path.splitext(data["target_file"][0])[0] log_str = "{}/{} {}-{} ".format(i, len(dataloader), s_filename, t_filename) print(log_str) f.write(log_str + "\n") ###################### outputs ############################ for b in range(deformed.shape[0]): if "source_mesh" in data and data[ "source_mesh"] is not None: if isinstance(data["source_mesh"][0], str): source_mesh = om.read_polymesh( data["source_mesh"][0]).points().copy() source_mesh = dataset.normalize( source_mesh, opt.isV2) source_mesh = torch.from_numpy( source_mesh.astype( np.float32)).unsqueeze(0).cuda() deformed = deform_with_MVC( outputs["cage"][b:b + 1], outputs["new_cage"][b:b + 1], outputs["cage_face"], source_mesh) else: deformed = deform_with_MVC( outputs["cage"][b:b + 1], outputs["new_cage"][b:b + 1], outputs["cage_face"], data["source_mesh"]) deformed[b] = center_bounding_box(deformed[b])[0] if data["source_face"] is not None and data[ "source_mesh"] is not None: source_mesh = data["source_mesh"][0].detach().cpu() source_mesh = center_bounding_box(source_mesh)[0] source_face = data["source_face"][0].detach().cpu() tosave = pymesh.form_mesh(vertices=source_mesh, faces=source_face) pymesh.save_mesh(os.path.join( opt.log_dir, save_subdir, "{}-{}-Sa.obj".format(s_filename, t_filename)), tosave, use_float=True) tosave = pymesh.form_mesh( vertices=deformed[0].detach().cpu(), faces=source_face) pymesh.save_mesh( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sab-{}.obj".format( s_filename, t_filename, b)), tosave, use_float=True, ) elif data["source_face"] is None and isinstance( data["source_mesh"][0], str): orig_file_path = data["source_mesh"][0] mesh = om.read_polymesh(orig_file_path) points_arr = mesh.points() points_arr[:] = source_mesh[0].detach().cpu().numpy() om.write_mesh( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sa.obj".format(s_filename, t_filename)), mesh) points_arr[:] = deformed[0].detach().cpu().numpy() om.write_mesh( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sab-{}.obj".format( s_filename, t_filename, b)), mesh) else: # save to "pts" for rendering save_pts( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sa.pts".format(s_filename, t_filename)), data["source_shape"][b].detach().cpu()) save_pts( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sab-{}.pts".format( s_filename, t_filename, b)), deformed[0].detach().cpu()) if data["target_face"] is not None and data[ "target_mesh"] is not None: data["target_mesh"][0] = center_bounding_box( data["target_mesh"][0])[0] tosave = pymesh.form_mesh( vertices=data["target_mesh"][0].detach().cpu(), faces=data["target_face"][0].detach().cpu()) pymesh.save_mesh( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sb.obj".format(s_filename, t_filename)), tosave, use_float=True, ) elif data["target_face"] is None and isinstance( data["target_mesh"][0], str): orig_file_path = data["target_mesh"][0] mesh = om.read_polymesh(orig_file_path) points_arr = mesh.points() points_arr[:] = dataset.normalize( points_arr.copy(), opt.isV2) om.write_mesh( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sb.obj".format(s_filename, t_filename)), mesh) else: save_pts( os.path.join( opt.log_dir, save_subdir, "{}-{}-Sb.pts".format(s_filename, t_filename)), data["target_shape"][0].detach().cpu()) outputs["cage"][b] = center_bounding_box( outputs["cage"][b])[0] outputs["new_cage"][b] = center_bounding_box( outputs["new_cage"][b])[0] pymesh.save_mesh_raw( os.path.join( opt.log_dir, save_subdir, "{}-{}-cage1-{}.ply".format( s_filename, t_filename, b)), outputs["cage"][b].detach().cpu(), outputs["cage_face"][0].detach().cpu(), binary=True) pymesh.save_mesh_raw( os.path.join( opt.log_dir, save_subdir, "{}-{}-cage2-{}.ply".format( s_filename, t_filename, b)), outputs["new_cage"][b].detach().cpu(), outputs["cage_face"][0].detach().cpu(), binary=True) dataset.render_result(test_output_dir)
if not os.path.exists(opt.outf): os.makedirs(opt.outf) PIL.Image.fromarray(sr_proj_img).save(opt.outf + "%04d_ours_s.png" % test_num) if opt.step: PIL.Image.fromarray(src_img).save(opt.outf + "%04d_src.png" % test_num) PIL.Image.fromarray(ja_proj_img).save(opt.outf + "%04d_ours_j.png" % test_num) PIL.Image.fromarray(sa_proj_img).save(opt.outf + "%04d_ours_a.png" % test_num) PIL.Image.fromarray(ori_proj_img).save(opt.outf + "%04d_hmr.png" % test_num) if opt.mesh: ja_mesh = make_trimesh(ja_verts, faces_smpl) om.write_mesh(opt.outf + "%04d_mesh_j.obj" % test_num, ja_mesh) sa_mesh = make_trimesh(sa_verts, faces_smpl) om.write_mesh(opt.outf + "%04d_mesh_a.obj" % test_num, sa_mesh) om.write_mesh(opt.outf + "%04d_mesh_v.obj" % test_num, deformed_mesh) print("mesh saved to [%s]" + opt.outf + "%04d_mesh.obj" % test_num) if opt.gif: gb_src_img = src_img.copy() # green bounding source image gb_src_img[:, :3] = gb_src_img[:, :3] / 2 + np.array([0, 128, 0]) gb_src_img[:3, :] = gb_src_img[:3, :] / 2 + np.array([0, 128, 0]) gb_src_img[-3:, :] = gb_src_img[-3:, :] / 2 + np.array([0, 128, 0]) gb_src_img[:, -3:] = gb_src_img[:, -3:] / 2 + np.array([0, 128, 0]) PIL.Image.fromarray(gb_src_img).save(opt.outf + "%04d_src_gb.png" % test_num) gif_name = opt.outf + "%04d.gif" % test_num
from vector import * import openmesh as om import numpy as np # create mesh for bottom part d1 = np.sqrt(0.5) mesh = om.TriMesh() # trigger part make_block_triangle_mesh(mesh, [10 + d1, 5 * d1 + 6, 1], [5 - 2 * d1, 0, 0], [0, -5 + 2 * d1, 0], [0, 0, 1]) make_block_mesh(mesh, [10 + d1, 15, 1], [0, -15 + 5 * d1 + 6, 0], [5 - 2 * d1, 0, 0], [0, 0, 1]) make_block_mesh(mesh, [10 + d1, 5 * d1 + 6, 1], [-5, 0, 0], [0, -1.5, 0], [0, 0, 1]) om.write_mesh("rubber_gun_trigger_part2.obj", mesh) d2 = 0.5 for i in range(5): mesh = om.TriMesh() make_block_triangle_mesh(mesh, [10 + d1, 5 * d1 + 6 - i * d2, 1], [5 - 2 * d1, 0, 0], [0, -5 + 2 * d1, 0], [0, 0, 1]) make_block_mesh(mesh, [10 + d1, 15 - i * d2, 1], [0, -15 + 5 * d1 + 6, 0], [5 - 2 * d1, 0, 0], [0, 0, 1]) make_block_mesh(mesh, [10 + d1, 5 * d1 + 6 - i * d2, 1], [-5, 0, 0], [0, -1.5, 0], [0, 0, 1]) om.write_mesh("rubber_gun_trigger_part2_{0}.obj".format(i), mesh)
def test_all(opt, new_cage_shape): opt.phase = "test" opt.target_model = None print(opt.model) if opt.is_poly: source_mesh = om.read_polymesh(opt.model) else: source_mesh = om.read_trimesh(opt.model) dataset = build_dataset(opt) dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=tolerating_collate, num_workers=0, worker_init_fn=lambda id: np.random.seed(np.random.get_state()[1][0] + id)) states = torch.load(opt.ckpt) if "states" in states: states = states["states"] # states["template_vertices"] = new_cage_shape.transpose(1, 2) # states["source_vertices"] = new_source.transpose(1,2) # states["source_faces"] = new_source_face # new_source_face = states["source_faces"] om.write_mesh(os.path.join(opt.log_dir, opt.subdir, "template-Sa.ply"), source_mesh) net = networks.FixedSourceDeformer(opt, 3, opt.num_point, bottleneck_size=opt.bottleneck_size, template_vertices=states["template_vertices"], template_faces=states["template_faces"].cuda(), source_vertices=states["source_vertices"], source_faces=states["source_faces"]).cuda() load_network(net, states) source_points = torch.from_numpy( source_mesh.points().copy()).float().cuda().unsqueeze(0) with torch.no_grad(): # source_face = net.source_faces.detach() for i, data in enumerate(dataloader): data = dataset.uncollate(data) target_shape, target_filename = data["target_shape"], data["target_file"] logger.info("", data["target_file"][0]) sample_idx = None if "sample_idx" in data: sample_idx = data["sample_idx"] outputs = net(target_shape.transpose(1, 2), cage_only=True) if opt.d_residual: cage_offset = outputs["new_cage"]-outputs["cage"] outputs["cage"] = new_cage_shape outputs["new_cage"] = new_cage_shape+cage_offset deformed = deform_with_MVC(outputs["cage"], outputs["new_cage"], outputs["cage_face"].expand( outputs["cage"].shape[0], -1, -1), source_points) for b in range(deformed.shape[0]): t_filename = os.path.splitext(target_filename[b])[0] source_mesh_arr = source_mesh.points() source_mesh_arr[:] = deformed[0].cpu().detach().numpy() om.write_mesh(os.path.join( opt.log_dir, opt.subdir, "template-{}-Sab.obj".format(t_filename)), source_mesh) # if data["target_face"] is not None and data["target_mesh"] is not None: # pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-{}-Sa.ply".format(t_filename)), # source_mesh[0].detach().cpu(), source_face[b].detach().cpu()) pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-{}-Sb.ply".format(t_filename)), data["target_mesh"][b].detach().cpu(), data["target_face"][b].detach().cpu()) # pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-{}-Sab.ply".format(t_filename)), # deformed[b].detach().cpu(), source_face[b].detach().cpu()) # else: # save_ply(source_mesh[0].detach().cpu(), os.path.join(opt.log_dir, opt.subdir,"template-{}-Sa.ply".format(t_filename))) # save_ply(target_shape[b].detach().cpu(), os.path.join(opt.log_dir, opt.subdir,"template-{}-Sb.ply".format(t_filename)), # normals=data["target_normals"][b].detach().cpu()) # save_ply(deformed[b].detach().cpu(), os.path.join(opt.log_dir, opt.subdir,"template-{}-Sab.ply".format(t_filename)), # normals=data["target_normals"][b].detach().cpu()) pymesh.save_mesh_raw( os.path.join(opt.log_dir, opt.subdir, "template-{}-cage1.ply".format(t_filename)), outputs["cage"][b].detach().cpu(), outputs["cage_face"][b].detach().cpu(), ) pymesh.save_mesh_raw( os.path.join(opt.log_dir, opt.subdir, "template-{}-cage2.ply".format(t_filename)), outputs["new_cage"][b].detach().cpu(), outputs["cage_face"][b].detach().cpu(), ) # if opt.opt_lap and deformed.shape[1] == source_mesh.shape[1]: # deformed = optimize_lap(opt, source_mesh, deformed, source_face) # for b in range(deformed.shape[0]): # pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-{}-Sab-optlap.ply".format(t_filename)), # deformed[b].detach().cpu(), source_face[b].detach().cpu()) if i % 20 == 0: logger.success("[{}/{}] Done".format(i, len(dataloader))) dataset.render_result(os.path.join(opt.log_dir, opt.subdir))
assert opt.set in ["recon", "syn"], \ "set must be one of [recon, syn]" data_num = int(opt.num) output_dir = "./eval_data/%s_set/pred_save/" % opt.set if not os.path.exists(output_dir): os.makedirs(output_dir) hmr_pred = hmr_predictor() faces = np.load("../predef/smpl_faces.npy") tr = trange(data_num, desc='Bar desc', leave=True) for i in tr: src_img = np.array(PIL.Image.open("./eval_data/%s_set/input_masked/%03d_img.png" % \ (opt.set, i)))[:,:,:3] verts, cam, proc_para, std_img = hmr_pred.predict(src_img) with open(output_dir + "pre_%03d.pkl" % i, 'wb') as fp: pickle.dump( { "verts": verts, "cam": cam, "proc_para": proc_para, "std_img": std_img, }, fp) mesh = make_trimesh(verts, faces) om.write_mesh("./eval_data/%s_set/pred_save/hmr_%03d.obj" % (opt.set, i), mesh)
def test_read_write_read(self): mesh1 = openmesh.read_trimesh("TestFiles/cube-minimal.stl") openmesh.write_mesh('OutFiles/test_read_write_read.stl', mesh1) mesh2 = openmesh.read_trimesh('OutFiles/test_read_write_read.stl') self.assertTrue(np.allclose(mesh1.points(), mesh2.points())) self.assertTrue(np.array_equal(mesh1.face_vertex_indices(), mesh2.face_vertex_indices()))
import openmesh as om import numpy as np import cv2.cv2 as cv mesh = om.TriMesh() rgbImg = cv.imread('rgb.png') dImg = cv.imread('d.png') imgWidth = rgbImg.shape[0] imgHeight = rgbImg.shape[1] for i in range(0, imgWidth): for j in range(0, imgHeight): if dImg[i, j][0] > 0: x = j y = -i z = dImg[i, j][0] * 2.3 vh = mesh.add_vertex([x, y, z]) g = rgbImg[i, j][0] / 255 b = rgbImg[i, j][1] / 255 r = rgbImg[i, j][2] / 255 mesh.set_color(vh, [r, g, b, 0]) om.write_mesh('PointCloud.ply', mesh, vertex_color=True)
faces = np.array([[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 6], [0, 6, 1], [1, 2, 7], [2, 3, 7], [3, 4, 7], [4, 5, 7], [5, 6, 7], [6, 1, 7]]) mesh = om.TriMesh() vlist = [] for i in coords: vlist.append(mesh.add_vertex(i)) flist = [] for i in faces: flist.append(mesh.add_face(vlist[i[0]], vlist[i[1]], vlist[i[2]])) om.write_mesh('../data/irreg.off', mesh) def load(): return coords, faces one_stride_s = mesh_traversal.traverse_mesh(coords, faces, 0, is_sparse=True) two_stride_s = mesh_traversal.traverse_mesh(coords, faces, 0, 2, is_sparse=True) three_stride_s = mesh_traversal.traverse_mesh(coords, faces, 0,
n = [0, 0, 0, 0] mesh.set_normal(vh0, n) mesh.set_normal(vh1, n) mesh.set_normal(vh2, n) mesh.set_normal(vh3, n) mesh.set_normal(vh4, n) # add another face to the mesh, this time using a list vh_list = [vh2, vh1, vh4] fh3 = mesh.add_face(vh_list) # 0 ==== 2 # |\ 0 /| # | \ / | # |2 1 3| # | / \ | # |/ 1 \| # 3 ==== 4 # get the point with vertex handle vh0 point = mesh.point(vh0) # get all points of the mesh point_array = mesh.points() # translate the mesh along the x-axis # point_array += np.array([1, 0, 0]) # write and read meshes om.write_mesh('cone.ply', mesh, vertex_normal=True, vertex_color=True)
from vector import * import openmesh as om import numpy as np # create mesh for top part d1 = np.sqrt(0.5) mesh = om.TriMesh() #make_block_mesh(mesh, [0, 0, 2], [5, 0, 0], [0, 5, 0], [0, 0, 1]) make_block_mesh(mesh, [5, 0, 2], [5, 0, 0], [0, 5, 0], [0, 0, 1]) make_block_mesh(mesh, [10, 0, 2], [5, 0, 0], [0, 20, 0], [0, 0, 1]) #make_block_mesh(mesh, [10, 20, 2], [5, 0, 0], [0, 5, 0], [0, 0, 1]) make_block_mesh(mesh, [14.5, 25, 2], [0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]) make_block_mesh(mesh, [10, 25, 2], [4, 0, 0], [0, 0.5, 0], [0, 0, 1]) make_block_mesh(mesh, [15 - d1, 0, 2], [0.5 * d1, -0.5 * d1, 0], [0.5 * d1, 0.5 * d1, 0], [0, 0, 1]) make_block_mesh(mesh, [15 - d1, 0, 2], [-0.5 * d1, 0.5 * d1, 0], [-0.5 * d1, -0.5 * d1, 0], [0, 0, 1]) # make hole part make_pipe_mesh(mesh, [2.5, 2.5, 2], [2.5, 2.5, 3], p2=[1, 1, 0.0], r1=d1, r2=5 * d1, n=4) make_pipe_mesh(mesh, [12.5, 22.5, 2], [12.5, 22.5, 3], p2=[22.5, 12.5, 0.0], r1=d1, r2=5 * d1, n=4) om.write_mesh("rubber_gun_top.obj", mesh)
from trianglulation import * from vector import * import numpy as np import math import openmesh as om mesh = om.TriMesh() make_funnel_mesh(mesh, [0, 0, 0], [0, 0, 3.8], p2=[1.0, 0.0, 0.0], z0=-0.5, c1=1.0, r1=15.0, r2=0.1, n=100, m=50) om.write_mesh("funnel_test1.obj", mesh)
file_gii = os.path.join(file_gii) img = nib.load(file_gii) img.print_summary() # these are the spatial coordinates data0 = img.darrays[0].data # these are the mesh connections data1 = img.darrays[1].data mesh = om.TriMesh() verts = [] for i in data0: verts.append(mesh.add_vertex(i)) v = [] faces = [] for i in data1: v.append(i[0]) v.append(i[1]) v.append(i[2]) faces.append(mesh.add_face(verts[i[0]], verts[i[1]], verts[i[2]])) v = set(v) print(len(verts)) pickle.dump(v, open("verts.pickle", "wb")) om.write_mesh('example_mesh.off', mesh)
if not os.path.exists(opt.outf): os.makedirs(opt.outf) PIL.Image.fromarray(sr_proj_img).save(opt.outf + "%04d_ours_s.png" % test_num) if opt.step: PIL.Image.fromarray(src_img).save(opt.outf + "%04d_src.png" % test_num) PIL.Image.fromarray(ja_proj_img).save(opt.outf + "%04d_ours_j.png" % test_num) PIL.Image.fromarray(sa_proj_img).save(opt.outf + "%04d_ours_a.png" % test_num) PIL.Image.fromarray(ori_proj_img).save(opt.outf + "%04d_hmr.png" % test_num) if opt.mesh: import openmesh as om om.write_mesh(opt.outf + "%04d_mesh.obj" % test_num, deformed_mesh) print("mesh saved to [%s]" + opt.outf + "%04d_mesh.obj" % test_num) if opt.gif: gb_src_img = src_img.copy() # green bounding source image gb_src_img[:, :3] = gb_src_img[:, :3] / 2 + np.array([0, 128, 0]) gb_src_img[:3, :] = gb_src_img[:3, :] / 2 + np.array([0, 128, 0]) gb_src_img[-3:, :] = gb_src_img[-3:, :] / 2 + np.array([0, 128, 0]) gb_src_img[:, -3:] = gb_src_img[:, -3:] / 2 + np.array([0, 128, 0]) PIL.Image.fromarray(gb_src_img).save(opt.outf + "%04d_src_gb.png" % test_num) gif_name = opt.outf + "%04d.gif" % test_num file_list = [ opt.outf + "%04d_src_gb.png" % test_num, opt.outf + "%04d_hmr.png" % test_num,
curve_mesh = EmbeddedCurveMesh(host_mesh) for h in host_mesh.halfedges(): vf, vt = host_mesh.from_vertex_handle(h), host_mesh.to_vertex_handle(h) vtt = host_mesh.to_vertex_handle(host_mesh.next_halfedge_handle(h)) if VL[vf.idx()] != VL[vt.idx()] != VL[vtt.idx()]: curve_mesh.add_embedd_edge(h, 0.5, host_mesh.next_halfedge_handle(h), 0.5).idx() color_map = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0.5, 0.5, 0]]) curve_mesh.request_vertex_colors() curve_mesh.request_face_colors() for i in range(len(V)): curve_mesh.set_color(curve_mesh.vertex_handle(i), np.append(color_map[VL[i], :], 1)) for f in curve_mesh.vf(curve_mesh.vertex_handle(i)): curve_mesh.set_color(f, np.append(color_map[VL[i], :], 1)) for i in range(len(V), curve_mesh.n_vertices()): curve_mesh.set_color(curve_mesh.vertex_handle(i), (1, 1, 1, 1)) om.write_mesh("1.off", curve_mesh, vertex_color=True, face_color=True) for curve in curve_mesh.extract_em_curves(): curve_length_minimize(curve_mesh, curve, 0.35) curvature_variation_minimize(curve_mesh, curve) break om.write_mesh("smoothed.off", curve_mesh, vertex_color=True, face_color=True)
if opt.crop_y != -1: if len(opt.crop_y) != 2: print("ERROR: crop_y must be a list with 2 elements") crop_img = crop_img[opt.crop_y[0]:-opt.crop_y[1], :] if opt.pad>0: crop_img = pad_arr(crop_img, 50) std_img, proc_para = preproc_img(crop_img, img_size = 224, margin = 30, normalize = True) # initialize hmr_pred = hmr_predictor() renderer = SMPLRenderer() faces = np.load("../predef/smpl_faces.npy") # hmr predict verts, cam, proc_para, std_img = hmr_pred.predict(std_img, normalize=False) # build output folder if not exist if not os.path.exists(opt.outf): os.makedirs(opt.outf) # write results result_mesh = make_trimesh(verts, faces) om.write_mesh(opt.outf + "hmr_mesh.obj", result_mesh) final_img = ((std_img.copy()+1)*127).astype(np.uint8) PIL.Image.fromarray(final_img).save(opt.outf + "std_img.jpg") print("%s - finished, results are saved to [%s]" % (opt.img, opt.outf)) print("hmr done")
def optimize(opt): """ weights are the same with the original source mesh target=net(old_source) """ # load new target if opt.is_poly: target_mesh = om.read_polymesh(opt.model) else: target_mesh = om.read_trimesh(opt.model) target_shape_arr = target_mesh.points() target_shape = target_shape_arr.copy() target_shape = torch.from_numpy( target_shape[:, :3].astype(np.float32)).cuda() target_shape.unsqueeze_(0) states = torch.load(opt.ckpt) if "states" in states: states = states["states"] cage_v = states["template_vertices"].transpose(1, 2).cuda() cage_f = states["template_faces"].cuda() shape_v = states["source_vertices"].transpose(1, 2).cuda() shape_f = states["source_faces"].cuda() if os.path.isfile(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")) and os.path.isfile(opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked")): new_label_path = opt.model.replace(os.path.splitext(opt.model)[1], ".picked") orig_label_path = opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked") logger.info("Loading picked labels {} and {}".format(orig_label_path, new_label_path)) import pandas as pd new_label = pd.read_csv(new_label_path, delimiter=" ",skiprows=1, header=None) orig_label = pd.read_csv(orig_label_path, delimiter=" ",skiprows=1, header=None) orig_label_name = orig_label.iloc[:,5] new_label_name = new_label.iloc[:,5].tolist() new_to_orig_idx = [] for i, name in enumerate(new_label_name): matched_idx = orig_label_name[orig_label_name==name].index if matched_idx.size == 1: new_to_orig_idx.append((i, matched_idx[0])) new_to_orig_idx = np.array(new_to_orig_idx) if new_label.shape[1] == 10: new_vidx = new_label.iloc[:,9].to_numpy()[new_to_orig_idx[:,0]] target_points = target_shape[:, new_vidx, :] else: new_label_points = torch.from_numpy(new_label.iloc[:,6:9].to_numpy().astype(np.float32)) target_points = new_label_points.unsqueeze(0).cuda() target_points, new_vidx, _ = faiss_knn(1, target_points, target_shape, NCHW=False) target_points = target_points.squeeze(2) # B,N,3 new_label[9] = new_vidx.squeeze(0).squeeze(-1).cpu().numpy() new_label.to_csv(new_label_path, sep=" ", header=[str(new_label.shape[0])]+[""]*(new_label.shape[1]-1), index=False) target_points = target_points[:, new_to_orig_idx[:,0], :] target_points = target_points.cuda() source_shape, _ = read_trimesh(opt.source_model) source_shape = torch.from_numpy(source_shape[None, :,:3]).float() if orig_label.shape[1] == 10: orig_vidx = orig_label.iloc[:,9].to_numpy()[new_to_orig_idx[:,1]] source_points = source_shape[:, orig_vidx, :] else: orig_label_points = torch.from_numpy(orig_label.iloc[:,6:9].to_numpy().astype(np.float32)) source_points = orig_label_points.unsqueeze(0) # find the closest point on the original meshes source_points, new_vidx, _ = faiss_knn(1, source_points, source_shape, NCHW=False) source_points = source_points.squeeze(2) # B,N,3 orig_label[9] = new_vidx.squeeze(0).squeeze(-1).cpu().numpy() orig_label.to_csv(orig_label_path, sep=" ", header=[str(orig_label.shape[0])]+[""]*(orig_label.shape[1]-1), index=False) source_points = source_points[:,new_to_orig_idx[:,1],:] _, source_center, _ = center_bounding_box(source_shape[0]) source_points -= source_center source_points = source_points.cuda() # # shift target so that the belly match # try: # orig_bellyUp_idx = orig_label_name[orig_label_name=="bellUp"].index[0] # orig_bellyUp = orig_label_points[orig_bellyUp_idx, :] # new_bellyUp_idx = [i for i, i2 in new_to_orig_idx if i2==orig_bellyUp_idx][0] # new_bellyUp = new_label_points[new_bellyUp_idx,:] # target_points += (orig_bellyUp - new_bellyUp) # except Exception as e: # logger.warn("Couldn\'t match belly to belly") # traceback.print_exc(file=sys.stdout) # source_points[0] = center_bounding_box(source_points[0])[0] elif not os.path.isfile(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")) and os.path.isfile(opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked")): logger.info("Assuming Faust model") orig_label_path = opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked") logger.info("Loading picked labels {}".format(orig_label_path)) import pandas as pd orig_label = pd.read_csv(orig_label_path, delimiter=" ",skiprows=1, header=None) orig_label_name = orig_label.iloc[:,5] source_shape, _ = read_trimesh(opt.source_model) source_shape = torch.from_numpy(source_shape[None, :,:3]).cuda().float() if orig_label.shape[1] == 10: idx = torch.from_numpy(orig_label.iloc[:,9].to_numpy()).long() source_points = source_shape[:,idx,:] target_points = target_shape[:,idx,:] else: source_points = torch.from_numpy(orig_label.iloc[:,6:9].to_numpy().astype(np.float32)) source_points = source_points.unsqueeze(0).cuda() # find the closest point on the original meshes source_points, idx, _ = faiss_knn(1, source_points, source_shape, NCHW=False) source_points = source_points.squeeze(2) # B,N,3 idx = idx.squeeze(-1) target_points = target_shape[:,idx,:] _, source_center, _ = center_bounding_box(source_shape[0]) source_points -= source_center elif opt.corres_idx is None and target_shape.shape[1] == shape_v.shape[1]: logger.info("No correspondence provided, assuming registered Faust models") # corresp_idx = torch.randint(0, shape_f.shape[1], (100,)).cuda() corresp_v = torch.unique(torch.randint(0, shape_v.shape[1], (4800,))).cuda() target_points = torch.index_select(target_shape, 1, corresp_v) source_points = torch.index_select(shape_v, 1, corresp_v) target_shape[0], target_center, target_scale = center_bounding_box(target_shape[0]) _, _, source_scale = center_bounding_box(shape_v[0]) target_scale_factor = (source_scale/target_scale)[1] target_shape *= target_scale_factor target_points -= target_center target_points = (target_points*target_scale_factor).detach() # make sure test use the normalized target_shape_arr[:] = target_shape[0].cpu().numpy() om.write_mesh(os.path.join(opt.log_dir, opt.subdir, os.path.splitext( os.path.basename(opt.model))[0]+"_normalized.obj"), target_mesh) opt.model = os.path.join(opt.log_dir, opt.subdir, os.path.splitext( os.path.basename(opt.model))[0]+"_normalized.obj") pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-initial.obj"), shape_v[0].cpu().numpy(), shape_f[0].cpu().numpy()) pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "cage-initial.obj"), cage_v[0].cpu().numpy(), cage_f[0].cpu().numpy()) save_ply(target_points[0].cpu().numpy(), os.path.join( opt.log_dir, opt.subdir, "target_points.ply")) save_ply(source_points[0].cpu().numpy(), os.path.join( opt.log_dir, opt.subdir, "source_points.ply")) logger.info("Optimizing for {} corresponding vertices".format( target_points.shape[1])) cage_init = cage_v.clone().detach() lap_loss = MeshLaplacianLoss(torch.nn.MSELoss(reduction="none"), use_cot=True, use_norm=True, consistent_topology=True, precompute_L=True) mvc_reg_loss = MVCRegularizer(threshold=50, beta=1.0, alpha=0.0) cage_v.requires_grad_(True) optimizer = torch.optim.Adam([cage_v], lr=opt.lr, betas=(0.5, 0.9)) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, int(opt.nepochs*0.4), gamma=0.5, last_epoch=-1) if opt.dim == 3: weights_ref = mean_value_coordinates_3D( source_points, cage_init, cage_f, verbose=False) else: raise NotImplementedError for t in range(opt.nepochs): optimizer.zero_grad() weights = mean_value_coordinates_3D( target_points, cage_v, cage_f, verbose=False) loss_mvc = torch.mean((weights-weights_ref)**2) # reg = torch.sum((cage_init-cage_v)**2, dim=-1)*1e-4 reg = 0 if opt.clap_weight > 0: reg = lap_loss(cage_init, cage_v, face=cage_f)*opt.clap_weight reg = reg.mean() if opt.mvc_weight > 0: reg += mvc_reg_loss(weights)*opt.mvc_weight # weight regularizer with the shape difference # dist = torch.sum((source_points - target_points)**2, dim=-1) # weights = torch.exp(-dist) # reg = reg*weights*0.1 loss = loss_mvc + reg if (t+1) % 50 == 0: print("t {}/{} mvc_loss: {} reg: {}".format(t, opt.nepochs, loss_mvc.item(), reg.item())) if loss_mvc.item() < 5e-6: break loss.backward() optimizer.step() scheduler.step() return cage_v, cage_f
fh57 = mesh.add_face(vh43, vh31, vh2) fh58 = mesh.add_face(vh31, vh38, vh2) fh59 = mesh.add_face(vh38, vh15, vh2) fh60 = mesh.add_face(vh38, vh37, vh15) fh61 = mesh.add_face(vh15, vh37, vh14) fh62 = mesh.add_face(vh37, vh36, vh14) fh63 = mesh.add_face(vh36, vh13, vh14) fh64 = mesh.add_face(vh36, vh32, vh13) fh65 = mesh.add_face(vh32, vh3, vh13) # get all points of the mesh point_array = mesh.points() # write and read meshes om.write_mesh('test.off', mesh) mesh_2 = om.read_trimesh('test.off') ###### CALCULO DE CENTROIDES Y AREAS DE LAS CELDAS ###### #Recorrer todas las interfaces contador = 0 for eh in mesh.edges(): eIdx = eh.idx() # devuelve el indice global del elemento contador = contador + 1 print(contador) # arreglo de baricentros aCenterx = [] aCentery = [] # arreglo de Area
#=============================================================================== # # This part should be in a function but it crashes duw to openmesh :/ #=============================================================================== mesh_om = om.PolyMesh() Result=om.read_mesh(mesh_om, "meshdecimated.stl") assert Result, "Open mesh could not read file" deci_om=om.PolyMeshDecimater(mesh_om) mh=om.PolyMeshModQuadricHandle() deci_om.add(mh) deci_om.initialize() deci_om.decimate_to(nvertices) mesh_om.garbage_collection() assert mesh_om.n_vertices()==nvertices, 'vertices goal not acomplished; nvertices={0:d}'.format(mesh_om.n_vertices()) print "Decimation to {0} vertices Sucessful".format(nvertices) om.write_mesh(mesh_om,'meshdecimated.stl') ################################################################################ meshvtktmp=LoadSTLMesh('meshdecimated.stl') WriteVTKMesh(meshvtktmp,"mymesh.vtk") meshvtk_dec=LoadVTKMesh('mymesh.vtk') compute_info_mesh(meshvtk_dec) norms=Compute_Normals(meshvtk_dec) glyph = MakeGlyphs(norms) Display_Normal_Mesh(meshvtk_dec,glyph,"arrows")
ax = np.int(np.round(achr_posi[j][0])) if cim[ay, ax] == 0: active_index[j] = 0 # anchor deform fd_sa = fast_deform_dsa(weight=1.0) sa_verts = fd_sa.deform( np.asarray(ja_verts), new_av, active_index=active_index, ) # visualize if False: ori_proj_img = renderer(verts=verts, img=src_img) joint_move_img = draw_vert_move(ori_jv, new_jv, src_img) achr_move_img = draw_vert_move(ori_av, new_av, src_img) ja_proj_img = renderer(verts=ja_verts, img=src_img) sa_proj_img = renderer(verts=sa_verts, img=src_img) final_prv_img = np.concatenate( (ori_proj_img, joint_move_img, ja_proj_img, achr_move_img, sa_proj_img), axis=1) show_img_arr(final_prv_img.astype(np.uint8)) mesh_j = make_trimesh(ja_verts, faces) om.write_mesh("./eval_data/%s_set/pred_save/j_%03d.obj" % \ (opt.set, test_ind), mesh_j) mesh_a = make_trimesh(sa_verts, faces) om.write_mesh("./eval_data/%s_set/pred_save/a_%03d.obj" % \ (opt.set, test_ind), mesh_a)
visi_vert_inds.append(fv[0]) visi_vert_inds.append(fv[1]) visi_vert_inds.append(fv[2]) visi_vert_inds = set(visi_vert_inds) # filter out exempt version visi_vert_inds = list(set(visi_vert_inds).difference(exempt_vert_list)) visi_vert_inds_m = [] for i in visi_vert_inds: xy = cam_para.project(verts[i]) x = int(round(xy[1])) y = int(round(xy[0])) if x < 0 or y < 0 or x >= 448 or y >= 448: continue if np.absolute(proj_depth[x, y] - verts[i, 2]) < 0.01: visi_vert_inds_m.append(i) for i in visi_vert_inds_m: xy = cam_para.project(verts[i]) x = int(round(xy[1])) y = int(round(xy[0])) depth = proj_depth[x, y] + pred_depth[x, y] #print(depth, verts[i]) if depth > 8.: continue verts[i][2] = depth deformed_mesh = make_trimesh(verts, faces) om.write_mesh("./eval_data/%s_set/pred_save/s_%03d.obj" % \ (opt.set, test_num), deformed_mesh)
def write(self, fname): openmesh.write_mesh(fname, self.mesh) print("Wrote Mesh to", fname)
if p0[2] < box[4] and p1[2] < box[4]: continue if p0[0] > box[1] and p1[0] > box[1]: continue if p0[1] > box[3] and p1[1] > box[3]: continue if p0[2] > box[5] and p1[2] > box[5]: continue # both inside if p0[0] > box[0] and p0[0] < box[1] and p0[1] > box[2] and p0[1] < box[3] and p0[2] > box[4] and p0[2] < box[5]: if p1[0] > box[0] and p1[0] < box[1] and p1[1] > box[2] and p1[1] < box[3] and p1[2] > box[4] and p1[2] < box[5]: make_mesh(mesh, p0, p1, p2=[1.0, 0.1, 1.0], r=frame_r*0.5, n=6) continue if False: p0[0] = box[0] if p0[0] < box[0] else p0[0] p0[0] = box[1] if p0[0] > box[1] else p0[0] p0[1] = box[2] if p0[1] < box[2] else p0[1] p0[1] = box[3] if p0[1] > box[3] else p0[1] p0[2] = box[4] if p0[2] < box[4] else p0[2] p0[2] = box[5] if p0[2] > box[5] else p0[2] p1[0] = box[0] if p1[0] < box[0] else p1[0] p1[0] = box[1] if p1[0] > box[1] else p1[0] p1[1] = box[2] if p1[1] < box[2] else p1[1] p1[1] = box[3] if p1[1] > box[3] else p1[1] p1[2] = box[4] if p1[2] < box[4] else p1[2] p1[2] = box[5] if p1[2] > box[5] else p1[2] make_mesh(mesh, p0, p1, p2=[1.0, 0.1, 1.0], r=frame_r*0.5, n=6) # output final buble box om.write_mesh("bubble_cut3.obj", mesh)
def test_teapot(): # load teapot and sphere reference = read_and_process_mesh( "example_data/pointclouds/teapot_mesh.obj", trans=ch.array([0, 0, 0]), rotation=ch.array([np.pi, 0, 0])) target = read_and_process_mesh( "example_data/pointclouds/sphere_normal_2K_mesh.obj", trans=ch.array([0, 0, 0]), rotation=ch.array([0, 0, 0])) # reference V_ref = ch.array(reference.v) vc_ref = ch.array(reference.vc) A_ref = LambertianPointLight(v=V_ref, f=reference.f, num_verts=len( V_ref), light_pos=ch.array([-1000, -1000, -1000]), vc=vc_ref, light_color=ch.array([0.9, 0, 0])) +\ LambertianPointLight(v=V_ref, f=reference.f, num_verts=len( V_ref), light_pos=ch.array([1000, -1000, -1000]), vc=vc_ref, light_color=ch.array([0.0, 0.9, 0])) +\ LambertianPointLight(v=V_ref, f=reference.f, num_verts=len( V_ref), light_pos=ch.array([-1000, 1000, -1000]), vc=vc_ref, light_color=ch.array([0.0, 0.0, 0.9])) U_ref = ProjectPoints(v=V_ref, f=[w, w], c=[w / 2., h / 2.], k=ch.zeros(5), t=ch.zeros(3), rt=ch.zeros(3)) f_ref = ColoredRenderer(vc=A_ref, camera=U_ref, f=reference.f, bgcolor=[1.0, 1.0, 1.0], frustum={ 'width': w, 'height': h, 'near': 1, 'far': 20 }) # target V_tgt = ch.array(target.v) vc_tgt = ch.array(target.vc) A_tgt = LambertianPointLight(v=V_tgt, f=target.f, num_verts=len( V_tgt), light_pos=ch.array([-1000, -1000, -1000]), vc=vc_tgt, light_color=ch.array([0.9, 0, 0])) +\ LambertianPointLight(v=V_tgt, f=target.f, num_verts=len( V_tgt), light_pos=ch.array([1000, -1000, -1000]), vc=vc_tgt, light_color=ch.array([0.0, 0.9, 0])) +\ LambertianPointLight(v=V_tgt, f=target.f, num_verts=len( V_tgt), light_pos=ch.array([-1000, 1000, -1000]), vc=vc_tgt, light_color=ch.array([0.0, 0.0, 0.9])) U_tgt = ProjectPoints(v=V_tgt, f=[w, w], c=[w / 2., h / 2.], k=ch.zeros(5), t=ch.zeros(3), rt=ch.zeros(3)) f_tgt = ColoredRenderer(vc=A_tgt, camera=U_tgt, f=target.f, bgcolor=[1.0, 1.0, 1.0], frustum={ 'width': w, 'height': h, 'near': 1, 'far': 20 }) # offset = ch.zeros(V_tgt.shape) translation, rotation = ch.array([0, 0, 6]), ch.zeros(3) f_tgt.v = translation + V_tgt.dot(Rodrigues(rotation)) f_ref.v = translation + V_ref.dot(Rodrigues(rotation)) op_mesh_target = om.read_trimesh( "example_data/pointclouds/sphere_normal_2K_mesh.obj") n_rotations = 144 # camera positions for index in range(n_rotations): rotation[:] = np.random.rand(3) * np.pi * 2 np.save(os.path.join(save_dir, "rot_v{:03d}".format(index)), rotation) img_ref = f_ref.r Image.fromarray((img_ref * 255).astype(np.uint8)).save( os.path.join(save_dir, "reference_v{:03d}.png".format(index))) img_tgt = f_tgt.r Image.fromarray((img_tgt * 255).astype(np.uint8)).save( os.path.join(save_dir, "target_v{:03d}.png".format(index))) E_raw = f_tgt - img_ref # E_pyr = gaussian_pyramid(E_raw, n_levels=6, normalization='size') free_variables = [V_tgt] # dogleg # Newton-CG # SLSQP # BFGS # trust-ncg method = "trust-ncg" maxiter = 30 ch.minimize({'pyr': E_raw}, x0=free_variables, method=method, options=dict(maxiter=30), callback=create_callback(f_tgt, step=index * maxiter)) ch.minimize({'pyr': E_raw}, x0=free_variables, method=method, options=dict(maxiter=30), callback=create_callback(f_tgt, step=index * maxiter)) # is not the same? target.v = f_tgt.v.r.copy() # save mesh # mesh = pymesh.form_mesh(f_tgt.v.r, f_tgt.f) # pymesh.save_mesh(os.path.join( # save_dir, "target_v{:03d}.obj".format(index)), mesh) point_array = op_mesh_target.points() point_array[:] = target.v np.copyto(op_mesh_target.points(), f_tgt.v.r) om.write_mesh( os.path.join(save_dir, "target_v{:03d}.obj".format(index)), op_mesh_target)
def test_write_triangle_vertex_integer_color(self): self.mesh.request_vertex_colors() options = openmesh.Options() options += openmesh.Options.VertexColor options += openmesh.Options.ColorFloat filename = "triangle-minimal-ColorsPerVertex.om" # Generate data v1 = self.mesh.add_vertex(openmesh.Vec3d(1.0, 0.0, 0.0)) v2 = self.mesh.add_vertex(openmesh.Vec3d(0.0, 1.0, 0.0)) v3 = self.mesh.add_vertex(openmesh.Vec3d(0.0, 0.0, 1.0)) self.mesh.add_face(v1, v2, v3) c1 = openmesh.Vec4f(0.00, 0.00, 0.50, 1.00) c2 = openmesh.Vec4f(0.25, 0.00, 0.00, 1.00) c3 = openmesh.Vec4f(0.00, 0.75, 0.00, 1.00) self.mesh.set_color(v1, c1) self.mesh.set_color(v2, c2) self.mesh.set_color(v3, c3) # Save ok = openmesh.write_mesh(self.mesh, filename, options) self.assertTrue(ok) self.mesh.release_vertex_colors() # Load cmpMesh = openmesh.TriMesh() cmpMesh.request_vertex_colors() ok = openmesh.read_mesh(cmpMesh, filename, options) self.assertTrue(ok) self.assertTrue(cmpMesh.has_vertex_colors()) # Compare self.assertEqual(self.mesh.n_vertices(), 3) self.assertEqual(self.mesh.n_edges(), 3) self.assertEqual(self.mesh.n_faces(), 1) self.assertEqual(cmpMesh.point(v1), openmesh.Vec3d(1.0, 0.0, 0.0)) self.assertEqual(cmpMesh.point(v2), openmesh.Vec3d(0.0, 1.0, 0.0)) self.assertEqual(cmpMesh.point(v3), openmesh.Vec3d(0.0, 0.0, 1.0)) self.assertAlmostEqual(cmpMesh.color(v1)[0], c1[0], 2) self.assertAlmostEqual(cmpMesh.color(v1)[1], c1[1], 2) self.assertAlmostEqual(cmpMesh.color(v1)[2], c1[2], 2) self.assertAlmostEqual(cmpMesh.color(v1)[3], c1[3], 2) self.assertAlmostEqual(cmpMesh.color(v2)[0], c2[0], 2) self.assertAlmostEqual(cmpMesh.color(v2)[1], c2[1], 2) self.assertAlmostEqual(cmpMesh.color(v2)[2], c2[2], 2) self.assertAlmostEqual(cmpMesh.color(v2)[3], c2[3], 2) self.assertAlmostEqual(cmpMesh.color(v3)[0], c3[0], 2) self.assertAlmostEqual(cmpMesh.color(v3)[1], c3[1], 2) self.assertAlmostEqual(cmpMesh.color(v3)[2], c3[2], 2) self.assertAlmostEqual(cmpMesh.color(v3)[3], c3[3], 2) # Clean up cmpMesh.release_vertex_colors() os.remove(filename)
def load(subdiv=2): """ generates an sphere mesh representing a smaller brain mesh, and embeds random patterns drawn from a distribution, creating data for a basic discrimination task. :param subdiv: # subdivisions for the recursive generation of mesh. More subdivisions lead to a more complex mesh. :return: vertices, faces and adjacency matrix for the mesh. """ # ----------------------------------------------------------------------------- # Settings scale = 1 # ----------------------------------------------------------------------------- # Functions middle_point_cache = {} def vertex(x, y, z): """ Return vertex coordinates fixed to the unit sphere """ length = sqrt(x**2 + y**2 + z**2) return [(i * scale) / length for i in (x, y, z)] def middle_point(point_1, point_2): """ Find a middle point and project to the unit sphere """ # We check if we have already cut this edge first # to avoid duplicated verts smaller_index = min(point_1, point_2) greater_index = max(point_1, point_2) key = '{0}-{1}'.format(smaller_index, greater_index) if key in middle_point_cache: return middle_point_cache[key] # If it's not in cache, then we can cut it vert_1 = verts[point_1] vert_2 = verts[point_2] middle = [sum(i) / 2 for i in zip(vert_1, vert_2)] verts.append(vertex(*middle)) index = len(verts) - 1 middle_point_cache[key] = index return index # ----------------------------------------------------------------------------- # Make the base icosahedron # Golden ratio PHI = (1 + sqrt(5)) / 2 verts = [ vertex(-1, PHI, 0), vertex(1, PHI, 0), vertex(-1, -PHI, 0), vertex(1, -PHI, 0), vertex(0, -1, PHI), vertex(0, 1, PHI), vertex(0, -1, -PHI), vertex(0, 1, -PHI), vertex(PHI, 0, -1), vertex(PHI, 0, 1), vertex(-PHI, 0, -1), vertex(-PHI, 0, 1), ] faces = [ # 5 faces around point 0 [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], # Adjacent faces [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], # 5 faces around 3 [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], # Adjacent faces [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1], ] # ----------------------------------------------------------------------------- # Subdivisions for i in range(subdiv): faces_subdiv = [] for tri in faces: v1 = middle_point(tri[0], tri[1]) v2 = middle_point(tri[1], tri[2]) v3 = middle_point(tri[2], tri[0]) faces_subdiv.append([tri[0], v1, v3]) faces_subdiv.append([tri[1], v2, v1]) faces_subdiv.append([tri[2], v3, v2]) faces_subdiv.append([v1, v2, v3]) faces = faces_subdiv mesh = om.TriMesh() vlist = [] for i in verts: vlist.append(mesh.add_vertex(i)) flist = [] for i in faces: flist.append(mesh.add_face(vlist[i[0]], vlist[i[1]], vlist[i[2]])) om.write_mesh('../data/small_sphere.off', mesh) adj_mtx, _, _ = mesh_traversal.create_adj_mtx(np.array(verts), np.array(faces), is_sparse=True) return verts, faces, adj_mtx
def write_off(self, mesh, path): return openmesh.write_mesh(mesh, path)
def save_mesh(self, fp, x): x = x * self.std + self.mean om.write_mesh(fp, om.TriMesh(x.numpy(), self.template_face))