def __init__(self, objpath, handpkg, gdb): self.objtrimesh=trimesh.load_mesh(objpath) self.objcom = self.objtrimesh.center_mass self.objtrimeshconv=self.objtrimesh.convex_hull # oc means object convex self.ocfacets, self.ocfacetnormals = self.objtrimeshconv.facets_over(.9999) # for dbaccess self.dbobjname = os.path.splitext(os.path.basename(objpath))[0] # use two bulletworld, one for the ray, the other for the tabletop self.bulletworldray = BulletWorld() self.bulletworldhp = BulletWorld() # plane to remove hand self.planebullnode = cd.genCollisionPlane(offset=0) self.bulletworldhp.attachRigidBody(self.planebullnode) self.handpkg = handpkg self.handname = handpkg.getHandName() self.hand = handpkg.newHandNM(hndcolor=[0,1,0,.1]) # self.rtq85hnd = rtq85nm.Rtq85NM(hndcolor=[1, 0, 0, .1]) # for dbsave # each tpsmat4 corresponds to a set of tpsgripcontacts/tpsgripnormals/tpsgripjawwidth list self.tpsmat4s = None self.tpsgripcontacts = None self.tpsgripnormals = None self.tpsgripjawwidth = None # for ocFacetShow self.counter = 0 self.gdb = gdb self.loadFreeAirGrip()
def __init__(self, objpath, robot, handpkg, gdb, armname): self.objtrimesh=trimesh.load_mesh(objpath) # for dbaccess self.dbobjname = os.path.splitext(os.path.basename(objpath))[0] # regg = regrip graph self.regg = nx.Graph() self.gdb = gdb self.robot = robot self.handpkg = handpkg # load retraction distances self.rethandx, self.retworldz, self.retworlda, self.worldz = self.gdb.loadIKRet() # worlda is default for the general grasps on table top # for assembly at start and goal, worlda is computed by assembly planner self.worlda = Vec3(0,0,1) self.globalgripids = [] self.fttpsids = [] self.nfttps = 0 self.gnodesplotpos = {} self.gdb = gdb self.robot = robot self.handpkg = handpkg self.__loadGripsToBuildGraph(armname)
def setUp(self): ray_filename = os.path.join(SCRIPT_DIR, 'ray_data.json') with open(ray_filename, 'r') as f_obj: data = json.load(f_obj) self.meshes = [trimesh.load_mesh(location(f)) for f in data['filenames']] self.rays = data['rays'] self.truth = data['truth']
def _convertFormat(self): mesh = trimesh.load_mesh(self.inputname) if mesh.is_watertight: self.inputname = "temporary{:d}.off".format(int(time.time())) mesh.export(file_obj=self.inputname, file_type="off") else: raise SystemError("There is a hole in the mesh. Aborting meshing...")
def transform_converted_matlab_meshes(mesh_path): mesh = load_mesh(mesh_path) roty = get_rot_y( -np.pi/2) rotz = get_rot_z( -np.pi/2) t = np.dot( rotz, roty) mesh.apply_transform(t) return mesh
def load_model(self, path, postprocess = None): self.scene = SceneStruct( meshes = [] ) record = spio.loadmat(exemplar_annotation_root + path + '.mat', struct_as_record=True) objects = record['record']['objects'][0,0] classes = objects['class'][0] for i, x in enumerate(classes): if x == 'car': car = objects[0,i] if car['viewpoint'].shape == (1,1): viewpoint = car['viewpoint'] azimuth = viewpoint['azimuth'][0,0][0,0] elevation = viewpoint['elevation'][0,0][0,0] distance = viewpoint['distance'][0,0][0,0] px = viewpoint['px'][0,0][0,0] py = viewpoint['py'][0,0][0,0] yaw = viewpoint['theta'][0,0][0,0] focal = 3000 cad_idx = car['cad_index'][0,0]-1 print 'loading mesh car%d_t.stl' % cad_idx far = 100 near = 0.001 self.near = near self.far = far r = viewport_size_x - px l = -px t = viewport_size_y - py b = -py self.perspMat = np.array([focal, 0, 0, 0, 0, -focal, 0, 0, -px, -py, near+far, -1, 0, 0, near*far, 0]) ###self.perspMat = np.array([focal, 0, 0, 0, 0, -focal, 0, 0, -px, -height/2, near+far, -1, 0, 0, near*far, 0]) mesh = load_mesh(cad_transformed_root + 'car%d_t.stl' % cad_idx) print 'Done' e = elevation*np.pi/180 a = azimuth*np.pi/180 d = distance C = np.zeros((3,1)) C[0] = 0 # d*np.cos(e)*np.sin(a) C[2] = -d # -d*np.cos(e)*np.cos(a) C[1] = 0 # -d*np.sin(e) roty = get_rot_y(-(azimuth-90)*np.pi/180) rotx = get_rot_x( elevation*np.pi/180) rotz = get_rot_z( yaw*np.pi/180) mesh.apply_transform( np.dot(rotx, roty) ) mesh.apply_translation(C) mesh.apply_transform(rotz) self.scene.meshes.append(mesh) self.bb_min = mesh.bounds[0,:] print self.bb_min self.bb_max = mesh.bounds[1,:] print self.bb_max self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] print self.scene_center for index, mesh in enumerate(self.scene.meshes): print 'preparing buffers' self.prepare_gl_buffers(mesh) print '%d done' % index
def setUp(self): # inertia numbers pulled from solidworks self.truth = json.load(open('mass_properties.json', 'r')) self.meshes = dict() for data in self.truth: filename = data['filename'] location = os.path.abspath(os.path.join(TEST_DIR, filename)) self.meshes[filename] = trimesh.load_mesh(location)
def setUp(self): meshes = deque() for filename in os.listdir(TEST_DIR): log.info('Attempting to load %s', filename) location = os.path.abspath(os.path.join(TEST_DIR, filename)) meshes.append(trimesh.load_mesh(location)) meshes[-1].metadata['filename'] = filename self.meshes = list(meshes)
def setUp(self): # inertia numbers pulled from solidworks self.truth = g.data['mass_properties'] self.meshes = dict() for data in self.truth: filename = data['filename'] location = os.path.abspath(os.path.join(g.dir_models, filename)) self.meshes[filename] = trimesh.load_mesh(location)
def genAvailableFAGsSgl(base, basepath, baseMat4, objpath, objMat4, gdb, handpkg): """ find the collision freeairgrips of objpath without considering rotation :param base: panda base :param basepath: the path of base object :param objpath: the path of obj object, the object to be assembled :param baseMat4, objMat4: all in world coordinates, not relative :param gdb: grasp db :param handpkg: hand package :return: [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair] author: weiwei date: 20170307 """ bulletworld = BulletWorld() robothand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1]) basetrimesh = trimesh.load_mesh(basepath) basenp = pg.packpandanp(basetrimesh.vertices, basetrimesh.face_normals, basetrimesh.faces) basenp.setMat(baseMat4) basebullnode = cd.genCollisionMeshNp(basenp, base.render) bulletworld.attachRigidBody(basebullnode) dbobjname = os.path.splitext(os.path.basename(objpath))[0] objfag = F*g(gdb, dbobjname, handpkg) assgripcontacts = [] assgripnormals = [] assgriprotmat4s = [] assgripjawwidth = [] assgripidfreeair = [] for i, rotmat in enumerate(objfag.freegriprotmats): assgrotmat = rotmat*objMat4 robothand.setMat(assgrotmat) # detect the collisions when hand is open! robothand.setJawwidth(robothand.jawwidthopen) hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp) result0 = bulletworld.contactTest(hndbullnode) robothand.setJawwidth(objfag.freegripjawwidth[i]) hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp) result1 = bulletworld.contactTest(hndbullnode) if (not result0.getNumContacts()) and (not result1.getNumContacts()): cct0 = objMat4.xformPoint(objfag.freegripcontacts[i][0]) cct1 = objMat4.xformPoint(objfag.freegripcontacts[i][1]) cctn0 = objMat4.xformPoint(objfag.freegripnormals[i][0]) cctn1 = objMat4.xformPoint(objfag.freegripnormals[i][1]) assgripcontacts.append([cct0, cct1]) assgripnormals.append([cctn0, cctn1]) assgriprotmat4s.append(assgrotmat) assgripjawwidth.append(objfag.freegripjawwidth[i]) assgripidfreeair.append(objfag.freegripids[i]) return [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]
def loadSerialized(self, filename, ompath): self.objtrimesh=trimesh.load_mesh(ompath) try: self.facets, self.facetnormals, self.facetcolorarray, self.objsamplepnts, \ self.objsamplenrmls, self.objsamplepnts_ref, self.objsamplenrmls_ref, \ self.objsamplepnts_refcls, self.objsamplenrmls_refcls = \ pickle.load(open(filename, mode="rb")) except: print str(sys.exc_info()[0])+" cannot load tmpcp.pickle" raise
def __init__(self, objpath, gdb, handpkg, base): """ initialization :param objpath: path of the object :param base: for the loadFreeAirGrip --> genHandPairs functions (for collision detection) author: weiwei date: 20161215, tsukuba """ self.handpkg = handpkg self.handname = handpkg.getHandName() self.hand0 = handpkg.newHandNM(hndcolor=[1,0,0,.1]) self.hand1 = handpkg.newHandNM(hndcolor=[0,0,1,.1]) self.objtrimesh = trimesh.load_mesh(objpath) self.objnp = pg.packpandanp(self.objtrimesh.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces) self.dbobjname = os.path.splitext(os.path.basename(objpath))[0] # mat4list is nested list, floatingposemat4 is list (the flat version of mat4lsit), they are essentially the same self.mat4list = [] self.floatingposemat4 = [] # gridsfloatingposemat4s is self.floatingposemat4 translated to different grids self.gridsfloatingposemat4s = [] self.icos = None self.floatinggripids = [] self.floatinggripmat4s = [] self.floatinggripcontacts = [] self.floatinggripnormals = [] self.floatinggripjawwidth = [] self.floatinggripidfreeair = [] self.bulletworld = BulletWorld() self.handpairList = [] self.gdb = gdb self.__loadFreeAirGrip(base) # for IK self.floatinggripikfeas_rgt = [] self.floatinggripikfeas_handx_rgt = [] self.floatinggripikfeas_lft = [] self.floatinggripikfeas_handx_lft = [] # for ik-feasible pairs self.floatinggrippairsids = [] self.floatinggrippairshndmat4s = [] self.floatinggrippairscontacts = [] self.floatinggrippairsnormals = [] self.floatinggrippairsjawwidths = [] self.floatinggrippairsidfreeairs = [] self.__genPandaRotmat4()
def loadMeshFromFile(self,filename,objname,initpos = (0.,0.,0.),initvel = (0.,0.,0.), \ initquat = (1.,0.,0.,0.), scale = 1., **kwargs): if not os.path.isfile(filename): raise IOError(filename + ' not found') mesh = trimesh.load_mesh(filename) #if not mesh.is_watertight: raise Exception('Only watertight meshes allowed! ' + filename) mesh.vertices -= mesh.center_mass mesh.vertices *= scale pem = PEMesh(self,objname,mesh,initpos,initvel,initquat,**kwargs) self._objs[objname] = pem return pem
def test_contains(self): mesh = trimesh.load_mesh(location('unit_cube.STL')) scale = 1+(trimesh.constants.tol.merge*2) test_on = mesh.contains(mesh.vertices) test_in = mesh.contains(mesh.vertices * (1.0/scale)) test_out = mesh.contains(mesh.vertices * scale) #assert test_on.all() assert test_in.all() assert not test_out.any()
def main(source, dest=None): debug = False if dest: build_dataset(source, dest) return # Debug mode build_panoramic_view_and_save(source, '.') import trimesh mesh = trimesh.load_mesh(source) mesh.show()
def _load_object(self, i): mesh_path = self._object_paths[i] mesh = trimesh.load_mesh(mesh_path) # V-REP encodes the object centroid as the literal center of the object, # so we need to make sure the points are centered the same way center = lib.utils.calc_mesh_centroid(mesh, center_type='vrep') mesh.vertices -= center mesh.vertices /= 100 # G3DB meshes are in cm, convert to meter mesh_file = self.to_mesh_tempfile(mesh) return mesh, mesh_file
def __getitem__(self, i): name = os.path.basename(self._object_paths[i]) mesh = trimesh.load_mesh(self._object_paths[i]) # mesh.vertices *= 1.75 mesh.vertices *= 1.5 mesh.vertices -= mesh.center_mass mesh_file = self.to_mesh_tempfile(mesh) mass = 1.0 center_mass = mesh.center_mass inertia = np.eye(3) * 1e-3 return Mesh(mesh_file, name, mass, center_mass, inertia)
def setUp(self): meshes = deque() for filename in os.listdir(TEST_DIR): ext = os.path.splitext(filename)[-1][1:].lower() if not ext in trimesh.available_formats(): continue log.info('Attempting to load %s', filename) location = os.path.abspath(os.path.join(TEST_DIR, filename)) meshes.append(trimesh.load_mesh(location)) meshes[-1].metadata['filename'] = filename self.meshes = list(meshes)
def setUp(self): # inertia numbers pulled from solidworks mass_filename = os.path.join(SCRIPT_DIR, 'mass_properties.json') with open(mass_filename, 'r') as f_obj: self.truth = json.load(f_obj) self.meshes = dict() for data in self.truth: filename = data['filename'] location = os.path.abspath(os.path.join(TEST_DIR, filename)) self.meshes[filename] = trimesh.load_mesh(location)
def load(self, path): try: import trimesh except: log.msg('trimesh not available') # load a file by name or from a buffer l = trimesh.load_mesh(path) if isinstance(l, trimesh.Trimesh): self.mesh = l else: log.msg('Unable to load mesh, multiple files loaded?')
def __init__(self, objpath0, objpath1): """ load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613 """ self.objtrimesh0 = trimesh.load_mesh(objpath0) self.objnp0 = pg.packpandanp_fn(self.objtrimesh0.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces) self.objtrimesh1 = trimesh.load_mesh(objpath1) self.objnp1 = pg.packpandanp_fn(self.objtrimesh1.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces) self.__floatingposemat40 = [] self.__floatingposemat41 = []
def setUp(self): meshes = deque() for filename in os.listdir(TEST_DIR): ext = os.path.splitext(filename)[-1][1:].lower() if not ext in trimesh.available_formats(): continue log.info('Attempting to load %s', filename) location = os.path.abspath(os.path.join(TEST_DIR, filename)) meshes.append(trimesh.load_mesh(location)) meshes[-1].metadata['filename'] = filename self.meshes = list(meshes)
def from_file(self, filename: str, name: Optional[str] = None, color: Union[str, Sequence[Union[int, float]]] = (1, 1, 1, .1), import_kwargs: Dict = {}, **init_kwargs) -> 'Volume': """ Load volume from file containing vertices and faces. For OBJ and STL files this function requires the optional library. Parameters ---------- filename : str File to load from. import_kwargs Keyword arguments passed to importer: - ``json.load`` for JSON file - ``trimesh.load_mesh`` for OBJ and STL files **init_kwargs Keyword arguments passed to navis.Volume upon initialization. Returns ------- navis.Volume """ if not os.path.isfile(filename): raise ValueError('File not found.') f, ext = os.path.splitext(filename) if ext == '.json': return self.from_json(filename=filename, name=name, color=color, import_kwargs=import_kwargs, **init_kwargs) try: import trimesh except ImportError: raise ImportError('Unable to import: trimesh missing - please ' 'install: "pip install trimesh"') except BaseException: raise tm = trimesh.load_mesh(filename, **import_kwargs) return self.from_object(tm, name=name, color=color, **init_kwargs)
def fullCurvatureDescriptorValue(specimen, dist=0.5, output_filename=None): mesh = trimesh.load_mesh(specimen['filename'], process=False) ariadne = ariaDne(mesh, dist=dist) if output_filename: values = np.hstack((ariadne['localDNE'], np.array([0, 0.0008]))) colors = trimesh.visual.interpolate(np.log(1e-6 + values), 'jet')[:-2] mesh_data = get_mesh_data(specimen['filename']) mesh_data[0]['vertex_colors'] = colors render_to_file(output_filename, mesh_data) return ariadne
def display_last_timestep(with_light=False, with_masses=False): last_mesh = sorted(glob.glob('output/mesh_*.obj'))[-1] mesh = trimesh.load_mesh(last_mesh) if with_light: last_light = sorted(glob.glob('output/light_*.pkl'))[-1] with open(last_light, 'rb') as fd: light = pickle.load(fd) mesh.visual.vertex_colors = trimesh.visual.interpolate(light / max(light)) if with_masses: plot_mass() return mesh.show() return mesh.show()
def export_meshes_to_run2D_pkl(in_folder='/Users/amirrahimi/src/3Dshapes/car_train_colored/transformed/', skip_to=None): skip = True if skip_to is None: skip = False for x in os.listdir(in_folder): if x == skip_to: skip = False if x.endswith('stl') and not skip: print x mesh = load_mesh(in_folder + x) run2D = mesh_to_voxelized_run2D(mesh, max_dim = 200) with open( in_folder + x[:-3] + 'pkl', 'wb') as f: pickle.dump(run2D, f, -1)
def add_wall(scene, house_id, room_id, bbox): # read wall mesh path_root = f"/shared/data/suncg/room/{house_id}/" floor_id = f"{room_id}f.obj" wall_id = f"{room_id}w.obj" ceiling_id = f"{room_id}c.obj" T = -(np.array(bbox["min"]) * 0.5 + np.array(bbox["max"]) * 0.5 - np.array(room_size_cap) * 1.5 * 0.5) orient = 0 r = R.from_euler("y", orient, degrees=True) # .cpu(), degrees=True) Rotation = r.as_matrix() Z = [1, 1, 1] transform = transforms3d.affines.compose(T, Rotation, Z, S=None) floor_file = osp.join(path_root, floor_id) floor_mesh = trimesh.load_mesh(floor_file) wall_file = osp.join(path_root, wall_id) wall_mesh = trimesh.load_mesh(wall_file) # transform the wall wall_mesh.apply_transform(transform) scene.add_geometry(wall_mesh) for i in scene.geometry.items(): bbox_dic[i[0]] = i[1].bounds floor_mesh.apply_transform(transform) scene.add_geometry(floor_mesh) ceiling_file = osp.join(path_root, ceiling_id) if os.path.isfile(ceiling_file): ceiling_mesh = trimesh.load_mesh(ceiling_file) ceiling_mesh.apply_transform(transform) scene.add_geometry(ceiling_mesh) return scene, bbox_dic
def __init__(self, base, objpath1, objpath2, nobj=1, ntimes=1): self.base = base self.nobj = nobj self.ntimes = ntimes self.poscount = 1 self.objnodepath = None self.workcell = None # for dbaccess self.dbobjname = os.path.splitext(os.path.basename(objpath1))[0] print self.dbobjname self.smiley = trimesh.load_mesh(objpath1) self.smileyCount = 0 self.lasttime0 = 0 self.lasttime0rot = 0 self.laststablepos = 0 self.setupODE() self.addGround() self.count = 0 self.stableFlag = 0 self.partlist = [] self.worktrimesh = trimesh.load_mesh(objpath2) self.addworkstl() self.simcontrolstart = time.time() self.interval0 = time.time() self.simdrop = time.time() self.checkcount = 0 self.body = None self.preObj() self.addObj() taskMgr.add(self.updateODE, "UpdateODE")
def __init__(self, cfg): # mesh_paths, # weights_on_models, # num_layers, # layer_size, # layer_center, # gap_between_layers, # only_inplane_rotations, # rotation_axis_range, # rotation_angle_range, # ): meshes = [] unit = cfg.INIT.GRID.MESH_UNIT.lower() if unit == "m": scale = 1. elif unit == "cm": scale = 0.01 elif unit == "mm": scale = 0.001 else: raise ValueError("Wrong mesh unit: {}".format(unit)) for mesh_path in cfg.INIT.GRID.MESH_PATHS: LOG.info("Loading {}".format(mesh_path)) mesh = trimesh.load_mesh(mesh_path) if scale != 1.: mesh.apply_scale(scale) tmpdir = tempfile.mkdtemp() trimesh.exchange.urdf.export_urdf(mesh, tmpdir) prefix = os.path.join(tmpdir, os.path.basename(tmpdir)) urdf_path = prefix + ".urdf" obj_path = prefix + "_convex_piece_0.obj" decimated_mesh = trimesh.load_mesh(obj_path) meshes.append(Mesh(mesh_path, urdf_path, obj_path, np.array(decimated_mesh.vertices))) self._meshes = meshes self._cfg = cfg
def __init__(self, param, g_code): self.data_points = [] self.gc = g_code self.pr = param if self.pr.outline == c.STL_FLAG: self.mesh = trimesh.load_mesh(self.pr.stl_file) self.partCount = 1 # The current part number self.layers = {} """ The dictionary which stores the computed layers. The key is created in
def samplePointsCallback(scene): if scene.new_index != scene.current_index: scene.current_index = scene.new_index mesh = trimesh.load_mesh(scene.sample[scene.current_index]['filename']) scene.delete_geometry("specimen") scene.add_geometry(mesh, "specimen") pointCloud = trimesh.points.PointCloud(getIntersections(mesh)) scene.delete_geometry("samplePoints") scene.add_geometry(pointCloud, "samplePoints") print(scene.current_index) print(scene.sample[scene.current_index])
def loadObjModel(self, ompath): self.objtrimesh=trimesh.load_mesh(ompath) # oversegmentation self.facets, self.facetnormals = self.objtrimesh.facets_over(faceangle=.95, segangle = .95) # self.facets, self.facetnormals = self.objtrimesh.facets_over(faceangle=.95) # conventional approach # self.facets = self.objtrimesh.facets() # self.facetnormals = [] # for i, faces in enumerate(self.objtrimesh.facets()): # facetnormal = np.sum(self.objtrimesh.face_normals[faces], axis=0) # facetnormal = facetnormal/np.linalg.norm(facetnormal) # self.facetnormals.append(facetnormal) self.facetcolorarray = pandageom.randomColorArray(self.facets.shape[0]) self.sampleObjModel()
def get_points(obj_fl): sample_pc = np.zeros((0, 3), dtype=np.float32) mesh_lst = trimesh.load_mesh(obj_fl, process=False) if not isinstance(mesh_lst, list): mesh_lst = [mesh_lst] for mesh in mesh_lst: choice = np.random.randint(mesh.vertices.shape[0], size=1000) sample_pc = np.concatenate((sample_pc, mesh.vertices[choice, ...]), axis=0) #[choice,...] # color = [[255,0,0], [0,255,0], [0,0,255], [255, 0, 255]] color = 255 * np.ones_like(sample_pc, dtype=np.uint8) color[:, 0] = 0 color[:, 1] = 0 return sample_pc, np.asarray(color, dtype=np.uint8)
def __init__(self, cfg, cfgdata): self.mesh = as_mesh(trimesh.load_mesh(cfg.path)) vert_center = 0.5 * (self.mesh.vertices.max(axis=0) + self.mesh.vertices.min(axis=0)) # vert_scale = np.linalg.norm(self.mesh.vertices - vert_center, axis=-1).max() vert_scale = (self.mesh.vertices.max(axis=0) - self.mesh.vertices.min(axis=0)).max() * 0.5 norm_vert = (self.mesh.vertices - vert_center) / vert_scale self.mesh = trimesh.Trimesh(vertices=norm_vert, faces=self.mesh.faces) self.tr_max_sample_points = cfg.tr_max_sample_points self.te_max_sample_points = cfg.te_max_sample_points self.length = int(cfgdata.length) # Default display axis order self.display_axis_order = [0, 1, 2]
def read_3d_obj(fname="lion_data.npy", fname_obj="lion-reference.obj"): if os.path.isfile(fname): return np.load(fname) else: mesh = trimesh.load_mesh(fname_obj) a = np.array(mesh.vertices) x, y, z = -a[:, 0], a[:, 2], a[:, 1] data = np.array(list(zip(x, y, z))) np.save(fname, data) return data
def get_faust_scan_by_id(data_dir, scan_id, part='test', mesh_lib='trimesh'): """Get FAUST scan by its id """ if part == 'test': scans_path = os.path.join(data_dir, 'test/scans/') else: scans_path = os.path.join(data_dir, 'training/scans/') mesh_path = os.path.join(scans_path, 'test_scan_%03d.ply' % scan_id) mesh_scan = trimesh.load_mesh(mesh_path) return mesh_scan
def cd_cat(cat_id, cat_nm, pred_dir, gt_dir, test_lst_f): pred_dict = build_file_dict(pred_dir) sum_cf_loss = 0. count = 0 with open(test_lst_f, "r") as f: test_objs = f.readlines() for obj_id in test_objs: obj_id = obj_id.rstrip('\r\n') if obj_id not in pred_dict: continue elif len(pred_dict[obj_id] ) == 0: #if the predicted mesh do not exists, skip continue src_path = os.path.join(gt_dir, obj_id, "skeleton.h5") verts_batch = np.zeros( (FLAGS.view_num + 1, FLAGS.num_points_gt, 3), dtype=np.float32) pointcloud_h5 = h5py.File(src_path, 'r') pointcloud = pointcloud_h5['skeleton'][:].astype(np.float32) #choice = np.random.randint(pointcloud.shape[0], size=FLAGS.num_points_gt) #verts_batch[0, ...] = pointcloud[choice,...] verts_batch[0, ...] = pointcloud[:FLAGS.num_points_gt, ...] pred_path_lst = pred_dict[obj_id] pred_path_lst = random.sample(pred_path_lst, FLAGS.view_num) for i in range(len(pred_path_lst)): pred_mesh_fl = pred_path_lst[i] mesh1 = trimesh.load_mesh(pred_mesh_fl) num_left = FLAGS.num_points_pred - mesh1.vertices.shape[0] if num_left > 0: samples = np.zeros((0, 3), dtype=np.float32) choice = np.random.randint(mesh1.vertices.shape[0], size=num_left) points = mesh1.vertices[choice, ...] samples = np.append(samples, points, axis=0) verts_batch[i + 1, :FLAGS.num_points_pred] = np.append( samples, mesh1.vertices, axis=0) else: choice = np.arange(FLAGS.num_points_pred) points = mesh1.vertices[choice, ...] verts_batch[i + 1, :FLAGS.num_points_pred] = points avg_cf_loss_val = get_chamfer_distance(verts_batch) sum_cf_loss += avg_cf_loss_val print( str(count) + " ", "cat_id {}, obj_id {}, avg cf:{}".format( cat_id, obj_id, str(avg_cf_loss_val))) count += 1 print("cat_nm:{}, cat_id:{}, avg_cf:{}, count:{}".format( cat_nm, cat_id, sum_cf_loss / count, count)) log_string("cat_nm:{}, cat_id:{}, avg_cf:{}, count:{}".format( cat_nm, cat_id, sum_cf_loss / count, count))
def __init__(self, mesh_file, scaling): # type: (str, np._ArrayLike) -> None import trimesh self.mesh = trimesh.load_mesh(mesh_file) self.num_vertices = np.size(self.mesh.vertices) self.normals = self.mesh.vertex_normals.reshape( -1).tolist() #.flatten() self.faces = self.mesh.faces.reshape(-1).tolist() self.vertices = self.mesh.vertices self.vertices[:, 0] *= scaling[0] self.vertices[:, 1] *= scaling[1] self.vertices[:, 2] *= scaling[2] self.vertices = self.vertices.reshape(-1).tolist()
def create_map_from_obj(fn, count=10000, size=32): mesh = trimesh.load_mesh(fn) nodes, face_index = trimesh.sample.sample_surface_even(mesh, count) min_coordinate = nodes.min() max_coordinate = nodes.max() #normalize nodes nodes = ((nodes - min_coordinate) / (max_coordinate - min_coordinate) / 2 + 0.25) * size np.savetxt("gt_pc.txt", nodes, delimiter=';') return nodes
def fvtostl(self): points = self.points faces = self.decomposition.surface.surface_sampler_data # add vertex and surface to mesh # mesh = om.TriMesh() vertex = [] for p in points: vertex.append(p) vertex_np_array = np.array(vertex) face = [] for f in faces: # for each face for tri in f: # for triangle in face face.append([tri[0], tri[1], tri[2]]) face_np_array = np.array(face) obj = mesh.Mesh(np.zeros(face_np_array.shape[0], dtype=mesh.Mesh.dtype)) for i, f in enumerate(face_np_array): for j in range(3): obj.vectors[i][j] = vertex_np_array[f[j], :] # fn = bertini_real.util.next_filenumber() fileName = os.getcwd().split(os.sep)[-1] obj.save('a' + fileName + '.stl') normmesh = trimesh.load_mesh('a' + fileName + '.stl') normmesh.fix_normals() for facet in normmesh.facets: normmesh.visual.face_colors[facet] = trimesh.visual.random_color() normmesh.show() normmesh.export(file_obj='anorm' + fileName + '.stl', file_type='stl') # fix_normals(normmesh,True) print("Export successfully")
def __getVolume__(self, path): mesh = trimesh.load_mesh(path) extend = max(mesh.extents) volume = mesh.voxelized(round(extend / self.side_len, 3)).matrix suma = max(volume.shape) - np.array(volume.shape) volume = np.pad(volume, max(suma), mode="constant") (x, y, z) = map(float, volume.shape) volume = nd.zoom( volume.astype(float), (self.side_len / x, self.side_len / y, self.side_len / z), order=1, mode='constant', cval=0) volume[np.nonzero(volume)] = 1.0 return torch.FloatTensor(volume)
def test_rps(self): dimension = (1000,3) sphere = trimesh.load_mesh(location('unit_sphere.STL')) rays_ori = np.random.random(dimension) rays_dir = np.tile([0,0,1], (dimension[0], 1)) rays_ori[:,2] = -5 rays = np.column_stack((rays_ori, rays_dir)).reshape((-1,2,3)) # force ray object to allocate tree before timing it tree = sphere.ray.tree tic = time.time() sphere.ray.intersects_id(rays) toc = time.time() rps = dimension[0] / (toc-tic) log.info('Measured %f rays/second', rps)
def __init__(self, objpath, handpkg): """ initialization :param objpath: path of the object author: weiwei date: 20161215, osaka """ self.objtrimesh = trimesh.load_mesh(objpath) self.dbobjname = os.path.splitext(os.path.basename(objpath))[0] self.handpkg = handpkg self.handname = handpkg.getHandName()
def write_objfile(pcaBase, pcaCoeff, mean_sample, ratio, filename, gender): """reconstruction mesh as obj file parameters ---------- pcaBase: eigenvector of covariance matrix num_feature * k pcaCoeff: the coefficient of base space 1 * k mean_sample: average of all samples 1 * num_feature ratio: body height (pca perform on nomalization body height, 1 meters) float (meter) filename: write to file, include path gender : female or male return -------- nn output parameters, results are written into file """ if gender == 'female': mesh = trimesh.load_mesh('./data/input/female/PCA/averHuman.obj', process=False) else: mesh = trimesh.load_mesh('./data/input/male/PCA/averHuman.obj', process=False) vertices_t = mesh.vertices num_vertices, num_dim = vertices_t.shape[0], vertices_t.shape[1] averX = mean_sample.reshape((num_vertices, num_dim), order='F') pcaRecon = np.matmul(pcaCoeff, pcaBase.T) recon_sample = pcaRecon.reshape((num_vertices, num_dim), order='F') recon_points = ratio * (recon_sample + averX) mesh.vertices = recon_points mesh.export(filename)
def loadObjModel(self, ompath, objrotmat, objposmat): self.objtrimesh = trimesh.load_mesh(ompath) #add pos and rot to origin trimensh self.objtrimesh.vertices = np.transpose( np.dot(objrotmat, np.transpose(self.objtrimesh.vertices))) self.objtrimesh.vertices = self.objtrimesh.vertices + objposmat # oversegmentation self.facets, self.facetnormals = self.objtrimesh.facets_over( faceangle=.95, segangle=.95) self.facetcolorarray = pandageom.randomColorArray(self.facets.shape[0]) self.sampleObjModel()
def loadmesh(self, meshfile=None): try: if meshfile is None: meshfile = 'trigrid-mesh.json' meshfile = meshfile[0] self.mesh = trimesh.load_mesh(meshfile) self.mesh.face_attributes['color'] = [ np.random.uniform(0, 1, (3, )) for _ in range(len(self.mesh.faces)) ] print('mesh loaded from {0}, vertices = {1}, faces = {2}'.format( meshfile, self.mesh.vertices.shape[0], self.mesh.faces.shape[0])) except Exception as e: print('loadmesh failed', e)
def test_rps(self): dimension = (1000, 3) sphere = trimesh.load_mesh(location('unit_sphere.STL')) rays_ori = np.random.random(dimension) rays_dir = np.tile([0, 0, 1], (dimension[0], 1)) rays_ori[:, 2] = -5 rays = np.column_stack((rays_ori, rays_dir)).reshape((-1, 2, 3)) # force ray object to allocate tree before timing it tree = sphere.triangles_tree() tic = time.time() sphere.ray.intersects_id(rays) toc = time.time() rps = dimension[0] / (toc - tic) log.info('Measured %f rays/second', rps)
def __init__(self, objpath, handpkg): """ initialization :param objpath: path of the object author: weiwei date: 20161215, osaka """ self.objtrimesh = trimesh.load_mesh(objpath) self.dbobjname = os.path.splitext(os.path.basename(objpath))[0] self.handpkg = handpkg self.handname = handpkg.getHandName()
def do_cut(axis, pos, name, engine='blender', mat=None, fix=False): done = [] print "loading "+name+" ..." m = trimesh.load_mesh(name) m.process() # basic cleanup if mat is not None: m.transform(mat) if fix: m.fix_normals() print "is watertight: ", m.fill_holes() m.process() # basic cleanup # print "... done." bbox = copy.deepcopy(m.bounds) bbox[0][0] -= bbox_eps bbox[0][1] -= bbox_eps bbox[0][2] -= bbox_eps bbox[1][0] += bbox_eps bbox[1][1] += bbox_eps bbox[1][2] += bbox_eps print m.bounds print bbox boxl = [] if axis == 'x': boxl = cutboxes_x(m.bounds, pos) if axis == 'y': boxl = cutboxes_y(m.bounds, pos) if axis == 'z': boxl = cutboxes_z(m.bounds, pos) base,suf = name.rsplit('.', 1) for b in range(len(boxl)): outname=base+"_"+axis+str(b+1)+"."+suf print "cutting "+outname+"..." boxl[b].process() # basic cleanup mcut = m.intersection(boxl[b], engine=engine) mcut.process() if fix: mcut.fix_normals() print "is watertight: ", m.fill_holes() mcut.process() print "saving "+outname+" ..." try: # 1.15.16 syntax open(outname, "wb+").write(trimesh.io.export.export_stl(mcut)) except: # old style trimesh.io.export.export_stl(mcut, open(outname, "wb+")) # print "... done." done.append(outname) return done
def open_mesh(self): """ add a mesh to the pyqt frame """ global mesh, mesh_vol # open file file_info = QtWidgets.QFileDialog.getOpenFileName() print(file_info) file_path = file_info[0] # determine file type and if conversion needed file_dir, file_name = os.path.split(file_path) mesh_name, mesh_type = os.path.splitext(file_name) # convert mesh file type #if ext != ".vtk" or ext != ".VTK": # mesh = meshio.read(file_path) # meshio.write(root + ".vtk", mesh) # mesh = pv.read(head + "/" + root + ".vtk") # need to store elsewhere or delete .vtk file in the future #else: # mesh = pv.read(file_path) # read mesh & transform according to principal axes pre = trimesh.load_mesh(file_path) orient = pre.principal_inertia_transform pre = pre.apply_transform(orient) pre.export('data/' + mesh_name + '_oriented.STL') mesh = pv.read('data/' + mesh_name + '_oriented.STL') # print mesh info print("Mesh Name:", mesh_name) print("Mesh Type:", mesh_type[1:]) # show transformed mesh #self.plotter.add_mesh(mesh, show_edges=True, color="w", opacity=0.6) # reset plotter self.reset_plotter() # find mesh centroid and translate the mesh so that's the origin self.centroid() # show bounding box # self.plotter.add_bounding_box(opacity=0.5, color="y") # mesh volume mesh_vol = float(format(mesh.volume, ".5f")) print("Mesh Volume:", mesh_vol)
def __init__(self, objpath, robot, handpkg, gdb, offset = -55): self.objtrimesh=trimesh.load_mesh(objpath) self.handpkg = handpkg self.handname = handpkg.getHandName() # for dbaccess self.dbobjname = os.path.splitext(os.path.basename(objpath))[0] # regg = regrip graph self.regg = nx.Graph() self.ndiscreterot = 0 self.nplacements = 0 self.globalgripids = [] # for removing the grasps at start and goal self.robothand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1]) # plane to remove hand self.bulletworld = BulletWorld() self.planebullnode = cd.genCollisionPlane(offset = offset) self.bulletworld.attachRigidBody(self.planebullnode) # add tabletop plane model to bulletworld # dont forget offset # this_dir, this_filename = os.path.split(__file__) # ttpath = Filename.fromOsSpecific(os.path.join(os.path.split(this_dir)[0]+os.sep, "grip", "supports", "tabletop.egg")) # self.ttnodepath = NodePath("tabletop") # ttl = loader.loadModel(ttpath) # ttl.instanceTo(self.ttnodepath) self.startnodeids = None self.goalnodeids = None self.shortestpaths = None self.gdb = gdb self.robot = robot # load retraction distances self.rethandx, self.retworldz, self.retworlda, self.worldz = self.gdb.loadIKRet() # worlda is default for the general grasps on table top # for assembly at start and goal, worlda is computed by assembly planner self.worlda = Vec3(0,0,1) # loadfreeairgrip self.__loadFreeAirGrip() self.__loadGripsToBuildGraph()
def genObjmnp(objpath, color = Vec4(1,0,0,1)): """ gen objmnp :param objpath: :return: """ objtrimesh = trimesh.load_mesh(objpath) geom = packpandageom(objtrimesh.vertices, objtrimesh.face_normals, objtrimesh.faces) node = GeomNode('obj') node.addGeom(geom) objmnp = NodePath('obj') objmnp.attachNewNode(node) objmnp.setColor(color) objmnp.setTransparency(TransparencyAttrib.MAlpha) return objmnp
def loadObjModel(self, ompath): self.objtrimesh=trimesh.load_mesh(ompath) # oversegmentation self.facets, self.facetnormals = self.objtrimesh.facets_over(faceangle=.95) self.facetcolorarray = pandageom.randomColorArray(self.facets.shape[0]) self.sampleObjModel() # prepare the model for collision detection self.objgeom = pandageom.packpandageom(self.objtrimesh.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces) self.objmeshbullnode = cd.genCollisionMeshGeom(self.objgeom) self.bulletworld.attachRigidBody(self.objmeshbullnode) # object center self.objcenter = [0,0,0] for pnt in self.objtrimesh.vertices: self.objcenter[0]+=pnt[0] self.objcenter[1]+=pnt[1] self.objcenter[2]+=pnt[2] self.objcenter[0] = self.objcenter[0]/self.objtrimesh.vertices.shape[0] self.objcenter[1] = self.objcenter[1]/self.objtrimesh.vertices.shape[0] self.objcenter[2] = self.objcenter[2]/self.objtrimesh.vertices.shape[0]
def load_model(self, path, obj_idx=0): record = spio.loadmat(exemplar_annotation_root + path + '.mat', struct_as_record=True) objects = record['record']['objects'][0,0] classes = objects['class'][0] cur_obj_idx = -1 mesh = None for i, x in enumerate(classes): if x == 'car': car = objects[0,i] if car['viewpoint'].shape == (1,1): cur_obj_idx = cur_obj_idx + 1 if cur_obj_idx != obj_idx: continue viewpoint = car['viewpoint'] self.azimuth = viewpoint['azimuth'][0,0][0,0] self.elevation = viewpoint['elevation'][0,0][0,0] self.distance = viewpoint['distance'][0,0][0,0] self.px = viewpoint['px'][0,0][0,0] self.py = viewpoint['py'][0,0][0,0] self.yaw = viewpoint['theta'][0,0][0,0] self.focal = 3000 cad_idx = car['cad_index'][0,0]-1 print 'loading mesh car%d_t.stl' % cad_idx far = 100 near = 0.001 px = self.px py = self.py focal = self.focal self.near = near #TODO can do it by computing max/min of mesh Zs self.far = far self.perspMat = np.array([focal, 0, 0, 0, 0, -focal, 0, 0, -px, -py, near+far, -1, 0, 0, near*far, 0]) mesh = load_mesh(cad_transformed_root + 'car%d_t.stl' % cad_idx) apply_transformations( mesh, self.azimuth, self.elevation, self.yaw, self.distance) mesh.export(file_obj='transformed.stl') self.meshes.append(mesh) if mesh is not None: self.prepare_gl_buffers(mesh) else: print 'Error mesh is None!'
def __init__(self, gdb, asspath, handpkg): """ :param asspath: an assembly path, see the definition in the leading text :param gdb: author: weiwei date: 20170227 """ self.handpkg = handpkg self.objTrimeshList = [] self.objFAGList = [] # F*g = free air grip self.objRotmat4List = [] for objpath, rotmat4 in asspath: self.objTrimeshList.append(trimesh.load_mesh(objpath)) curRotmat4 = rotmat4 for prevRotmat4 in self.objRotmat4List[::-1]: curRotmat4 = prevRotmat4*curRotmat4 self.objRotMat4List.append(curRotmat4) dbobjname = os.path.splitext(os.path.basename(objpath))[0] self.objFAGList.append(FreeAirGrip(gdb, dbobjname, self.handpkg.getHandName())) pass
import numpy as np import sys import trimesh # normalize a vertex (to the range 0-255) def normalize(v): return [int(v[0]), int(v[1]), int(v[2])] # XXX if len(sys.argv) < 2: print ("Usage: {0} model_filename\n", sys.argv[0]) exit(0) mesh = trimesh.load_mesh(sys.argv[1]) print len(mesh.vertices) verts = mesh.vertices faces = mesh.faces for v0, v1, v2 in faces: o_face = [normalize(verts[v0]), normalize(verts[v1]), normalize(verts[v2])] for f in o_face: print ("{0},{1},{2},{3}\n", f[0], f[1], f[2], 0xFF) print ("{0},{1},{2},{3}\n", 0xFF, 0xFF, 0xFF, 0xFF)
Take a mesh with multiple bodies, take the convex hull of each body, then combine them back into one mesh. Useful for generating collision models of an object. ''' import sys import trimesh import numpy as np if __name__ == '__main__': # attach to trimesh logs trimesh.util.attach_to_log() # load the mesh from filename # file objects are also supported mesh = trimesh.load_mesh('../models/box.STL') # split the mesh into connected components of the face adjacency graph. # splitting sometimes produces non- watertight meshes # though the splitter will try to repair single quad and # single triangle holes, in our case here we are going to be # taking convex hulls anyway, so there is no reason to not discard # the non- watertight bodies meshes = mesh.split(only_watertight=False) # the convex hull of every component meshes_convex = [i.convex_hull for i in meshes] # combine all components into one mesh convex_combined = np.sum(meshes_convex)
s = ode.Space() cgroup = ode.JointGroup() def callback(args,g1,g2): contacts = ode.collide(g1,g2) world,cgroup = args for c in contacts: c.setBounce(.9) c.setMu(1000) j = ode.ContactJoint(world,cgroup,c) j.attach(g1.getBody(),g2.getBody()) floor = ode.GeomPlane(s, (0,0,1), 0) mesh = trimesh.load_mesh('unit_sphere.stl') mdat = ode.TriMeshData() mdat.build(mesh.vertices,mesh.faces) I = mesh.moment_inertia #print I mass = ode.Mass() mass.setParameters(mesh.volume,0.,0.,0., I[0][0],I[1][1],I[2][2],I[0][1],I[0][2],I[1][2]) b.setMass(mass) g = ode.GeomTriMesh(mdat,s) g.setBody(b) b.setPosition((0,0,2))
''' examples/section.py Slice a mesh into 2D sections, like you would do to write a basic 3D printing driver. ''' import trimesh import numpy as np if __name__ == '__main__': # load the mesh from filename # file objects are also supported mesh = trimesh.load_mesh('../models/featuretype.STL') # we're going to slice the mesh into evenly spaced chunks along z # this takes the (2,3) bounding box and slices it into [minz, maxz] z_extents = mesh.bounds[:,2] # 10 evenly spaced z values, between the extents of the mesh z_levels = np.linspace(*z_extents, num=10) # create an array to hold the section objects sections = [None] * len(z_levels) for i, z in enumerate(z_levels): # this will return a Path3D object, each of which will # have curves in 3D space sections[i] = mesh.section(plane_origin = [0,0,z], plane_normal = [0,0,1])