Exemple #1
0
def main():
    args = parse_args();
    mesh1 = pymesh.load_mesh(args.input_mesh_1);
    mesh2 = pymesh.load_mesh(args.input_mesh_2);
    if args.timing:
        mesh, t = pymesh.boolean(mesh1, mesh2, args.operation, args.engine,
                with_timing = args.timing,
                exact_mesh_file = args.exact);
        print("Timing: {}".format(t));
    else:
        mesh = pymesh.boolean(mesh1, mesh2, args.operation, args.engine,
                exact_mesh_file = args.exact);
    pymesh.save_mesh(args.output_mesh, mesh, *mesh.get_attribute_names());
Exemple #2
0
def main():
    args = parse_args();
    mesh_1 = pymesh.load_mesh(args.input_mesh_1);
    mesh_2 = pymesh.load_mesh(args.input_mesh_2);
    assert(mesh_1.dim == 3);
    assert(mesh_2.dim == 3);

    bbox_min_1, bbox_max_1 = mesh_1.bbox;
    bbox_min_2, bbox_max_2 = mesh_2.bbox;

    bbox_min = np.minimum(bbox_min_1, bbox_min_2);
    bbox_max = np.maximum(bbox_max_1, bbox_max_2);

    #queries = grid_sample(bbox_min, bbox_max, args.num_samples);
    queries = random_sample(bbox_min, bbox_max, args.num_samples);

    winding_number_1 = pymesh.compute_winding_number(mesh_1, queries,
            engine=args.winding_number_engine) > 0.5;
    winding_number_2 = pymesh.compute_winding_number(mesh_2, queries,
            engine=args.winding_number_engine) > 0.5;

    diff = np.logical_xor(winding_number_1, winding_number_2);
    num_diff = np.count_nonzero(diff);
    print("Winding numbers of {} out of {} samples differ".format(
        num_diff, len(queries)));

    if args.output is not None:
        r = np.amax(bbox_max - bbox_min) * 0.01;
        box = pymesh.generate_box_mesh(np.ones(3) * -r, np.ones(3) * r);

        vertices = [];
        faces = [];
        for i in range(len(queries)):
            vertices.append(box.vertices + queries[i]);
            faces.append(box.faces + box.num_vertices * i);
        vertices = np.vstack(vertices);
        faces = np.vstack(faces);
        mesh = pymesh.form_mesh(vertices, faces);
        mesh.add_attribute("diff");
        mesh.set_attribute("diff", np.repeat(diff, box.num_faces));
        pymesh.save_mesh(args.output, mesh, "diff");

    if args.export:
        info = load_info(args.input_mesh_2);
        info["diff"] = num_diff
        dump_info(args.input_mesh_2, info);

    if args.timing:
        pymesh.timethis.summarize();
Exemple #3
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    if (mesh.vertex_per_face != 4):
        raise IOError("input mesh is not a quad mesh");
    mesh = pymesh.quad_to_tri(mesh, args.keep_symmetry);
    pymesh.save_mesh(args.output_mesh, mesh, *mesh.get_attribute_names());
Exemple #4
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    grid = pymesh.VoxelGrid(args.cell_size, mesh.dim);
    grid.insert_mesh(mesh);
    out_mesh = grid.mesh;
    pymesh.save_mesh(args.output_mesh, out_mesh);
Exemple #5
0
def triangulate(wires, engine, stage, eps, logger, wire_file, json_file):
    if wires.num_vertices == 0:
        return pymesh.form_mesh(np.zeros((0, 2)), np.zeros((0,3)));
    basename = os.path.splitext(wire_file)[0];
    if engine == "triwild":
        out_mesh = "{}_linear.msh".format(basename);
        log_file = "{}_triwild.log".format(basename);
        if json_file is not None:
            command = "TriWild --choice TRI --is-log 0 --epsilon {} --stage {} --log-file {} --int-edge-length 20 --feature-input {} --output-debug-mesh=0 --skip-eps --input {} --output {}".format(
                    eps, stage, log_file, json_file, wire_file, basename);
        else:
            command = "TriWild --choice TRI --is-log 0 --epsilon {} --stage {} --log-file {} --int-edge-length 20 --output-debug-mesh=0 --skip-eps --input {} --output {}".format(
                    eps, stage, log_file, wire_file, basename);
        print(command);
        start_time = time();
        check_call(command.split());
        finish_time = time();
        t = finish_time - start_time;
        mesh = pymesh.load_mesh(out_mesh, drop_zero_dim=True);
    else:
        mesh, t = pymesh.triangulate_beta(wires.vertices, wires.edges,
                engine=engine, with_timing=True);
    logger.info("Triangulation running time: {}".format(t));

    return mesh;
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);

    vertices = mesh.vertices;
    voxels = mesh.voxels;
    num_voxels = mesh.num_voxels;
    orientation = np.zeros(num_voxels);

    for i in range(num_voxels):
        tet = voxels[i];
        orientation[i] = pymesh.orient_3D(
                vertices[tet[1]],
                vertices[tet[0]],
                vertices[tet[2]],
                vertices[tet[3]]);
        if orientation[i] < 0:
            orientation[i] = -1;
        elif orientation[i] > 0:
            orientation[i] = 1;

    mesh.add_attribute("orientation");
    mesh.set_attribute("orientation", orientation);

    pymesh.save_mesh(args.output_mesh, mesh, "orientation");
Exemple #7
0
def main():
    args = parse_args();

    mesh = load_mesh(args.mesh_in);
    comps = separate_mesh(mesh, args.connectivity_type);

    if args.highlight:
        if (args.connectivity_type == "face"):
            comp_indicator = np.zeros(mesh.num_faces);
        elif (args.connectivity_type == "voxel"):
            comp_indicator = np.zeros(mesh.num_voxels);
        elif (mesh.num_voxels > 0):
            comp_indicator = np.zeros(mesh.num_voxels);
        else:
            comp_indicator = np.zeros(mesh.num_faces);

        for i in range(len(comps)):
            elem_sources = comps[i].get_attribute("ori_elem_index")\
                    .ravel().astype(int);
            comp_indicator[elem_sources] = i;
        mesh.add_attribute("component_index");
        mesh.set_attribute("component_index", comp_indicator);
        save_mesh(args.mesh_out, mesh, *mesh.get_attribute_names());
    else:
        basename, ext = os.path.splitext(args.mesh_out);
        for i,comp in enumerate(comps):
            filename = "{}_cc{}{}".format(basename, i, ext);
            save_mesh(filename, comp, *comp.get_attribute_names());
Exemple #8
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    mesh.add_attribute("vertex_index");
    mesh.add_attribute("face_index");
    mesh.add_attribute("voxel_index");
    pymesh.save_mesh(args.output_mesh, mesh, *mesh.attribute_names);
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.in_mesh);
    if (args.with_rounding):
        mesh = pymesh.form_mesh(
                np.round(mesh.vertices, args.precision),
                mesh.faces);
    intersecting_faces = pymesh.detect_self_intersection(mesh);

    counter = 0;
    while len(intersecting_faces) > 0 and counter < args.max_iterations:
        if (args.with_rounding):
            involved_vertices = np.unique(mesh.faces[intersecting_faces].ravel());
            mesh.vertices_ref[involved_vertices, :] =\
                    np.round(mesh.vertices[involved_vertices, :],
                            args.precision//2);
        mesh = pymesh.resolve_self_intersection(mesh, "igl");
        mesh, __ = pymesh.remove_duplicated_faces(mesh, fins_only=True);
        if (args.with_rounding):
            mesh = pymesh.form_mesh(
                    np.round(mesh.vertices, args.precision),
                    mesh.faces);
        intersecting_faces = pymesh.detect_self_intersection(mesh);
        counter += 1;

    if len(intersecting_faces) > 0:
        logging.warn("Resolving failed: max iteration reached!");

    pymesh.save_mesh(args.out_mesh, mesh);
Exemple #10
0
def main():
    args = parse_args();

    input_meshes = [load_mesh(filename) for filename in args.input_meshes];
    output_mesh = merge_meshes(input_meshes);
    save_mesh(args.output, output_mesh,
            *output_mesh.get_attribute_names());
Exemple #11
0
def main():
    args = parse_args();

    mesh = pymesh.load_mesh(args.input_mesh);
    mesh.add_attribute("vertex_gaussian_curvature");
    mesh.add_attribute("vertex_mean_curvature");
    pymesh.save_mesh(args.output_mesh, mesh, *mesh.get_attribute_names());
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);

    f_indices = pymesh.get_degenerated_faces(mesh);
    if (len(f_indices) == 0):
        print("mesh does not have any degenerated faces");
        return;

    v_indices = mesh.faces[f_indices].ravel();
    degenerated_faces = np.zeros(mesh.num_faces);
    degenerated_faces[f_indices] = 1.0;
    degenerated = np.zeros(mesh.num_vertices);
    degenerated[v_indices] = 1.0;
    mesh.add_attribute("degenerated_faces");
    mesh.set_attribute("degenerated_faces", degenerated_faces);
    mesh.add_attribute("degenerated");
    mesh.set_attribute("degenerated", degenerated);

    print("{} degenerated faces, consisting of {} vertices.".format(
        len(f_indices), np.count_nonzero(degenerated)));
    if args.verbose:
        print("Degenerated faces indices: {}".format(f_indices));

    pymesh.save_mesh(args.output_mesh, mesh, "degenerated", "degenerated_faces");

    if args.extract_region is not None:
        region = pymesh.submesh(mesh, f_indices, 0);
        pymesh.save_mesh(args.extract_region, region,
                *region.get_attribute_names());
Exemple #13
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    mesh = pymesh.retriangulate(mesh,
            args.max_area,
            not args.no_split_boundary,
            not args.no_steiner_points);
    pymesh.save_mesh(args.output_mesh, mesh);
Exemple #14
0
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)
    wires = pymesh.wires.WireNetwork.create_from_file(args.path)
    path = chain_wires(wires)

    result = pymesh.minkowski_sum(mesh, path)
    pymesh.save_mesh(args.output_mesh, result)
Exemple #15
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh, drop_zero_dim=True);
    mesh,__ = pymesh.split_long_edges(mesh, 0.01);
    points = mesh.vertices[mesh.boundary_vertices,:];
    mesh = pymesh.triangulate_beta(points, args.engine);
    pymesh.save_mesh(args.output_mesh, mesh);
    pymesh.timethis.summarize();
Exemple #16
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    out_mesh, info = pymesh.split_long_edges(mesh, args.max_edge_length);

    if mesh.has_attribute("corner_texture"):
        pymesh.map_corner_attribute(mesh, out_mesh, "corner_texture");

    pymesh.save_mesh(args.output_mesh, out_mesh, *out_mesh.attribute_names);
Exemple #17
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    if (mesh.vertex_per_face != 4):
        logging.warning("Input mesh is not quad mesh.");
        pymesh.save_mesh(args.output_mesh, mesh, *mesh.get_attribute_names());
    else:
        mesh = pymesh.quad_to_tri(mesh, args.keep_symmetry);
        pymesh.save_mesh(args.output_mesh, mesh, *mesh.get_attribute_names());
Exemple #18
0
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)
    if mesh.num_voxels <= 0:
        raise RuntimeError("Input mesh contains 0 voxels.")
    if mesh.vertex_per_voxel != 4:
        raise RuntimeError("Input mesh is not a tet mesh.")
    mesh = tet_to_hex(mesh)
    pymesh.save_mesh(args.output_mesh, mesh)
Exemple #19
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.mesh_file);
    if not args.dual:
        vertices, edges = pymesh.mesh_to_graph(mesh);
    else:
        vertices, edges = pymesh.mesh_to_dual_graph(mesh);
    wire_network = pymesh.wires.WireNetwork.create_from_data(vertices, edges);
    wire_network.write_to_file(args.wire_file);
def tryGetTile(x, y, l):
	decname = decTileName(x, y, l)
	if(os.path.exists(decname)):
		return pymesh.load_mesh(decname)
	name = tileName(x, y, l)
	if(os.path.exists(name)):
		print("loaded ", name)
		# return pymesh.load_mesh(name)
	else :
		return ""
Exemple #21
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh, drop_zero_dim=True);
    r = pymesh.convex_hull(mesh, args.engine, args.with_timing);
    if args.with_timing:
        hull, running_time = r;
        print("Running time: {}s".format(running_time));
    else:
        hull = r;
    pymesh.save_mesh(args.output_mesh, hull, *hull.attribute_names);
Exemple #22
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    if args.initial_block is not None:
        block = pymesh.load_mesh(args.initial_block);
    else:
        bbox_min, bbox_max = mesh.bbox;
        block = pymesh.generate_box_mesh(bbox_min, bbox_max, 2, keep_symmetry=True);
        block = pymesh.form_mesh(block.vertices, block.faces);
        block, __ = pymesh.remove_isolated_vertices(block);

    carved = carve_mesh(mesh, block, args.N,
            args.batch_size,
            args.output_mesh,
            args.initial_N,
            args.save_intermediate,
            args.debug);

    pymesh.save_mesh(args.output_mesh, carved);
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    bd_edges = mesh.boundary_edges;
    bd_vertices = np.unique(bd_edges.ravel());
    is_bd_vertices = np.zeros(mesh.num_vertices);
    is_bd_vertices[bd_vertices] = True;
    mesh.add_attribute("boundary_vertices");
    mesh.set_attribute("boundary_vertices", is_bd_vertices);

    pymesh.save_mesh(args.output_mesh, mesh, *mesh.attribute_names);
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);

    intersecting_faces = pymesh.detect_self_intersection(mesh);
    intersection_marker = np.zeros(mesh.num_faces);
    for i,face_pair in enumerate(intersecting_faces):
        intersection_marker[face_pair] = i+1;

    mesh.add_attribute("intersecting_faces");
    mesh.set_attribute("intersecting_faces", intersection_marker);
    pymesh.save_mesh(args.output_mesh, mesh, "intersecting_faces");
Exemple #25
0
def main():
    args = parse_args();
    scale = np.ones(3) * args.scale;
    if args.scale_x is not None:
        scale[0] = args.scale_x;
    if args.scale_y is not None:
        scale[1] = args.scale_y;
    if args.scale_z is not None:
        scale[2] = args.scale_z;

    mesh = pymesh.load_mesh(args.input_mesh);
    mesh = pymesh.form_mesh(mesh.vertices * scale, mesh.faces, mesh.voxels);
    pymesh.save_mesh(args.output_mesh, mesh);
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    mesh.add_attribute("face_area");
    areas = mesh.get_attribute("face_area");
    zero_faces = areas == 0.0;

    roi = np.zeros(mesh.num_vertices);
    roi[mesh.faces[zero_faces]] = 1.0;
    mesh.add_attribute("zero_faces");
    mesh.set_attribute("zero_faces", roi);

    pymesh.save_mesh(args.output_mesh, mesh, "zero_faces");
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);

    formula = Formula(mesh);
    values = formula.eval_formula(args.formula);
    if isinstance(values, list):
        values = np.array(values, dtype=float);
    elif isinstance(values, (int, float)):
        values = np.ones(mesh.num_elements, dtype=float) * values;
    mesh.add_attribute(args.name);
    mesh.set_attribute(args.name, values);

    pymesh.save_mesh(args.output_mesh, mesh, *mesh.get_attribute_names());
Exemple #28
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    assert(mesh.has_attribute("corner_texture"));

    mesh.enable_connectivity();
    vertices = np.copy(mesh.vertices);

    bad_vertex = np.logical_not(np.all(np.isfinite(mesh.vertices), axis=1));
    bad_vertex_indices = np.arange(mesh.num_vertices, dtype=int)[bad_vertex];
    for i in bad_vertex_indices:
        adj_v = mesh.get_vertex_adjacent_vertices(i);
        adj_v = adj_v[np.logical_not(bad_vertex[adj_v])];
        vertices[i] = np.mean(vertices[adj_v,:], axis=0);

    out_mesh = pymesh.form_mesh(vertices, mesh.faces);

    if mesh.has_attribute("corner_texture"):
        faces = mesh.faces;
        uv = np.copy(mesh.get_attribute("corner_texture").reshape((-1, 2)));
        bad_uv = np.logical_not(np.all(np.isfinite(uv), axis=1));
        bad_uv_indices = np.arange(len(uv), dtype=int)[bad_uv];
        for i in bad_uv_indices:
            fi = i // mesh.vertex_per_face;
            ci = i % mesh.vertex_per_face;
            vi = faces[fi, ci];
            adj_f = mesh.get_vertex_adjacent_faces(vi);
            adj_c = [adj_f[j]*mesh.vertex_per_face +
                    np.argwhere(f==vi).ravel()[0]
                    for j,f in enumerate(faces[adj_f, :])];
            adj_c = np.array(adj_c, dtype=int);
            adj_c = adj_c[np.logical_not(bad_uv[adj_c])];
            if len(adj_c) > 0:
                uv[i] = np.mean(uv[adj_c,:], axis=0);
            else:
                # All corner uv at this vertex is NaN. Average the one-ring instead.
                adj_c = [adj_f[j]*mesh.vertex_per_face +
                        (np.argwhere(f==vi).ravel()[0]+1)%mesh.vertex_per_face
                        for j,f in enumerate(faces[adj_f, :])];
                adj_c += [adj_f[j]*mesh.vertex_per_face +
                        (np.argwhere(f==vi).ravel()[0]+2)%mesh.vertex_per_face
                        for j,f in enumerate(faces[adj_f, :])];
                adj_c = np.array(adj_c, dtype=int);
                adj_c = adj_c[np.logical_not(bad_uv[adj_c])];
                uv[i] = np.mean(uv[adj_c,:], axis=0);

        out_mesh.add_attribute("corner_texture");
        out_mesh.set_attribute("corner_texture", uv);

    pymesh.save_mesh(args.output_mesh, out_mesh);
Exemple #29
0
def tile_with_guide_mesh(config):
    options = extract_options(config);
    network = load_wire(str(config["wire_network"]));
    parameters = load_parameters(network, config);
    guide_mesh = pymesh.load_mesh(config["guide_mesh"]);

    tiler = Tiler();
    tiler.set_base_pattern(network);
    tiler.tile_with_guide_mesh(guide_mesh, parameters);
    network = tiler.wire_network;

    inflator = Inflator(network);
    inflator.inflate(network.get_attribute("thickness").ravel(),
            parameters.per_vertex_thickness);
    return inflator.mesh;
Exemple #30
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    assert(mesh.dim == 3);

    total_vol = 0.0;
    origin = np.zeros(3);
    vertices = mesh.vertices;
    for f in mesh.faces:
        corners = vertices[f];
        volume = np.dot(np.cross(corners[0], corners[1]), corners[2]);
        total_vol += volume;

    total_vol /= 6.0;
    print("Total volume: {}".format(total_vol));
Exemple #31
0
def convert_obj2ply(obj_filename,
                    ply_filename,
                    recenter=False,
                    center_mode='pt_center'):
    mesh = pymesh.load_mesh(obj_filename)
    pymesh.remove_isolated_vertices(mesh)

    if recenter:
        if center_mode == 'pt_center':
            center = np.mean(mesh.vertices, axis=0)
        elif center_mode == 'box_center':
            min_p = np.amin(mesh.vertices, axis=0)
            max_p = np.amax(mesh.vertices, axis=0)
            center = (min_p + max_p) / 2.0

        new_vertices = mesh.vertices - center
        mesh = pymesh.form_mesh(new_vertices, mesh.faces)

    pymesh.save_mesh(ply_filename, mesh)
Exemple #32
0
def main():
    args = parse_args();
    mesh = pymesh.load_mesh(args.input_mesh);
    slices = slice_mesh(mesh, args.N);

    v_count = 0;
    vertices = [];
    edges = [];
    basename, ext = os.path.splitext(args.output_slices);
    for i,s in enumerate(slices):
        slice_file = "{}_{:06}{}".format(basename, i, ext);
        s.write_to_file(slice_file);
        vertices.append(s.vertices);
        edges.append(s.edges + v_count);
        v_count += s.num_vertices;

    all_wires = pymesh.wires.WireNetwork.create_from_data(
            np.vstack(vertices), np.vstack(edges));
    all_wires.write_to_file(args.output_slices);
Exemple #33
0
def get_normalize_mesh(model_dir, norm_mesh_sub_dir, target_dir):
    norm_file = os.path.join(norm_mesh_sub_dir, "pc_norm.obj")
    target_norm_file = os.path.join(target_dir, "pc_norm.obj")
    command_str = "cp " + norm_file + " " + target_norm_file
    print("command:", command_str)
    os.system(command_str)

    model_obj = os.path.join(model_dir, "model.obj")
    target_model_obj = os.path.join(target_dir, "model.obj")
    params = np.loadtxt(os.path.join(norm_mesh_sub_dir, "pc_norm.txt"))
    print("trimesh_load:", model_obj)

    centroid = params[:3]
    m = params[3]
    print("centroid, m", centroid, m)

    ori_mesh = pymesh.load_mesh(model_obj)
    verts = (ori_mesh.vertices - centroid) / float(m)
    pymesh.save_mesh_raw(target_model_obj, verts, ori_mesh.faces)
def measure_distances_on_surface_non_registered_pymesh(
        source_obj_file,
        destination_obj_file,
        measure_on_source_vertices=ALL_POINTS):
    import pymesh

    #source_mesh = np.array(read_mesh(source_obj_file))
    destination_mesh = pymesh.load_mesh(destination_obj_file)
    #for index_source in range(len(source_mesh)):
    # if index in list of given vertices or if list empty measure all distances
    #	if (measure_on_source_vertices==ALL_POINTS or index_source in measure_on_source_vertices):
    if measure_on_source_vertices == ALL_POINTS:
        measure_on_source_vertices = range(destination_mesh.num_vertices)
    source_points = get_vertex_positions(source_obj_file,
                                         measure_on_source_vertices)
    squared_distances, face_indices, closest_points = pymesh.distance_to_mesh(
        destination_mesh, source_points)
    distances = [math.sqrt(d2) for d2 in squared_distances]
    return distances
Exemple #35
0
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)
    info = load_info(args.input_mesh)

    header = "Summary of {}".format(args.input_mesh)
    print_header("{:=^55}".format(header))
    print_basic_info(mesh, info)
    print_bbox(mesh, info)
    print_face_info(mesh, info)
    print_voxel_info(mesh, info)
    if (args.extended):
        print_quantile_info(mesh, info)
        print_extended_info(mesh, info)
    if (args.self_intersection):
        print_self_intersection_info(mesh, info)

    if (args.export):
        dump_info(args.input_mesh, info)
Exemple #36
0
def isolate_files():
    """
    Utility fonction to generate the metro_file archive. Useless to all users but the author.
    """
    with open('./dataset/data/metro_files/files-metro.txt', 'r') as file:
        files = file.read().split('\n')
    for file in files:
        if file[-3:] == "ply":
            cat = file.split('/')[0]
            name = file.split('/')[1][:-4]
            path_points = '/'.join([
                '.', 'dataset', 'data', 'ShapeNetV1PointCloud', cat,
                name + '.points.ply.npy'
            ])
            path_png = '/'.join([
                '.', 'dataset', 'data', 'ShapeNetV1Renderings', cat, name,
                "rendering", '00.png'
            ])

            path_obj = '/'.join([
                '', 'home', 'thibault', 'hdd', 'data', 'ShapeNetCore.v1', cat,
                name, 'model.obj'
            ])
            mesh = pymesh.load_mesh(path_obj)
            points = np.load((path_points))
            if not exists('/'.join(
                ['.', 'dataset', 'data', 'metro_files', cat])):
                os.mkdir('/'.join(['.', 'dataset', 'data', 'metro_files',
                                   cat]))

            pymesh.save_mesh('/'.join(
                ['.', 'dataset', 'data', 'metro_files', cat, name + '.ply']),
                             mesh,
                             ascii=True)
            np.save(
                '/'.join([
                    '.', 'dataset', 'data', 'metro_files', cat, name + '.npy'
                ]), points)
            copy(
                path_png, '/'.join([
                    '.', 'dataset', 'data', 'metro_files', cat, name + '.png'
                ]))
Exemple #37
0
def tile_with_mixed_patterns(config):
    options = extract_options(config);
    options["dof_type"] = str(config.get("dof_type", "isotropic"));
    options["thickness_type"] = str(config.get("thickness_type", "vertex"));
    networks = load_wires(str(config["wire_list_file"]));
    guide_mesh = pymesh.load_mesh(config["guide_mesh"]);
    per_vertex_thickness = options["thickness_type"] == "vertex";

    tiler = Tiler();
    tiler.tile_with_mixed_patterns(mesh,
            per_vertex_thickness, options["dof_type"] == "isotropic");
    network = tiler.wire_network;

    if config.get("trim", False):
        network.trim();

    inflator = Inflator(network);
    inflator.inflate(network.get_attribute("thickness").ravel(),
            per_vertex_thickness);
    return inflator.mesh;
Exemple #38
0
def extract_vertices_and_faces(fn):
    print(f"Processing {fn}")
    mesh = pymesh.load_mesh(str(fn))

    # clean up
    mesh, _ = pymesh.remove_isolated_vertices(mesh)

    # get elements
    vertices = mesh.vertices.copy()
    faces = mesh.faces.copy()

    # move to center
    center = np.mean(vertices, axis=0)
    vertices -= center

    # normalize
    max_len = np.max(np.sum(vertices**2, axis=1))
    vertices /= np.sqrt(max_len)

    return vertices, faces
def extract_centroid_normal_list(mesh_filepath):
    mesh = pymesh.load_mesh(mesh_filepath)

    mesh.enable_connectivity()  # enables connectivity on mesh
    mesh.add_attribute("face_centroid")  # adds the face centroids to be accessed
    mesh.add_attribute("face_normal")  # adds the face normals to be accessed
    mesh.add_attribute("vertex_valance")

    faces = mesh.faces
    centroids = mesh.get_face_attribute("face_centroid")
    normals = mesh.get_face_attribute("face_normal")
    vertex_valance = mesh.get_vertex_attribute("vertex_valance")

    with open('/tmp/centroid_face_normals.txt', 'w') as file:
        file.write("x\ty\tz\tnx\tny\tnz\n")
        for face_id in range(0, mesh.num_faces):
            p = centroids[face_id]
            n = normals[face_id]

            file.write("{}\t{}\t{}\t{}\t{}\t{}\n".format(p[0], p[1], p[2], n[0], n[1], n[2]))
Exemple #40
0
def sample_save_gt_pnt(cat_id, cat_nm, gt_dir_cat, test_lst_f):
    count = 0
    with open(test_lst_f, "r") as f:
        test_objs = f.readlines()
        count += 1
        for obj_id in test_objs:
            obj_id = obj_id.rstrip('\r\n')
            obj_path = os.path.join(gt_dir_cat, obj_id, "isosurf.obj")
            # pred_path_lst = pred_dict[obj_id]
            verts_batch = np.zeros((FLAGS.num_sample_points, 3),
                                   dtype=np.float32)
            mesh1 = pymesh.load_mesh(obj_path)
            if mesh1.vertices.shape[0] > 0:
                choice = np.random.randint(mesh1.vertices.shape[0],
                                           size=FLAGS.num_sample_points)
                verts_batch = mesh1.vertices[choice, ...]
            savefn = os.path.join(gt_dir_cat, obj_id,
                                  "pnt_{}.txt".format(FLAGS.num_sample_points))
            np.savetxt(savefn, verts_batch, delimiter=',')
            print("saved gt pnt of {} at {}".format(obj_id, savefn))
Exemple #41
0
    def __init__(self, root, transform):
        self.root = root
        self.transform = transform
        self.CT = pymesh.load_mesh(self.root + 'hepatic_artery_200417.stl')
        self.dlist = os.listdir(self.root)
        self.list = [root + x for x in self.dlist if os.path.isdir(root + x)]
        self.list.sort()
        self.xlist = []
        self.num = 0
        for x in self.list:
            tt = os.listdir(x)
            tt.sort()
            [self.xlist.append(x + '/' + p) for p in tt]
            self.num += len(tt)

        self.f = open("kaist_rt.txt", "r")
        self.lines = self.f.read().split('\n')
        self.rt = np.zeros((len(self.lines), 4))
        for i in range(len(self.lines)):
            # print(self.lines[i].split(' '))
            self.rt[i, :] = np.asarray(self.lines[i].split(' '))
Exemple #42
0
def sample_save_pred_pnt(cat_id, cat_nm, pred_dir, test_lst_f):
    pred_dict = build_file_dict(pred_dir)
    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')
            pred_path_lst = pred_dict[obj_id]
            verts_batch = np.zeros((FLAGS.view_num, FLAGS.num_sample_points, 3), dtype=np.float32)
            for i in range(len(pred_path_lst)):
                pred_mesh_fl = pred_path_lst[i]
                mesh1 = pymesh.load_mesh(pred_mesh_fl)
                if mesh1.vertices.shape[0] > 0:
                    choice = np.random.randint(mesh1.vertices.shape[0], size=FLAGS.num_sample_points)
                    verts_batch[i, ...] = mesh1.vertices[choice, ...]
                savedir = os.path.join(os.path.dirname(pred_dir),"pnt_{}_{}".format(FLAGS.num_sample_points, cat_id))
                os.makedirs(savedir,exist_ok=True)
                view_id = pred_mesh_fl[-6:-4]
                savefn = os.path.join(savedir, "pnt_{}_{}.txt".format(obj_id, view_id))
                print(savefn)
                np.savetxt(savefn, verts_batch[i, ...], delimiter=',')
                print("saved gt pnt of {} at {}".format(obj_id, savefn))
Exemple #43
0
def shuffle_pc(file, output_path):
    mesh = pymesh.load_mesh(file)
    vertices = copy.deepcopy(mesh.vertices)
    permutation = np.random.permutation(len(vertices))
    vertices = vertices[permutation]
    new_mesh = pymesh.meshio.form_mesh(vertices, mesh.faces)
    new_mesh.add_attribute("vertex_nx")
    new_mesh.set_attribute("vertex_nx",
                           mesh.get_vertex_attribute("vertex_nx")[permutation])
    new_mesh.add_attribute("vertex_ny")
    new_mesh.set_attribute("vertex_ny",
                           mesh.get_vertex_attribute("vertex_ny")[permutation])
    new_mesh.add_attribute("vertex_nz")
    new_mesh.set_attribute("vertex_nz",
                           mesh.get_vertex_attribute("vertex_nz")[permutation])
    pymesh.save_mesh(output_path,
                     new_mesh,
                     ascii=True,
                     anonymous=True,
                     use_float=True,
                     *new_mesh.get_attribute_names())
Exemple #44
0
def main():
    mesh = pm.load_mesh(FLAGS.mesh)
    bmin, bmax = mesh.bbox
    pts = mesh.vertices
    pts = pts - np.tile(np.expand_dims((bmax + bmin) / 2,
                                       axis=0), [mesh.num_vertices, 1])
    pts = pts / np.max(np.linalg.norm(pts, axis=1))
    pts = pts[:, [0, 2, 1]]
    faces = mesh.faces

    style_img = ndimage.imread(FLAGS.style, mode='RGB')

    optimize(pts, faces, FLAGS.batch_size, style_img,
             content_weight=FLAGS.content_weight,
             style_weight=FLAGS.style_weight,
             tv_weight=FLAGS.tv_weight,
             epochs=FLAGS.max_epoch,
             learning_rate=FLAGS.learning_rate,
             tex_unit_size=FLAGS.tex_unit_size,
             subsample=FLAGS.subsample_size,
             log_dir=FLAGS.log_dir,
             try_resuming=FLAGS.try_resume_training)
Exemple #45
0
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)

    vertices = mesh.vertices
    voxels = mesh.voxels
    num_voxels = mesh.num_voxels
    orientation = np.zeros(num_voxels)

    for i in range(num_voxels):
        tet = voxels[i]
        orientation[i] = pymesh.orient_3D(vertices[tet[1]], vertices[tet[0]],
                                          vertices[tet[2]], vertices[tet[3]])
        if orientation[i] < 0:
            orientation[i] = -1
        elif orientation[i] > 0:
            orientation[i] = 1

    mesh.add_attribute("orientation")
    mesh.set_attribute("orientation", orientation)

    pymesh.save_mesh(args.output_mesh, mesh, "orientation")
Exemple #46
0
def test_attacks():
    
    data = [0, 1]*32
    write_file = "test_data/layered_spectral_attacks.csv"

    with open(write_file, 'a+') as output:

        layers = 60

        for strength in [1, 2, 3, 5, 7, 10, 20, 30, 50, 70, 100]:  

            # Read the watermarked mesh
            file_name = "watermarked_models/generated/bunny_strength"+str(strength)+ "_patches" + str(layers) + ".obj"
            data = [0, 1]*32
            watermarked_mesh = pymesh.load_mesh(file_name) 
            
            for iterations in [1, 2, 3, 5, 7, 10]:
                file_smoothed = "watermarked_models/generated/smoothed/bunny_strength"+str(strength)+ "_patches" + str(layers) + "_iterations" + str(iterations) + ".obj"
                # Smooth the model then save it
                pymesh.save_mesh(file_smoothed, attacks.smoothing(watermarked_mesh, iterations))
                # Extraction of the watermark
                retrieved = spectral_decomposition.extract(file_smoothed, 123456, 64, strength, layers)
                # Compute the number of errors
                n_errors = len([x for x, y in zip(data, retrieved) if x != y])
                # Write the results to a file 
                output.write("SMOOTHING, " + str(strength) + ", " + str(layers) + ", " + str(iterations) + "," + str(n_errors) + ";\n")
                output.flush()

            for amplitude in [0.01, 0.02, 0.03, 0.05, 0.07, 0.1]:
                file_noisy = "watermarked_models/generated/noisy/bunny_strength"+str(strength)+ "_layers" + str(layers) + "_amplitude" + str(amplitude) + ".obj"
                # Add random noise to the model then save it
                pymesh.save_mesh(file_noisy, attacks.noise(watermarked_mesh, amplitude))
                # Extraction of the watermark
                retrieved = spectral_decomposition.extract(file_noisy, 123456, 64, strength, layers)
                # Compute the number of errors
                n_errors = len([x for x, y in zip(data, retrieved) if x != y])
                # Write the results to a file 
                output.write("NOISE, " + str(strength) + ", " + str(layers) + ", " + str(amplitude) + ", " + str(n_errors) + ";\n")
                output.flush()
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)
    delaunay = pymesh.is_delaunay(mesh)
    mesh.add_attribute("delaunay")
    mesh.set_attribute("delaunay", delaunay)

    strictly_delaunay = np.count_nonzero(delaunay > 0)
    cospherical = np.count_nonzero(delaunay == 0)
    not_delaunay = np.count_nonzero(delaunay < 0)

    print("Strictly Delaunay: {:10} ({:>6.3%})".format(
        strictly_delaunay,
        float(strictly_delaunay) / mesh.num_voxels))
    print("      Cospherical: {:10} ({:>6.3%})".format(
        cospherical,
        float(cospherical) / mesh.num_voxels))
    print("     Not Delaunay: {:10} ({:>6.3%})".format(
        not_delaunay,
        float(not_delaunay) / mesh.num_voxels))

    pymesh.save_mesh(args.output_mesh, mesh, "delaunay")
Exemple #48
0
def mesh_object(fnstl, fnstep, fnout):
    print("Importing %s..." % (fnstl))
    mesh = pymesh.load_mesh(fnstl)
    log_mesh(mesh, "Imported mesh")
    mesh = fix_mesh(mesh)
    mv = []
    for v in mesh.vertices:
        mv.append(Vector(tuple(v)))
    obj = import_step_file(fnstep)
    edges = obj.edges().vals()
    log_mesh(mesh, msg="Imported STEP", edges=edges)

    print("  Discretizing edges...")
    edges = discretize_all_edges(edges,
                                 curve_res=CURVE_RES,
                                 circle_res=CIRCLE_RES,
                                 as_pts=True)
    log_mesh(mesh, edges=edges)

    vertices = np.array(mesh.vertices)
    epts = []
    for e in edges:
        e0 = list(e[0])
        e1 = list(e[1])
        p0 = tuple(vertices[spatial.distance.cdist([e0], vertices).argmin()])
        p1 = tuple(vertices[spatial.distance.cdist([e1], vertices).argmin()])
        p0 = p0 if abs(Vector(p0) - Vector(tuple(e0))) < 0.2 else e0
        p1 = p1 if abs(Vector(p1) - Vector(tuple(e1))) < 0.2 else e1
        epts.append((p0, p1))

    log_mesh(mesh, edges=epts)
    ldr_obj = mesh_to_ldr(mesh.faces, mv, LDR_DEF_COLOUR, epts, LDR_OPT_COLOUR)
    hs = ldr_header(fnout, prefix="FxTrack")
    f = open(fnout, "w")
    f.write(hs)
    f.write(ldr_obj)
    f.write("0 NOFILE\n")
    f.close()
Exemple #49
0
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)

    pymesh.is_vertex_manifold(mesh)
    pymesh.is_edge_manifold(mesh)

    faces = mesh.faces
    edge_manifold = mesh.get_attribute("edge_manifold").reshape(
        (-3, mesh.vertex_per_face))
    is_edge_nonmanifold = np.any(edge_manifold == 0, axis=1)
    involved_faces = faces[is_edge_nonmanifold]
    mesh.add_attribute("faces_adj_nonmanifold_edge")
    mesh.set_attribute("faces_adj_nonmanifold_edge", is_edge_nonmanifold)

    print("Faces adjacent to nonmanifold edges")
    print("Indices: {}".format(np.arange(mesh.num_faces)[is_edge_nonmanifold]))
    print(involved_faces)
    pymesh.save_matrix("nonmanifold_edges.dmat", involved_faces)

    vertex_manifold = mesh.get_attribute("vertex_manifold").ravel()
    is_vertex_nonmanifold = np.any(vertex_manifold[faces] == 0, axis=1)
    involved_faces = faces[is_vertex_nonmanifold]
    mesh.add_attribute("faces_adj_nonmanifold_vertex")
    mesh.set_attribute("faces_adj_nonmanifold_vertex", is_vertex_nonmanifold)

    print("Faces adjacent to nonmanifold vertices")
    print("Indices: {}".format(
        np.arange(mesh.num_faces)[is_vertex_nonmanifold]))
    print(involved_faces)
    pymesh.save_matrix("nonmanifold_vertices.dmat", involved_faces)

    pymesh.save_mesh(args.output_mesh, mesh, *mesh.attribute_names)

    if args.debug_output is not None:
        debug_faces = faces[is_edge_nonmanifold]
        debug_mesh = pymesh.form_mesh(mesh.vertices, debug_faces)
        pymesh.save_mesh(args.debug_output, debug_mesh)
Exemple #50
0
def main():
    args = parse_args()

    numeric_level = getattr(logging, args.log, None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
    logging.basicConfig(level=numeric_level)
    logger = logging.getLogger("tet.py")

    mesh = pymesh.load_mesh(args.in_mesh)
    if mesh.vertex_per_face == 4:
        logger.info("Spliting quad mesh into triangle mesh")
        mesh = pymesh.quad_to_tri(mesh)

    tet_mesh, t = pymesh.tetrahedralize(mesh,
                                        args.cell_size,
                                        args.radius_edge_ratio,
                                        args.facet_distance,
                                        args.feature_angle,
                                        args.engine,
                                        with_timing=True)
    pymesh.save_mesh(args.out_mesh, tet_mesh)
    logger.info("Running time: {}".format(t))
def tile_with_guide_mesh(config):
    options = extract_options(config)
    network = load_wire(str(config["wire_network"]))
    parameters = load_parameters(network, config)
    guide_mesh = pymesh.load_mesh(config["guide_mesh"])

    tiler = Tiler()
    tiler.set_base_pattern(network)
    tiler.tile_with_guide_mesh(guide_mesh, parameters)
    network = tiler.wire_network

    if config.get("trim", False):
        network.trim()
    if "output_wire_network" in config:
        network.write_to_file(config["output_wire_network"])

    inflator = Inflator(network)
    inflator.subdivide_order = options["subdiv"]
    inflator.subdivide_method = options["subdiv_method"]
    inflator.inflate(
        network.get_attribute("thickness").ravel(),
        parameters.per_vertex_thickness)
    return inflator.mesh
Exemple #52
0
def main():
    args = parse_args()
    mesh = pymesh.load_mesh(args.input_mesh)
    if not mesh.has_attribute("corner_texture"):
        raise RuntimeError("Mesh contains no uv!")

    mesh.add_attribute("face_area")
    cutted_mesh = pymesh.cut_mesh(mesh)

    uvs = cutted_mesh.get_attribute("corner_texture").reshape((-1, 2))
    faces = cutted_mesh.faces
    per_vertex_uv = np.ndarray((cutted_mesh.num_vertices, 2))
    per_vertex_uv[faces.ravel(order="C")] = uvs

    if not args.save_uv:
        cutted_mesh.add_attribute("u")
        cutted_mesh.set_attribute("u", per_vertex_uv[:, 0])
        cutted_mesh.add_attribute("v")
        cutted_mesh.set_attribute("v", per_vertex_uv[:, 1])
        pymesh.save_mesh(args.output_mesh, cutted_mesh, "u", "v")
    else:
        uv_mesh = pymesh.form_mesh(per_vertex_uv, faces)
        pymesh.save_mesh(args.output_mesh, uv_mesh)
def get_trimesh(geometry_id):
    query = """query geometry($geometry_id: String!){
            geometry(geometryId: $geometry_id){
            signedUrl
        }
    }
    """

    variables = {"geometry_id": geometry_id}
    r = requests.post(url=base_storage_url,
                      json={
                          "query": query,
                          "variables": variables
                      })

    # TODO fix signedUrl
    # aquiring signedUrl
    mesh_url = r.json()["data"]["geometry"]["signedUrl"]
    test_url = mesh_url.split("/")
    mesh_name = test_url[4].split("?")[0]
    test_url = "https://storage.googleapis.com/" + test_url[3] + "/" + mesh_name
    new_url = "https://storage.googleapis.com/" + test_url

    # Check for correct file format
    file_format_in = new_url.split(".")[-1].lower()
    assert file_format_in in ["stl"], "Incorrect file format loaded"

    # Downloading uploaded mesh
    r = requests.get(test_url, stream=True, allow_redirects=True)

    temp_file = f"temp_render_mesh.{file_format_in}"
    with open(temp_file, "wb") as f:
        f.write(r.content)
    # io.BytesIO(r.content)
    trimesh = pymesh.load_mesh(temp_file)

    return trimesh, mesh_name
def remeshing_and_texture(reconstruction_dir):
    texture_mesh(reconstruction_dir, 0)
    print_header("Remeshing the model")
    length = 1.0
    while 1:
        print(
            "Trying to resize mesh and texture. Current edge collapse threshold "
            + str(length) + ".")
        start = time.time()
        mesh = pymesh.load_mesh(reconstruction_dir +
                                "/scene_dense_mesh_refine.ply")
        mesh, info = pymesh.collapse_short_edges(mesh,
                                                 rel_threshold=float(length))
        if len(mesh.vertices) > 1000 and length < 4:
            pymesh.save_mesh(
                reconstruction_dir + "/remesh_" + str(length) + ".ply", mesh)
            end = time.time()
            print("Elapsed time: %d sec" % (end - start) + "\n")
            texture_mesh(reconstruction_dir, length)
            length += 0.5
        else:
            print("Can't texture mapping on resized mesh with threshold " +
                  str(length) + "!")
            return -1
def tile_with_mixed_patterns(config):
    options = extract_options(config)
    options["dof_type"] = str(config.get("dof_type", "isotropic"))
    options["thickness_type"] = str(config.get("thickness_type", "vertex"))
    networks = load_wires(str(config["wire_list_file"]))
    guide_mesh = pymesh.load_mesh(config["guide_mesh"])
    per_vertex_thickness = options["thickness_type"] == "vertex"

    tiler = Tiler()
    tiler.tile_with_mixed_patterns(mesh, per_vertex_thickness,
                                   options["dof_type"] == "isotropic")
    network = tiler.wire_network

    if config.get("trim", False):
        network.trim()
    if "output_wire_network" in config:
        network.write_to_file(config["output_wire_network"])

    inflator = Inflator(network)
    inflator.subdivide_order = options["subdiv"]
    inflator.subdivide_method = options["subdiv_method"]
    inflator.inflate(
        network.get_attribute("thickness").ravel(), per_vertex_thickness)
    return inflator.mesh
Exemple #56
0
def compute_metrics():
    """
        Calculate all metrics of all meshes in folder toAnalyse/, put them into a dataframes object
         and save it as metrics.csv in toAnalyse folder
        :return:
    """
    colList = ['Name', 'Length', 'Surface', 'Volume', 'Hull Volume', 'Hull Ratio',
               'Average Distance', 'CVD', 'Open Angle', 'Mean Curvature', 'Variance Curvature',
               'Mean Gaussian', 'Variance Gaussian', 'Highest Curvature', 'Lowest Curvature',
               'Lowest Gaussian', 'Highest Gaussian']
    df = pd.DataFrame(columns=colList)
    for (dirpath, _, filenames) in os.walk("toAnalyse/"):
        for filename in filenames:
            if filename != 'metrics.csv':
                mesh = pymesh.load_mesh(os.path.join(dirpath, filename))
                meanCurvature = calculate_mean_curvature(mesh)
                gaussianCurvature = calculate_gaussian_curvature(mesh)
                df2 = pd.DataFrame([{'Name': str(filename),
                                     'Length': spine_length(mesh),
                                     'Surface': mesh_surface(mesh),
                                     'Volume': mesh_volume(mesh),
                                     'Hull Volume': calculate_hull_volume(mesh),
                                     'Hull Ratio': calculate_hull_ratio(mesh),
                                     'Average Distance': average_distance(mesh),
                                     'CVD': coefficient_of_variation_in_distance(mesh),
                                     'Open Angle': open_angle(mesh),
                                     'Mean Curvature': meanCurvature[0],
                                     'Variance Curvature': meanCurvature[1],
                                     'Mean Gaussian': gaussianCurvature[0],
                                     'Variance Gaussian': gaussianCurvature[1],
                                     'Highest Curvature': meanCurvature[2],
                                     'Lowest Curvature': meanCurvature[3],
                                     'Lowest Gaussian': gaussianCurvature[2],
                                     'Highest Gaussian': gaussianCurvature[3]}])
                df = df.append(df2, ignore_index=True)
    df.to_csv('toAnalyse/metrics.csv')
Exemple #57
0
    def load_point_input(self, path):
        ext = path.split('.')[-1]
        if ext == "npy":
            points = np.load(path)
        elif ext == "ply" or ext == "obj":
            import pymesh
            points = pymesh.load_mesh(path).vertices
        else:
            print("invalid file extension")

        points = torch.from_numpy(points).float()
        operation = pointcloud_processor.Normalization(points, keep_track=True)
        if self.opt.normalization == "UnitBall":
            operation.normalize_unitL2ball()
        elif self.opt.normalization == "BoundingBox":
            operation.normalize_bounding_box()
        else:
            pass
        return_dict = {
            'points': points,
            'operation': operation,
            'path': path,
        }
        return return_dict
Exemple #58
0
#!/usr/bin/env python
import os
import pymesh

#os.listdir("/home")

nr = 0

for obj_file in os.listdir("/home/obj"):
    if obj_file.endswith(".obj"):
        #print(str(nr))
        mesh = pymesh.load_mesh("/home/obj/" + obj_file)
        pymesh.save_mesh("/home/off/" + str(nr) + ".off", mesh)
        nr = nr + 1
Exemple #59
0
            continue
        print("Number of vertices: {}".format(len(labels)))

        # pos_labels: points that pass the sc_filt.
        pos_labels = np.where(
            (labels > params["min_sc_filt"]) & (labels < params["max_sc_filt"])
        )[0]
        l = pos_labels
    else:
        l = []



    if len(l) > 0 and chain2 != "":
        ply_fn1 = masif_opts['ply_file_template'].format(pdbid, chain1)
        v1 = pymesh.load_mesh(ply_fn1).vertices[l]
        from sklearn.neighbors import NearestNeighbors

        ply_fn2 = masif_opts['ply_file_template'].format(pdbid, chain2 )
        v2 = pymesh.load_mesh(ply_fn2).vertices

        # For each point in v1, find the closest point in v2.
        nbrs = NearestNeighbors(n_neighbors=1, algorithm="ball_tree").fit(v2)
        d, r = nbrs.kneighbors(v1)
        d = np.squeeze(d, axis=1)
        r = np.squeeze(r, axis=1)

        # Contact points: those within a cutoff distance.
        contact_points = np.where(d < params["pos_interface_cutoff"])[0]
        if len(contact_points) > 0:
            k1 = l[contact_points]  # contact points protein 1
Exemple #60
0
    def __init__(self,
                 root_dir='/home/xiao/Datasets/MV_renderings/renderings',
                 input_dim=224,
                 bg_dir='/home/xiao/Datasets/SUN397_256',
                 bg_list='SUN_database.txt',
                 all_angles=True,
                 model_number=200,
                 annotation_file='annotation_all_texture.txt',
                 mode='RGB',
                 novel=False,
                 shape=None,
                 render_dir='Renders_semi_sphere',
                 render_number=12,
                 tour=2,
                 random_range=0,
                 cat_choice=None,
                 train=True,
                 mutated=False):
        self.root_dir = root_dir
        self.input_dim = input_dim
        self.all_angles = all_angles
        self.bg_dir = bg_dir
        self.bg_list = pd.read_csv(os.path.join(self.bg_dir, bg_list))
        self.shape = shape
        self.render_dir = render_dir
        self.mode = mode
        self.render_number = render_number
        self.tour = tour
        self.random_range = random_range
        self.train = train
        self.mutated = mutated

        # load the appropriate data frame for annotations
        frame = pd.read_csv(os.path.join(root_dir, annotation_file))
        if cat_choice is not None:
            if train:
                frame = frame[~frame.cat_id.isin(cat_choice
                                                 )] if novel else frame
            else:
                frame = frame[frame.cat_id.isin(cat_choice)]
        cats = np.unique(frame.cat_id)
        for i in range(0, len(cats)):
            frame_cat = frame[frame.cat_id == cats[i]]
            examples = list(np.unique(frame_cat.example_id))
            if len(examples) > model_number:
                examples = examples[:model_number]
            if i == 0:
                new_frame = frame_cat[frame_cat.example_id.isin(examples)]
            else:
                new_frame = pd.concat([
                    new_frame, frame_cat[frame_cat.example_id.isin(examples)]
                ])
        self.annotation_frame = new_frame

        # define data augmentation and preprocessing for RGB images
        im_augmentation = transforms.Compose([
            transforms.ColorJitter(brightness=0.5,
                                   contrast=0.5,
                                   saturation=0.5),
            transforms.RandomCrop(224)
        ])
        im_transform = transforms.CenterCrop(224)
        if input_dim != 224:
            im_augmentation = transforms.Compose(
                [im_augmentation,
                 transforms.Resize(input_dim)])
            im_transform = transforms.Compose(
                [im_transform, transforms.Resize(input_dim)])
        self.im_augmentation = transforms.Compose(
            [im_augmentation,
             transforms.ToTensor(), normalize, disturb])
        self.im_transform = transforms.Compose(
            [im_transform, transforms.ToTensor(), normalize])

        # define data preprocessing for rendered images
        self.render_path = 'crop' if mode == 'RGB' else 'normal_depth_crop'
        self.render_transform = transforms.ToTensor()
        if input_dim != 224:
            self.render_transform = transforms.Compose(
                [transforms.Resize(input_dim),
                 transforms.ToTensor()])

        if shape == 'PointCloud':
            # Load the point clouds
            import pymesh
            self.point_clouds = {}
            point_cloud_path = join(self.root_dir, "CAD/sampledPCinfRay/")
            for filename in glob.iglob(join(point_cloud_path, '**/*.ply'),
                                       recursive=True):
                category = basename(os.path.dirname(filename))
                idx = int(basename(filename).split(sep=".")[0])
                vertices = pymesh.load_mesh(filename).vertices
                if category in self.point_clouds:
                    self.point_clouds[category][idx] = vertices
                else:
                    self.point_clouds[category] = {idx: vertices}