Example #1
0
def getVolumeFromOFF(path, sideLen=32):
    mesh = trimesh.load(path)
    volume = trimesh.voxel.Voxel(mesh, 0.5).raw
    (x, y, z) = map(float, volume.shape)
    volume = nd.zoom(volume.astype(float), 
                     (sideLen/x, sideLen/y, sideLen/z),
                     order=1, 
                     mode='nearest')
    volume[np.nonzero(volume)] = 1.0
    return volume.astype(np.bool)
Example #2
0
def get_meshes(path='../../../models', cutoff=None):
    """
    Get a list of single- body meshes to test identifiers on.

    Parameters
    ------------
    path:   str, location of models
    cutoff: int, number of meshes to stop loading at

    Returns
    ------------
    meshes: (n,) list of Trimesh objects
    """

    bodies = collections.deque()
    for file_name in os.listdir(path):
        try:
            mesh = trimesh.load(os.path.join(path, file_name))
            split = mesh.split()
            bodies.extend(split)
            if len(split) > 1:
                bodies.append(mesh)
        except BaseException:
            continue

        if cutoff is not None and len(bodies) > cutoff:
            return np.array(bodies)

    for i in range(100):
        cylinder = trimesh.creation.cylinder(
            radius=np.random.random() * 100,
            height=np.random.random() * 1000,
            sections=int(np.clip(np.random.random() * 720,
                                 20,
                                 720)))

        capsule = trimesh.creation.capsule(
            radius=np.random.random() * 100,
            height=np.random.random() * 1000,
            count=np.clip(np.random.random(2) * 720,
                          20,
                          720).astype(int))
        bodies.append(cylinder)
        bodies.append(capsule)
    for i in range(10):
        bodies.append(trimesh.creation.random_soup(
            int(np.clip(np.random.random() * 1000,
                        20,
                        1000))))
    bodies.append(trimesh.creation.icosphere())
    bodies.append(trimesh.creation.uv_sphere())
    bodies.append(trimesh.creation.icosahedron())

    return np.array(bodies)
Example #3
0
def get_2D(count=None):
    """
    Get Path2D objects to test with.

    Parameters
    --------------
    count : int
      Number of 2D drawings to return

    Yields
    --------------
    path : trimesh.path.Path2D
      Drawing from models folder
    """
    # if no path loading return empty list
    if not has_path:
        raise StopIteration

    # all files in the 2D models directory
    listdir = sorted(os.listdir(dir_2D))
    # if count isn't passed return all files
    if count is None:
        count = len(listdir)
    # save resulting loaded paths
    paths = []
    for file_name in listdir:
        # check to see if the file is loadable
        ext = trimesh.util.split_extension(file_name)
        if ext not in trimesh.available_formats():
            continue
        # full path
        location = os.path.join(dir_2D, file_name)
        try:
            paths.append(trimesh.load(location))
        except BaseException as E:
            log.error('failed on: {}'.format(file_name),
                      exc_info=True)
            raise E

        yield paths[-1]

        # if we don't need every path break
        if len(paths) >= count:
            break
Example #4
0
 def setUp(self):
     self.drawings = deque()
     file_list     = os.listdir(TEST_DIR)
     tic           = time_function()
     for filename in file_list:
         file_path = os.path.join(TEST_DIR, filename)
         tic_load = time_function()
         drawing = trimesh.load(file_path)
         toc_load = time_function()
         log.info('loaded %s in %f', filename, toc_load-tic_load)
         drawing.filename = filename
         drawing.process()
         self.drawings.append(drawing)
     toc = time_function()
     log.info('Successfully loaded %i drawings from %i files in %f seconds',
              len(self.drawings),
              len(file_list),
              toc-tic)
     self.drawings = list(self.drawings)
Example #5
0
def get_mesh(file_name, *args, **kwargs):
    """
    Get a mesh from the models directory by name.

    Parameters
    -------------
    file_name : str
      Name of model in /models/
    *args : [str]
      Additional files to load

    Returns
    -----------
    meshes : trimesh.Trimesh or list
      Single mesh or list of meshes from args
    """
    meshes = collections.deque()
    for name in np.append(file_name, args):
        location = os.path.join(dir_models, name)
        log.info('loading mesh from: %s', location)
        meshes.append(trimesh.load(location, **kwargs))
    if len(meshes) == 1:
        return meshes[0]
    return list(meshes)
Example #6
0
#!/usr/bin/env python

import ymero as ymr
import numpy as np
import trimesh, argparse

parser = argparse.ArgumentParser()
parser.add_argument("--mesh", type=str, required=True)
args = parser.parse_args()

ranks  = (1, 1, 1)
domain = (12, 8, 10)

u = ymr.ymero(ranks, domain, dt=0, debug_level=8, log_filename='log')

m = trimesh.load(args.mesh);
mesh = ymr.ParticleVectors.MembraneMesh(m.vertices.tolist(), m.faces.tolist())

rbc  = ymr.ParticleVectors.MembraneVector("rbc", mass=1.0, mesh=mesh)
icrbc = ymr.InitialConditions.Membrane([[6.0, 4.0, 5.0,   1.0, 0.0, 0.0, 0.0]])
u.registerParticleVector(pv=rbc, ic=icrbc)

dumpEvery = 1
ovDump = ymr.Plugins.createDumpParticlesWithMesh('partDump', rbc, dumpEvery, [], 'h5/rbc-')
u.registerPlugins(ovDump)

u.run(2)

# TEST: dump.h5.mesh
# cd dump
# rm -rf h5
Example #7
0
 def setUp(self):
     filename = os.path.join(g.dir_models, 'box.STL')
     mesh = trimesh.load(filename)
     split = mesh.split()
     scene = trimesh.scene.Scene(split)
     self.scene = scene
Example #8
0
    args = parser.parse_args()

    lists = [
        'TShirtNoCoat.obj', 'ShortPants.obj', 'Pants.obj', 'ShirtNoCoat.obj',
        'LongCoat.obj'
    ]

    all_dirs, all_paths = get_dirs_paths(args.input_folder)
    for index in range(len(all_paths)):
        path = all_paths[index]
        for file in os.listdir(path):
            if file in lists:
                class_name = file.replace('.obj', '')
                mesh_path = os.path.join(path, file)
                out_dir = os.path.join(args.output_folder,
                                       class_name + '_' + all_dirs[index])
                if not os.path.isdir(out_dir):
                    os.makedirs(out_dir)

                out_file = os.path.join(out_dir, 'mesh.off')

                mesh = trimesh.load(mesh_path)

                new_verts = mesh.vertices - np.mean(mesh.vertices, axis=0)
                new_verts_sc = new_verts / 0.9748783846
                new_verts_sc = new_verts_sc * 0.5
                new_mesh = trimesh.Trimesh(vertices=new_verts_sc,
                                           faces=mesh.faces)
                new_mesh.export(out_file)
                print("Processed {} {}".format(all_dirs[index], class_name))
    def buildViewPatches(self, use_random_colors):
        ''' Generates view patches. self.viewPatches stores a list of
        viewPatches for each body (starting at body id 1). A viewPatch is a
        list of all 3D vertices of a piece of visual geometry. '''

        self.viewPatches = {}
        self.viewPatchColors = {}

        mock_lcm = DrakeMockLcm()
        mock_lcm_subscriber = Subscriber(lcm=mock_lcm,
                                         channel="DRAKE_VIEWER_LOAD_ROBOT",
                                         lcm_type=lcmt_viewer_load_robot)
        DispatchLoadMessage(self._scene_graph, mock_lcm)
        mock_lcm.HandleSubscriptions(0)
        assert mock_lcm_subscriber.count > 0
        load_robot_msg = mock_lcm_subscriber.message

        # Spawn a random color generator, in case we need to pick
        # random colors for some bodies. Each body will be given
        # a unique color when using this random generator, with
        # each visual element of the body colored the same.
        color = iter(plt.cm.rainbow(np.linspace(0, 1,
                                                load_robot_msg.num_links)))

        for i in range(load_robot_msg.num_links):
            link = load_robot_msg.link[i]

            this_body_patches = []
            this_body_colors = []
            this_color = next(color)

            for j in range(link.num_geom):
                geom = link.geom[j]
                # MultibodyPlant currently sets alpha=0 to make collision
                # geometry "invisible".  Ignore those geometries here.
                if geom.color[3] == 0:
                    continue

                element_local_tf = RigidTransform(
                    RotationMatrix(Quaternion(geom.quaternion)),
                    geom.position)

                if geom.type == geom.BOX:
                    assert geom.num_float_data == 3

                    # Draw a bounding box.
                    patch = np.vstack((
                        geom.float_data[0]/2.*np.array(
                            [-1, -1, 1, 1, -1, -1, 1, 1]),
                        geom.float_data[1]/2.*np.array(
                            [-1, 1, -1, 1, -1, 1, -1, 1]),
                        geom.float_data[2]/2.*np.array(
                            [-1, -1, -1, -1, 1, 1, 1, 1])))

                elif geom.type == geom.SPHERE:
                    assert geom.num_float_data == 1
                    radius = geom.float_data[0]
                    lati, longi = np.meshgrid(np.arange(0., 2.*math.pi, 0.5),
                                              np.arange(0., 2.*math.pi, 0.5))
                    lati = lati.ravel()
                    longi = longi.ravel()
                    patch = np.vstack([
                        np.sin(longi)*np.cos(lati),
                        np.sin(longi)*np.sin(lati),
                        np.cos(lati)])
                    patch *= radius

                elif geom.type == geom.CYLINDER:
                    assert geom.num_float_data == 2
                    radius = geom.float_data[0]
                    length = geom.float_data[1]

                    # In the lcm geometry, cylinders are along +z
                    # https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/matlab/systems/plants/RigidBodyCylinder.m
                    # Two circles: one at bottom, one at top.
                    sample_pts = np.arange(0., 2.*math.pi, 0.25)
                    patch = np.hstack(
                        [np.array([
                            [radius*math.cos(pt),
                             radius*math.sin(pt),
                             -length/2.],
                            [radius*math.cos(pt),
                             radius*math.sin(pt),
                             length/2.]]).T
                         for pt in sample_pts])

                elif geom.type == geom.MESH:
                    # TODO(gizatt): Remove trimesh and shapely dependency when
                    # vertex information is accessible from the SceneGraph
                    # interface.
                    mesh = trimesh.load(geom.string_data)
                    patch = mesh.vertices.T
                    # Apply scaling
                    for i in range(3):
                        patch[i, :] *= geom.float_data[i]

                else:
                    print("UNSUPPORTED GEOMETRY TYPE {} IGNORED".format(
                        geom.type))
                    continue

                patch = np.vstack((patch, np.ones((1, patch.shape[1]))))
                patch = np.dot(element_local_tf.GetAsMatrix4(), patch)

                # Close path if not closed
                if (patch[:, -1] != patch[:, 0]).any():
                    patch = np.hstack((patch, patch[:, 0][np.newaxis].T))

                this_body_patches.append(patch)
                if use_random_colors:
                    this_body_colors.append(this_color)
                else:
                    this_body_colors.append(geom.color)

            self.viewPatches[link.name] = this_body_patches
            self.viewPatchColors[link.name] = this_body_colors
Example #10
0
import trimesh
import numpy as np

#make sure the order of identity points and gt points are same
#for original_model, please keep the identity and pose points in different order

ours_mesh = trimesh.load('ours.obj')
ours_vertices = ours_mesh.vertices
ours_bbox= np.array([[np.max(ours_vertices[:,0]), np.max(ours_vertices[:,1]), np.max(ours_vertices[:,2])], \
                        [np.min(ours_vertices[:,0]), np.min(ours_vertices[:,1]), np.min(ours_vertices[:,2])]])

ours_vertices_align = ours_vertices - (ours_bbox[0] + ours_bbox[1]) / 2

gt_mesh = trimesh.load('gt.obj')
gt_vertices = gt_mesh.vertices
gt_bbox= np.array([[np.max(gt_vertices[:,0]), np.max(gt_vertices[:,1]), np.max(gt_vertices[:,2])], \
                        [np.min(gt_vertices[:,0]), np.min(gt_vertices[:,1]), np.min(gt_vertices[:,2])]])
gt_vertices_align = gt_vertices - (gt_bbox[0] + gt_bbox[1]) / 2

print(np.mean((ours_vertices_align - gt_vertices_align)**2))
Example #11
0
import sys
import numpy as np
import trimesh


if __name__ == '__main__':
    # print logged messages
    trimesh.util.attach_to_log()

    # load a mesh
    mesh  = trimesh.load('../models/featuretype.STL')

    # get a scene object containing the mesh, this is equivalent to:
    # scene = trimesh.scene.Scene(mesh)
    scene = mesh.scene()

    r = trimesh.transformations.rotation_matrix(np.radians(45.0), [0,1,0], 
                                                scene.centroid)    
    for i in range(4):
        trimesh.constants.log.info('Saving image %d', i)
        
        # rotate the camera view
        camera_new = np.dot(scene.transforms.get('camera'), r)
        scene.transforms.update('camera', matrix=camera_new)

        file_name = 'render_' + str(i) + '.png'

        # saving an image requires an opengl context, so if -nw
        # is passed don't save the image
        if not '-nw' in sys.argv:
from shrink_wrap_quad_mesh import *
from build_depth_surface import *
from pyrender_dev import pyrender
import matplotlib.pyplot as plt
import trimesh
import transforms3d

# Params
target = trimesh.load('../models/car_test.stl')
# target = trimesh.load('../models/cars/car_thingi_whole.stl')
# car_thingi_whole
# target = trimesh.load('../models/fuzzybear100kpoly.stl')
# target = trimesh.load('../ModelNet10/dresser/train/dresser_0020.off')
# target = trimesh.load('../ModelNet10/dresser/train/dresser_0020.off')
previewModel = True
previewDepthMap = True
previewDepthSurfaces = True
previewEachSubdivPass = True


def preview_mesh(m):
    scene = pyrender.Scene()
    scene.add(pyrender.Mesh.from_trimesh(m))
    pyrender.Viewer(scene, use_raymond_lighting=True)


target_mesh = pyrender.Mesh.from_trimesh(target)
# print(target.bounds)
# bounding_box = [50.0, 50.0, 50.0]
# bounding_box = [400.0, 200.0, 100.0]
def wall_distance_orient():
    import trimesh
    ROOT = './dataset/'
    level_root = "./dataset/alilevel_oriFix/"
    room_root = "./dataset/room/"
    object_root = "./dataset/object/"
    with open('./dataset/sk_to_ali.json') as f:
        obj_semantic = json.load(f)

    level_dirs = os.listdir(level_root)
    ds = {}
    objMeshCache = {}
    for obj in obj_semantic:
        ds[obj] = []
    for i in range(0, len(level_dirs)):
        dire = level_dirs[i]
        # debug mode...
        # if dire not in ['3c29e2e4-4b96-4124-91b6-00580ba3414d.json']:
        #     continue
        print('(%d/%d) tackle ' % (i + 1, len(level_dirs)) + dire)
        with open(f'./dataset/alilevel_oriFix/{dire}', 'r') as f:
            h = json.load(f)
        for i in range(0, len(h['rooms'])):
            room = h['rooms'][i]
            try:
                shape = processGeo(room_root + '/' + room['origin'],
                                   room['modelId'] + 'f.obj')
            except Exception as e:
                continue
            if len(shape) <= 2:
                continue
            for i in range(len(room['objList'])):
                obji = room['objList'][i]

                if obji['modelId'] not in obj_semantic:
                    continue
                if 'translate' not in obji:
                    continue
                if 'orient' not in obji:
                    continue

                # find the nearest wall;
                p = np.array([obji['translate'][0], obji['translate'][2]])
                shapeEnd = shape[np.arange(1, len(shape)).tolist() + [0]]
                a_square = np.sum((shape - p)**2, axis=1)
                b_square = np.sum((shapeEnd - p)**2, axis=1)
                c_square = np.sum((shape - shapeEnd)**2, axis=1)
                area_double = 0.5 * np.sqrt(4 * a_square * b_square -
                                            (a_square + b_square -
                                             c_square)**2)
                distances = area_double / np.sqrt(c_square)
                _indicesList = []
                wallMinIndices = np.argsort(distances)
                innerProducts = np.sum((shape - p) * (shape - shapeEnd),
                                       axis=1)
                for i in wallMinIndices:
                    if 0 <= innerProducts[i] and innerProducts[i] <= c_square[
                            i]:
                        _indicesList.append(i)
                        if len(_indicesList) == 2:
                            break
                        # wallMinIndex = i
                if len(_indicesList) < 2:
                    continue
                wallMinIndex = _indicesList[0]
                minDistance = distances[wallMinIndex]
                secMinDistance = distances[_indicesList[1]]

                # calculate the wall orient;
                wn = (shape[wallMinIndex] - shapeEnd[wallMinIndex])[[1, 0]]
                wn[1] = -wn[1]

                # ori_prior equals to ori_final - ori_wall;
                ori = obji['orient'] - np.arctan2(wn[0], wn[1])
                while ori > math.pi:
                    ori -= 2 * math.pi
                while ori < -(math.pi):
                    ori += 2 * math.pi

                # calculate the length of this object w.r.t the wall;
                # wd = shapeEnd[wallMinIndex] - shape[wallMinIndex]
                # wallorient = np.arctan2(wd[0], wd[1])
                Ry = trimesh.transformations.rotation_matrix(
                    -np.arctan2(wn[0], wn[1]), yaxis)
                try:
                    if obji['modelId'] in objMeshCache:
                        _mesh = objMeshCache[obji['modelId']]
                    else:
                        print('loading ... ' + obji['modelId'])
                        _mesh = trimesh.load(
                            f'./dataset/object/{obji["modelId"]}/{obji["modelId"]}.obj'
                        )
                        objMeshCache[obji['modelId']] = _mesh
                    # we always take the copy before modifying it;
                    mesh = _mesh.copy()
                    mesh.vertices *= np.array(obji['scale'])
                    mesh.apply_transform(Ry)
                    objWallLength = np.max(mesh.vertices[:, 0]) - np.min(
                        mesh.vertices[:, 0])
                    objWallLength = objWallLength.tolist() / 2
                except Exception as e:
                    print(e)
                    objWallLength = 0

                # ds[obji['modelId']].append([-1, ori, minDistance,
                # f'{h["origin"]} - {room["roomId"]}',
                # obji['orient'], np.arctan2(wn[0], wn[1]),
                # int(wallMinIndex), shape[wallMinIndex][0], shape[wallMinIndex][1], secMinDistance])

                ds[obji['modelId']].append([-1, ori, minDistance] +
                                           obji['scale'] +
                                           [objWallLength, secMinDistance])
    wdotdirname = 'wdot-4'
    cnt = 0
    for obji in ds:
        if len(ds[obji]) == 0:
            continue
        print('(%d/%d) saving ' % (cnt, len(ds)) + obji)
        if os.path.exists(f'./latentspace/{wdotdirname}') is False:
            os.mkdir(f'./latentspace/{wdotdirname}')
        with open(f'./latentspace/{wdotdirname}/{obji}.json', 'w') as f:
            json.dump(ds[obji], f)
        cnt += 1
Example #14
0
import mirheo as mir
import numpy as np
import trimesh, argparse

parser = argparse.ArgumentParser()
parser.add_argument("--mesh", type=str, required=True)
args = parser.parse_args()

ranks  = (1, 1, 1)
domain = (12, 8, 10)

rc=1.0

u = mir.Mirheo(ranks, domain, dt=0, debug_level=3, log_filename='log', no_splash=True)

m = trimesh.load(args.mesh);
mesh = mir.ParticleVectors.MembraneMesh(m.vertices.tolist(), m.faces.tolist())

pv_rbc = mir.ParticleVectors.MembraneVector("rbc", mass=1.0, mesh=mesh)
ic_rbc = mir.InitialConditions.Membrane([[6.0, 4.0, 5.0,   1.0, 0.0, 0.0, 0.0]])
u.registerParticleVector(pv_rbc, ic_rbc)

box_lo = (          - domain[0],           - domain[1],             rc)
box_hi = (domain[0] + domain[0], domain[1] + domain[1], domain[2] - rc)
plates = mir.Walls.Box("plates", box_lo, box_hi, inside=True)
u.registerWall(plates, 0)

# fake repulsion module to force sdf computation
u.registerPlugins(mir.Plugins.createWallRepulsion("wallRepulsion", pv_rbc, plates, C=500, h=rc, max_force=500))

dump_every = 1
Example #15
0
def get_mesh(file_name):
    mesh = trimesh.load(os.path.join(dir_models,
                                     file_name))
    mesh.metadata['file_name'] = str(file_name)
    return mesh
    cfg['generation']['mesh_color'] = False
    print('Disabling mesh color for interpolation generation.')
generator = config.get_generator(model, cfg, device=device)

# Generate
model.eval()

if not os.path.exists(generation_dir):
    os.makedirs(generation_dir)

# Process folder path
mesh_files.sort()
modelname = args.seq_name

loc, scale, mesh = load_and_scale_mesh(mesh_files[0])
f = trimesh.load(mesh_files[0], process=False).faces

# Sample random points
n_p = args.num_points
_, face_idx = mesh.sample(n_p, return_index=True)
alpha = np.random.dirichlet((1, ) * 3, n_p)
points = []
vertices = []
for mesh_path in mesh_files:
    _, _, mesh = load_and_scale_mesh(mesh_path, loc, scale)
    p = (alpha[:, :, None] * mesh.vertices[mesh.faces[face_idx]]).sum(axis=1)
    points.append(torch.tensor(p).float())
    vertices.append(torch.tensor(mesh.vertices).float())

# Prepare data dictionary
data = {
Example #17
0
# trimesh utilities and helpers
import npp
import numpy as np
import trimesh as tm, trimesh.viewer
import du
import datetime
import pyglet, pyglet.gl  # dependencies of trimesh
import os, pathlib
# import IPython as ip

currentPath = pathlib.Path(os.path.abspath(__file__))
spherePath = currentPath.parents[1] / 'data/sphere/sphere_ico5.obj'
assert spherePath.is_file(), "Can't find data/sphere/sphere_ico5.obj."
sphere = tm.load(str(spherePath))
nSV = sphere.vertices.shape[0]


def LoadObjs(objDir):
    """ Parallel load obj files in meshDir. """
    files = du.GetFilePaths(objDir, 'obj')
    return du.Parfor(tm.load, files, showProgress=False)


def MakeEllipsoid(Tx, scale, color=None):
    """ Make ellipsoidal mesh 

  INPUT
    Tx (ndarray, [4x4]): Transformation to apply
    scale (ndarray, [3,]): Scale x, y z
    color (ndarray, uint8, [3,] or [4,]): 0..255 for rgba
Example #18
0
    grid_y, grid_x = np.mgrid[Y_max:Y_min:-gsd, X_min:X_max:gsd]
    grid_z = griddata(xyz[:, 0:2], xyz[:, 2], (grid_x, grid_y), method=method)

    bbox = np.array([X_min, X_max, Y_min, Y_max])

    return grid_x, grid_y, grid_z, bbox


if __name__ == '__main__':

    # test on a sphere mesh
    #mesh = trimesh.primitives.Sphere()
    #mesh = trimesh.load('./models/cube_compressed.obj')
    #mesh = trimesh.load('./models/cube.OBJ')
    #mesh = trimesh.load('./models/cube_test.OBJ')
    mesh = trimesh.load('./models/DEM_yeosu/34707 - Cloud.obj')  # GSD: 90m
    vertices = np.array(mesh.vertices)

    # create some rays
    # DJI_0386.JPG
    # ray_origins = np.array([[266277.339, 237080.832, 214.9540],   # Absolute height
    #                         [266277.339, 237080.832, 214.9540],
    #                         [266277.339, 237080.832, 214.9540],
    #                         [266277.339, 237080.832, 214.9540]])
    ray_origins = np.array([
        [266277.339, 237080.832, 149.9540],  # Relative height
        [266277.339, 237080.832, 149.9540],
        [266277.339, 237080.832, 149.9540],
        [266277.339, 237080.832, 149.9540]
    ])
    direction = np.array([1.697624393, -2.926766149, -54.16184732
Example #19
0
import trimesh
import numpy as np
import gdist

ames = trimesh.load('../notebooks/Ames_inverted.ply')

print ames.faces

Example #20
0
import numpy as np
import trimesh


if __name__ == "__main__":
    # print logged messages
    trimesh.util.attach_to_log()

    # load a mesh
    mesh = trimesh.load("../models/featuretype.STL")

    # get a scene object containing the mesh, this is equivalent to:
    # scene = trimesh.scene.Scene(mesh)
    scene = mesh.scene()

    r = trimesh.transformations.rotation_matrix(np.radians(45.0), [0, 1, 0], scene.centroid)
    for i in range(4):
        trimesh.constants.log.info("Saving image %d", i)

        # rotate the camera view
        camera_new = np.dot(scene.transforms.get("camera"), r)
        scene.transforms.update("camera", matrix=camera_new)

        file_name = "render_" + str(i) + ".png"
        # save a render of the object as a png
        scene.save_image(file_name, resolution=np.array([1920, 1080]) * 2)
Example #21
0
def obj2ply_trimesh(obj_file, ply_file, debug=True):
    '''
	sometims the pcl function does not work
	'''
    mesh = trimesh.load(obj_file)
    trimesh.io.export.export_mesh(mesh, ply_file)
Example #22
0
args = parser.parse_args()


path   = "ply/"
pvname = "rbc"
off    = "rbc_mesh.off"

ranks  = (1, 1, 1)
domain = (12, 8, 10)

u = ymr.ymero(ranks, domain, dt=0, debug_level=3, log_filename='log')

if args.readFrom == "off":
    mesh = ymr.ParticleVectors.MembraneMesh(off)
elif args.readFrom == "trimesh":
    m = trimesh.load(off);
    mesh = ymr.ParticleVectors.MembraneMesh(m.vertices.tolist(), m.faces.tolist())

rbc  = ymr.ParticleVectors.MembraneVector(pvname, mass=1.0, mesh=mesh)
icrbc = ymr.InitialConditions.Membrane([[6.0, 4.0, 5.0,   1.0, 0.0, 0.0, 0.0]])
u.registerParticleVector(pv=rbc, ic=icrbc)

mdump = ymr.Plugins.createDumpMesh("mesh_dump", rbc, 1, path)
u.registerPlugins(mdump)

u.run(3)

if u.isMasterTask():
    mesh = trimesh.load(path + pvname + "_00000.ply")
    np.savetxt("vertices.txt", mesh.vertices, fmt="%g")
    np.savetxt("faces.txt",    mesh.faces,    fmt="%d")
                    0] / occupancies.shape[0]
                eval_dict['occupancy rate'] = occupied_perc
            else:
                print('Warning: %s points for %s %s do not exist' %
                      (f, c, modelname))

            # Pointcloud
            pointcloud_path = os.path.join(model_path, 'pointcloud.npz')
            if os.path.exists(pointcloud_path):
                pointcloud = np.load(pointcloud_path)
                # Original Mesh
                mesh_path = os.path.join(pix3d_path, 'model', c, modelname,
                                         'model.obj')
                if os.path.exists(mesh_path):
                    # Read Pix3D Mesh
                    mesh_orig = trimesh.load(mesh_path)
                    pointcloud_orig, idx = mesh_orig.sample(200000,
                                                            return_index=True)
                    pointcloud_orig = pointcloud_orig.astype(np.float32)
                    normals_orig = mesh_orig.face_normals[idx]
                    # Define Targets
                    normals_tgt = pointcloud['normals'].astype(np.float32)
                    pointcloud_tgt = pointcloud['points'].astype(np.float32)
                    # Evaluate
                    eval_dict_pointcloud = evaluator.eval_pointcloud(
                        pointcloud_orig, pointcloud_tgt, normals_orig,
                        normals_tgt)
                    for k, v in eval_dict_pointcloud.items():
                        eval_dict[k] = v
                else:
                    print('Warning: original mesh for %s does not exist' %
Example #24
0
# check whether the data folder exists
FILE_PATH = os.path.dirname(os.path.abspath(__file__))
RES_PATH = os.path.join(FILE_PATH, '../data/bunny_v2')
if not os.path.exists(RES_PATH):
    print('cannot find resources folder, please update RES_PATH')
    exit(1)

if __name__ == '__main__':
    # Load data file into trimesh-object
    dst_DataFile = 'bun000_v2.ply'
    src_DataFile = 'bun045_v2.ply'

    mesh_fp = os.path.join(RES_PATH, dst_DataFile)
    assert os.path.exists(mesh_fp), 'cannot found:' + mesh_fp
    dst_tm = trimesh.load(mesh_fp)

    mesh_fp = os.path.join(RES_PATH, src_DataFile)
    assert os.path.exists(mesh_fp), 'cannot found:' + mesh_fp
    src_tm = trimesh.load(mesh_fp)

    # rate list
    rates = np.array([0.01, 0.1, 0.25, 0.5, 0.75, 1])

    # ME figure setting
    fig_ME = plt.figure(figsize=(16, 8))
    ax_ME = fig_ME.add_subplot(1, 2, 1)
    ax_time = fig_ME.add_subplot(1, 2, 2)
    ax_ME.set_ylabel('distance ME')
    ax_ME.set_xlabel('iteration')
    # mesh figure
        st = np.sin(beta)
        sp = np.sin(alpha)
        out[..., 0] = r * st * cp  # x
        out[..., 1] = r * st * sp  # y
        out[..., 2] = r * ct       # z
        return out

file_list = glob.glob(os.path.join('/flush5/ram095/nips20/datasets/shapenet/ShapeNetCore.v2.zip/', '*.obj'))
sgrid = make_sgrid_(128)
itr=0
mitr = 0
nPoints = 0
for filename in file_list:
    try:
        if 'chair' in filename:
                mesh = trimesh.load(filename)
                mitr = mitr + 1
                print(filename)
                print(mesh.vertices.shape[0])
                if mesh.vertices.shape[0] < 15000:
                        if itr > 0:
                                print(mesh.vertices.shape)
                                mesh.remove_degenerate_faces()
                                mesh.fix_normals()
                                mesh.fill_holes()
                                mesh.remove_duplicate_faces()
                                mesh.remove_infinite_values()
                                mesh.remove_unreferenced_vertices()
                                mesh.apply_translation(-mesh.centroid)
                                r = np.max(np.linalg.norm(mesh.vertices, axis=-1))
                                mesh.apply_scale(1 / r)
def evaluate_one_instance(dataset, class_name, instance_name, experiment_directory, checkpoint, data_dir):
    logging.debug(
        "evaluating " + os.path.join(dataset, class_name, instance_name)
    )
    reconstructed_mesh_filename = ws.get_reconstructed_mesh_filename(
        experiment_directory, checkpoint, dataset, class_name, instance_name
    )

    logging.debug(
        'reconstructed mesh is "' + reconstructed_mesh_filename + '"'
    )

    if not os.path.isfile(reconstructed_mesh_filename):
        print('[WARNING] Skipping %s as it doesn\'t exists' % reconstructed_mesh_filename)
        return "", 0

    ground_truth_samples_filename = os.path.join(
        data_dir,
        "SurfaceSamples",
        dataset,
        class_name,
        instance_name + ".ply",
    )

    logging.debug(
        "ground truth samples are " + ground_truth_samples_filename
    )

    normalization_params_filename = os.path.join(
        data_dir,
        "NormalizationParameters",
        dataset,
        class_name,
        instance_name + ".npz",
    )

    logging.debug(
        "normalization params are " + ground_truth_samples_filename
    )

    ground_truth_points = trimesh.load(ground_truth_samples_filename)
    reconstruction = trimesh.load(reconstructed_mesh_filename)

    normalization_params = np.load(normalization_params_filename)

    chamfer_dist = deep_sdf.metrics.chamfer.compute_trimesh_chamfer(
        ground_truth_points,
        reconstruction,
        normalization_params["offset"],
        normalization_params["scale"],
    )

    earthmover_dist = deep_sdf.metrics.emd.compute_trimesh_emd(
        ground_truth_points,
        reconstruction,
        normalization_params["offset"],
        normalization_params["scale"],
    )

    logging.debug("chamfer distance: " + str(chamfer_dist))

    return os.path.join(dataset, class_name, instance_name), chamfer_dist, earthmover_dist
class OPT:
    sample_num = 2500
    max_distance_bin = 1146
    distance_resolution = 5 * 10**-3
    epsilon = sys.float_info.epsilon
    normal = 'fn'
    f = 0.5
    z = 1.8
    sensor = np.array([f, 0, z])
    lighting = np.array([-f, 0, z])
    sensor_normal = np.array([0, 0, -1])
    lighting_normal = np.array([0, 0, -1])


mesh_location = '../mesh_processing/data/bunny.obj'
mesh = trimesh.load(mesh_location)

opt = OPT()

gpu_IDs = [3, 3, 3]
gpu_threads = []

weight = torch.DoubleTensor(opt.max_distance_bin).fill_(1)
queue = queue.Queue()

tic = time.time()
for tid in gpu_IDs:
    t = threading.Thread(target=worker,
                         args=[tid, mesh, opt, weight, queue, True])
    print("start GPU thread {0}...".format(tid))
    time.sleep(0.2)