Ejemplo n.º 1
0
    def estimateAverageTransform(self):
        targets = glob.glob(self.file_path + "*left.ply")
        sources = glob.glob(self.file_path + "*right.ply")
        assert len(sources) == len(targets)
        transform_list = []
        for i in range(len(sources)):
            tran = (self.estimateTransform(sources[i], targets[i]))
            transform_list.append(tran)
            if np.linalg.norm(self.base_transform - tran) < 0.1:
                self.base_transform = tran

        # estimate good average transform
        # avg_transformation = self.base_transform

        avg_transformation = np.mean(transform_list, axis=0)
        print(avg_transformation)
        # print(transform_list)

        # display final result
        for i in range(len(transform_list) - 1):
            source = od.read_point_cloud(sources[i])
            target = od.read_point_cloud(targets[i])
            self.draw_registration_result_original_color(
                source, target, avg_transformation)
        np.save(self.file_path + "transform", avg_transformation)
        print(avg_transformation)
Ejemplo n.º 2
0
    def estimateTransform(self, source, target):
        source = od.read_point_cloud(source)
        target = od.read_point_cloud(target)
        current_transformation = self.base_transform

        for scale in range(len(self.voxel_radius)):
            iterations = self.max_iter[scale]
            radius = self.voxel_radius[scale]

            source_down = od.voxel_down_sample(source, radius)
            target_down = od.voxel_down_sample(target, radius)

            od.estimate_normals(
                source_down,
                od.KDTreeSearchParamHybrid(radius=2 * radius,
                                           max_nn=self.max_nn))
            od.estimate_normals(
                target_down,
                od.KDTreeSearchParamHybrid(radius=2 * radius,
                                           max_nn=self.max_nn))

            result_icp = od.registration_colored_icp(
                source_down, target_down, radius, current_transformation,
                od.ICPConvergenceCriteria(
                    relative_fitness=self.relative_fitness,
                    relative_rmse=self.relative_rmse,
                    max_iteration=iterations))

            current_transformation = result_icp.transformation
            # self.draw_registration_result_original_color(
            # source_down, target_down, current_transformation)

        return current_transformation
Ejemplo n.º 3
0
    def NonFirstCloud(self, cloud_index):
        self.cloud1 = o3d.read_point_cloud(
            r"C:\Users\newsmart\Desktop\NSTAlgo\3D\PCL\stitch\2\2-{}_Extract.ply".format(cloud_index - 1))
        self.cloud2 = o3d.read_point_cloud(
            r"C:\Users\newsmart\Desktop\NSTAlgo\3D\PCL\stitch\2\2-{}_Extract.ply".format(cloud_index))

        # get local transformation between two lastest clouds
        self.posLocalTrans = self.registerLocalCloud(self.cloud1, self.cloud2)

        # if result is not good, drop it
        if self.goodResultFlag:
            # test for loop detection info
            self.detectTransLoop = np.dot(self.posLocalTrans, self.detectTransLoop)
            # print ("==== loop detect trans ====")
            # print(self.detectTransLoop)
            # print ("==== ==== ==== ==== ==== ====")
            self.posWorldTrans = np.dot(self.posWorldTrans, self.posLocalTrans)
            # update latest cloud
            self.cloud1 = copy.deepcopy(self.cloud2)
            self.cloud2.transform(self.posWorldTrans)
            o3d.write_point_cloud(r"C:\Users\newsmart\Desktop\NSTAlgo\3D\PCL\stitch\2\test.ply",
                                  self.cloud2, write_ascii=False)
            self.cloud_base = self.cloud_base + self.cloud2

            # Down Sampling
            self.cloud_base = o3d.voxel_down_sample(self.cloud_base, 0.001)

            self.registrationCount += 1
            # save PCD file to local
            o3d.write_point_cloud(r"C:\Users\newsmart\Desktop\NSTAlgo\3D\PCL\stitch\2\registerResult.ply",
                                  self.cloud_base, write_ascii=False)
Ejemplo n.º 4
0
def main():

    argvs = sys.argv
    model_num = str(argvs[1])
    scene_num = str(argvs[2])
    cloud_dir = "/mnt/container-data/remove_plane/"

    model_path = cloud_dir + model_num + ".ply"
    model_cloud = o3.read_point_cloud(model_path)

    scene_path = cloud_dir + scene_num + ".ply"
    scene_cloud = o3.read_point_cloud(scene_path)

    rot_in = read_rotation(model_num)
    model_cloud.transform(rot_in)

    model_cloud = o3.voxel_down_sample(model_cloud, voxel_size=0.020)
    scene_cloud = o3.voxel_down_sample(scene_cloud, voxel_size=0.020)

    # 基準とするpointcloud, 回転させたいpointcloud の順番
    cbs = [callbacks.Open3dVisualizerCallback(model_cloud, scene_cloud)]
    objective_type = 'pt2pt'

    # 基準とするpointcloud, 回転させたいpointcloud の順番
    tf_param, _, _ = filterreg.registration_filterreg(
        model_cloud,
        scene_cloud,
        scene_cloud.normals,
        objective_type=objective_type,
        sigma2=sig,
        callbacks=cbs,
        maxiter=ter,
        tol=ol)

    write_rotation(tf_param, scene_num)
def rabbit_dataset():
    A1 = o3d.read_point_cloud("./bunny/data/bun000.ply")
    A2 = o3d.read_point_cloud("./bunny/data/bun045.ply")
    A3 = o3d.read_point_cloud("./bunny/data/bun090.ply")
    A4 = o3d.read_point_cloud("./bunny/data/bun180.ply")
    A5 = o3d.read_point_cloud("./bunny/data/bun270.ply")
    A6 = o3d.read_point_cloud("./bunny/data/bun315.ply")
    A7 = o3d.read_point_cloud("./bunny/data/chin.ply")
    A8 = o3d.read_point_cloud("./bunny/data/ear_back.ply")
    A9 = o3d.read_point_cloud("./bunny/data/top2.ply")
    A10 = o3d.read_point_cloud("./bunny/data/top3.ply")
    return [A1, A2, A3, A4, A5, A6, A7, A8, A9]
Ejemplo n.º 6
0
def point_cloud_txt_to_pcd(raw_dir, file_prefix):
    # File names
    txt_file = os.path.join(raw_dir, file_prefix + ".txt")
    pts_file = os.path.join(raw_dir, file_prefix + ".pts")
    pcd_file = os.path.join(raw_dir, file_prefix + ".pcd")

    # Skip if already done
    if os.path.isfile(pcd_file):
        print("pcd {} exists, skipped".format(pcd_file))
        return

    # .txt to .pts
    # We could just prepend the line count, however, there are some intensity value
    # which are non-integers.
    print("[txt->pts]")
    print("txt: {}".format(txt_file))
    print("pts: {}".format(pts_file))
    with open(txt_file, "r") as txt_f, open(pts_file, "w") as pts_f:
        for line in txt_f:
            # x, y, z, i, r, g, b
            tokens = line.split()
            tokens[3] = str(int(float(tokens[3])))
            line = " ".join(tokens)
            pts_f.write(line + "\n")
    prepend_line(pts_file, str(wc(txt_file)))

    # .pts -> .pcd
    print("[pts->pcd]")
    print("pts: {}".format(pts_file))
    print("pcd: {}".format(pcd_file))
    point_cloud = open3d.read_point_cloud(pts_file)
    open3d.write_point_cloud(pcd_file, point_cloud)
Ejemplo n.º 7
0
def _calculate_num_points_in_gt(data_path,
                                infos,
                                remove_outside=True,
                                num_features=4):
    for info in infos:
        pc_info = info["point_cloud"]
        v_path = pc_info["velodyne_path"]
        if True:
            pcd = open3d.read_point_cloud(v_path)
            points_v = np.asarray(pcd.points).astype(np.float32)

        #points_v = np.fromfile(
        #    v_path, dtype=np.float32, count=-1).reshape([-1, num_features])

        # points_v = points_v[points_v[:, 0] > 0]
        annos = info['annos']
        num_obj = len(
            annos['name'])  #len([n for n in annos['name'] if n != 'DontCare'])
        # annos = kitti.filter_kitti_anno(annos, ['DontCare'])
        gt_boxes = np.array(annos['boxes'], dtype=np.float32)

        #gt_boxes_camera = np.concatenate([loc, dims, rots[..., np.newaxis]],
        #                                 axis=1)
        #gt_boxes_lidar = box_np_ops.box_camera_to_lidar(
        #    gt_boxes_camera, rect, Trv2c)
        indices = box_np_ops.points_in_rbbox(points_v, gt_boxes)
        num_points_in_gt = indices.sum(0)
        #num_ignored = len(annos['dimensions']) - num_obj
        #num_points_in_gt = np.concatenate(
        #    [num_points_in_gt, -np.ones([num_ignored])])
        annos["num_points_in_gt"] = num_points_in_gt.astype(np.int32)
        pass
Ejemplo n.º 8
0
def run_static_pointcloud_visualization():
    import open3d, os
    vis_path = os.path.dirname(__file__)
    cloud_path = os.path.join(vis_path, 'data/bunny.pcd')
    pcd = open3d.read_point_cloud(cloud_path)
    pcd_np = np.asarray(pcd.points)
    MeshCatVisualizer.draw_pointcloud(pcd_np)
Ejemplo n.º 9
0
def down_sample(dense_pcd_path, dense_label_path, sparse_pcd_path,
                sparse_label_path, voxel_size):
    # Skip if done
    if os.path.isfile(sparse_pcd_path) and (
            not os.path.isfile(dense_label_path)
            or os.path.isfile(sparse_label_path)):
        print("Skipped:", file_prefix)
        return
    else:
        print("Processing:", file_prefix)

    # Inputs
    dense_pcd = open3d.read_point_cloud(dense_pcd_path)
    try:
        dense_labels = load_labels(dense_label_path)
    except:
        dense_labels = None

    # Skip label 0, we use explicit frees to reduce memory usage
    print("Num points:", np.asarray(dense_pcd.points).shape[0])
    if dense_labels is not None:
        non_zero_indexes = dense_labels != 0

        dense_points = np.asarray(dense_pcd.points)[non_zero_indexes]
        dense_pcd.points = open3d.Vector3dVector()
        dense_pcd.points = open3d.Vector3dVector(dense_points)
        del dense_points

        dense_colors = np.asarray(dense_pcd.colors)[non_zero_indexes]
        dense_pcd.colors = open3d.Vector3dVector()
        dense_pcd.colors = open3d.Vector3dVector(dense_colors)
        del dense_colors

        dense_labels = dense_labels[non_zero_indexes]
        print("Num points after 0-skip:",
              np.asarray(dense_pcd.points).shape[0])

    # Downsample points
    min_bound = dense_pcd.get_min_bound() - voxel_size * 0.5
    max_bound = dense_pcd.get_max_bound() + voxel_size * 0.5

    sparse_pcd, cubics_ids = open3d.voxel_down_sample_and_trace(
        dense_pcd, voxel_size, min_bound, max_bound, False)
    print("Num points after down sampling:",
          np.asarray(sparse_pcd.points).shape[0])

    open3d.write_point_cloud(sparse_pcd_path, sparse_pcd)
    print("Point cloud written to:", sparse_pcd_path)

    # Downsample labels
    if dense_labels is not None:
        sparse_labels = []
        for cubic_ids in cubics_ids:
            cubic_ids = cubic_ids[cubic_ids != -1]
            cubic_labels = dense_labels[cubic_ids]
            sparse_labels.append(np.bincount(cubic_labels).argmax())
        sparse_labels = np.array(sparse_labels)

        write_labels(sparse_label_path, sparse_labels)
        print("Labels written to:", sparse_label_path)
Ejemplo n.º 10
0
 def load_ply(self, data_dir, ind, downsample, aligned=True):
     pcd = open3d.read_point_cloud(join(data_dir, f'{ind}.ply'))
     pcd = open3d.voxel_down_sample(pcd, voxel_size=downsample)
     if aligned is True:
         matrix = np.load(join(data_dir, f'{ind}.pose.npy'))
         pcd.transform(matrix)
     return pcd
Ejemplo n.º 11
0
def read_point_cloud():
    """
    Read Open3d point clouds and covnert to Houdini geometry

    Based on http://www.open3d.org/docs/tutorial/Basic/working_with_numpy.html
    """
    node = hou.pwd()
    node_geo = node.geometry()
    path = node.parm("path").eval()
    
    pcd_load = open3d.read_point_cloud(path)
    
    if not pcd_load.has_points():
        raise hou.NodeWarning("Geometry does not contain any points.")

    # create numpy arrays
    np_pos = np.asarray(pcd_load.points)
    np_n = np.asarray(pcd_load.normals)
    np_cd = np.asarray(pcd_load.colors)

    # position
    node_geo.createPoints(np_pos)

    # normals
    if pcd_load.has_normals():
        node_geo.addAttrib(hou.attribType.Point, "N", default_value=(0.0, 0.0, 0.0), transform_as_normal=True, create_local_variable=False)
        node_geo.setPointFloatAttribValuesFromString("N", np_n, float_type=hou.numericData.Float64)
    
    # colors
    if pcd_load.has_colors():
        node_geo.addAttrib(hou.attribType.Point, "Cd", default_value=(0.0, 0.0, 0.0), transform_as_normal=False, create_local_variable=False)
        node_geo.setPointFloatAttribValuesFromString("Cd", np_cd, float_type=hou.numericData.Float64)
Ejemplo n.º 12
0
    def __init__(self, root, intance_num, trans_by_pose=None):
        # trans_by_pose: <Bx3> pose
        self.root = os.path.expanduser(root)
        self._trans_by_pose = trans_by_pose
        file_list = glob.glob(os.path.join(self.root, '*pcd'))
        self.file_list = sorted(file_list)  #[:intance_num]

        self.pcds = []  # a list of open3d pcd objects
        point_clouds = []  #a list of tensor <Lx2>
        for file in self.file_list:
            pcd = read_point_cloud(file)
            self.pcds.append(pcd)

            current_point_cloud = np.asarray(pcd.points, dtype=np.float32)[:,
                                                                           0:2]
            point_clouds.append(current_point_cloud)

        point_clouds = np.asarray(point_clouds)
        self.point_clouds = torch.from_numpy(point_clouds)  # <NxLx2>

        self.valid_points = find_valid_points(self.point_clouds)  # <NxL>

        # number of points in each point cloud
        self.n_obs = 256

        self.indeces = range(256)
Ejemplo n.º 13
0
    def create_object_masks(self,
                            object_name,
                            session_name,
                            dilate_size=15,
                            show=False):
        logger = logging.getLogger(__name__)
        # DEPRECATED: use generate_object_masks.py instead
        # TODO: Bug: no mask for excluded views, because their segmented object
        # is not saved
        base_dir = osp.join(self.data_dir, session_name, object_name)
        pc_dir = osp.join(base_dir, 'pointclouds')

        # thermal camera info
        thermal_dir = osp.join(base_dir, 'thermal_images')
        thermal_im_size, thermal_K = self._load_thermal_cinfo(thermal_dir)

        _, _, pc_filenames = os.walk(pc_dir).next()
        done = True
        for pc_filename in pc_filenames:
            if 'segmented_object' not in pc_filename:
                continue
            view_id = pc_filename.split('_')[0]

            pc_filename = osp.join(pc_dir, pc_filename)
            xyz_kinect = open3d.read_point_cloud(pc_filename)
            xyz_kinect = np.asarray(xyz_kinect.points).T

            xyz_thermal = np.dot(
                np.linalg.inv(self.T_rgb_t),
                np.vstack((xyz_kinect, np.ones(xyz_kinect.shape[1]))))

            uv_thermal = np.dot(thermal_K, xyz_thermal[:3])
            uv_thermal = uv_thermal[:2] / uv_thermal[2]
            uv_thermal = np.round(uv_thermal).astype(np.int)
            idx = np.logical_and(
                uv_thermal >= 0, uv_thermal < np.asarray(
                    [thermal_im_size[0], thermal_im_size[1]])[:, np.newaxis])
            idx = np.logical_and(*idx)
            uv_thermal = uv_thermal[:, idx]

            mask = np.zeros((thermal_im_size[1], thermal_im_size[0]))
            mask[uv_thermal[1], uv_thermal[0]] = 1

            if show:
                plt.figure()
                plt.imshow(mask)
                plt.show()

            mask_filename = '{:s}_mask.png'.format(view_id)
            mask_filename = osp.join(thermal_dir, mask_filename)
            mask = (mask * 255).astype(np.uint8)
            kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
                                               (dilate_size, dilate_size))
            mask = cv2.dilate(mask, kernel)
            done = done and cv2.imwrite(mask_filename, mask)
            if not done:
                logger.error(
                    '### WARN: Could not write {:s}'.format(mask_filename))

        return done
Ejemplo n.º 14
0
    def __init__(self, file_path_without_ext, has_label, use_color, box_size_x,
                 box_size_y):
        """
        Loads file data
        """
        self.file_path_without_ext = file_path_without_ext
        self.box_size_x = box_size_x
        self.box_size_y = box_size_y

        # Load points
        pcd = open3d.read_point_cloud(file_path_without_ext + ".pcd")
        self.points = np.asarray(pcd.points)

        # Load label. In pure test set, fill with zeros.
        if has_label:
            self.labels = load_labels(file_path_without_ext + ".labels")
        else:
            self.labels = np.zeros(len(self.points)).astype(bool)

        # Load colors. If not use_color, fill with zeros.
        if use_color:
            self.colors = np.asarray(pcd.colors)
        else:
            self.colors = np.zeros_like(self.points)

        # Sort according to x to speed up computation of boxes and z-boxes
        sort_idx = np.argsort(self.points[:, 0])
        self.points = self.points[sort_idx]
        self.labels = self.labels[sort_idx]
        self.colors = self.colors[sort_idx]
Ejemplo n.º 15
0
def visualize_scene_keypoint(annotation_dict, keypoint_name_list: List[str]):
    # Get all the keypoint
    keypoint_3d_position: List[List[float]] = []
    annotation_keypoints_dict = annotation_dict['keypoints']
    for keypoint_name in keypoint_name_list:
        assert keypoint_name in annotation_keypoints_dict
        keypoint_pos = annotation_keypoints_dict[keypoint_name]['position']
        keypoint_3d_position.append([
            float(keypoint_pos[0]),
            float(keypoint_pos[1]),
            float(keypoint_pos[2])
        ])

    # Get the scene root and ply file
    assert 'scene_name' in annotation_dict
    scene_name: str = annotation_dict['scene_name']
    scene_root_path = os.path.join(args.log_root_path, scene_name)
    scene_processed_path = os.path.join(scene_root_path, 'processed')
    fusion_mesh_path: str = os.path.join(scene_processed_path,
                                         'fusion_mesh.ply')
    assert os.path.exists(fusion_mesh_path)

    # Get the open3d point cloud and draw it
    point_cloud = open3d.read_point_cloud(fusion_mesh_path)
    n_keypoint: int = len(keypoint_3d_position)
    if args.one_by_one:
        for i in range(n_keypoint):
            draw_single_keypoint(point_cloud, keypoint_3d_position[i])
    else:
        keypoint_np = np.zeros(shape=[3, n_keypoint])
        for i in range(n_keypoint):
            keypoint_np[0, i] = keypoint_3d_position[i][0]
            keypoint_np[1, i] = keypoint_3d_position[i][1]
            keypoint_np[2, i] = keypoint_3d_position[i][2]
        draw_all_keypoints(point_cloud, keypoint_np)
Ejemplo n.º 16
0
def cb_load(msg):
  global Model,tfReg
#load point cloud
  for n,l in enumerate(Config["scenes"]):
    pcd=o3d.read_point_cloud(Config["path"]+"/"+l+".ply")
    Model[n]=np.reshape(np.asarray(pcd.points),(-1,3))
  rospy.Timer(rospy.Duration(Config["tf_delay"]),cb_master,oneshot=True)
  tfReg=[]
#load TF such as master/camera...
  for n,m in enumerate(Config["master_frame_id"]):
    path=Config["path"]+"/"+m.replace('/','_')+".yaml"
    try:
      f=open(path, "r+")
    except Exception:
      pub_msg.publish("searcher::file error "+path)
    else:
      yd=yaml.load(f)
      f.close()
      trf=tflib.dict2tf(yd)
      tf=TransformStamped()
      tf.header.stamp=rospy.Time.now()
      tf.header.frame_id="world"
      tf.child_frame_id=m
      tf.transform=trf
      print "world->",m
      print trf
      tfReg.append(tf)
  broadcaster.sendTransform(tfReg)
  Param.update(rospy.get_param("~param"))
  solver.learn(Model,Param)
  pub_msg.publish("searcher::model learning completed")
Ejemplo n.º 17
0
    def load_full_scan(self, file_path, cfg):
        print('file_path', file_path)
        self.pc = open3d.read_point_cloud(
            os.path.join(file_path, "sampled_points.ply"))

        file_names = dict()
        file_names['output_tetrahedron_adj'] = (os.path.join(
            file_path, "output_tetrahedron_adj"))
        file_names['output_cell_vertex_idx'] = (os.path.join(
            file_path, "output_cell_vertex_idx.txt"))
        file_names['ref_label'] = (os.path.join(file_path,
                                                "ref_point_label.txt"))

        l = dict()
        l['ref_label'] = np.fromfile(file_names['ref_label'],
                                     dtype=np.int32,
                                     sep=' ').reshape(-1, 7)
        l['adj_mat'] = np.fromfile(file_names['output_tetrahedron_adj'],
                                   dtype=np.int32,
                                   sep=' ').reshape(-1, 4)
        l['cell_vertex_idx'] = np.fromfile(
            file_names['output_cell_vertex_idx'], dtype=np.int32,
            sep=' ').reshape(-1, 4)

        self.cell_vertex_idx = (l['cell_vertex_idx'])
        self.adj = l['adj_mat']
        self.ref_label = l['ref_label'][:, 0:cfg["ref_num"]]
        print("loaded " + file_path.split('/')[-2])
Ejemplo n.º 18
0
def testing():
    f = r'/home/clh/git/compile/Open3D/src/Test/TestData/fragment.ply'

    print("Load a ply point cloud, print it, and render it")
    pcd = open3d.read_point_cloud(f)
    print(pcd)
    print(np.asarray(pcd.colors).shape)
Ejemplo n.º 19
0
def main():
    keypoint_path: str = args.keypoint_yaml_path
    keypoint_datamap = None
    with open(keypoint_path, 'r') as file:
        try:
            keypoint_datamap = yaml.load(file)
        except yaml.YAMLError as exc:
            print(exc)
            exit(-1)

    # Process the map
    assert keypoint_datamap is not None
    mesh_path: str = keypoint_datamap['mesh_path']
    keypoint_index: List[int] = keypoint_datamap['keypoint_index']
    keypoint_3d_position: List[
        List[float]] = keypoint_datamap['keypoint_world_position']
    pcd = open3d.read_point_cloud(mesh_path)

    # Depends on visualization type
    if args.one_by_one:
        for i in range(len(keypoint_index)):
            draw_single_keypoint(pcd, keypoint_3d_position[i])
    else:
        n_keypoint = len(keypoint_3d_position)
        keypoint_np = np.zeros(shape=[3, n_keypoint])
        for i in range(n_keypoint):
            keypoint_np[0, i] = keypoint_3d_position[i][0]
            keypoint_np[1, i] = keypoint_3d_position[i][1]
            keypoint_np[2, i] = keypoint_3d_position[i][2]
        draw_all_keypoints(pcd, keypoint_np)
Ejemplo n.º 20
0
def prepare_source_and_target_rigid_3d(source_filename,
                                       noise_amp=0.001,
                                       n_random=500,
                                       orientation=np.deg2rad([0.0, 0.0,
                                                               30.0]),
                                       normals=False):
    source = o3.read_point_cloud(source_filename)
    source = o3.voxel_down_sample(source, voxel_size=0.005)
    print(source)
    target = copy.deepcopy(source)
    tp = np.asarray(target.points)
    rg = 1.5 * (tp.max(axis=0) - tp.min(axis=0))
    rands = (np.random.rand(n_random, 3) - 0.5) * rg + tp.mean(axis=0)
    target.points = o3.Vector3dVector(
        np.r_[tp + noise_amp * np.random.randn(*tp.shape), rands])
    ans = trans.euler_matrix(*orientation)
    target.transform(ans)
    if normals:
        o3.estimate_normals(source,
                            search_param=o3.geometry.KDTreeSearchParamHybrid(
                                radius=0.1, max_nn=50))
        o3.orient_normals_to_align_with_direction(source)
        o3.estimate_normals(target,
                            search_param=o3.geometry.KDTreeSearchParamHybrid(
                                radius=0.1, max_nn=50))
        o3.orient_normals_to_align_with_direction(target)
    return source, target
Ejemplo n.º 21
0
 def setUp(self):
     pcd = o3.read_point_cloud('data/horse.ply')
     pcd = o3.voxel_down_sample(pcd, voxel_size=0.01)
     self._source = np.asarray(pcd.points)
     rot = trans.euler_matrix(*np.random.uniform(0.0, np.pi / 4, 3))
     self._tf = tf.RigidTransformation(rot[:3, :3], np.zeros(3))
     self._target = self._tf.transform(self._source)
Ejemplo n.º 22
0
def ViewPLY(path):
    # 読み込み
    pointcloud = open3d.read_point_cloud(path)

    # ダウンサンプリング
    # 法線推定できなくなるので不採用
    pointcloud = open3d.voxel_down_sample(pointcloud, 10)

    # 法線推定
    open3d.estimate_normals(pointcloud,
                            search_param=open3d.KDTreeSearchParamHybrid(
                                radius=20, max_nn=30))

    # 法線の方向を視点ベースでそろえる
    open3d.orient_normals_towards_camera_location(pointcloud,
                                                  camera_location=np.array(
                                                      [0., 10., 10.],
                                                      dtype="float64"))

    # 可視化
    open3d.draw_geometries([pointcloud])

    # numpyに変換
    points = np.asarray(pointcloud.points)
    normals = np.asarray(pointcloud.normals)

    print("points:{}".format(points.shape[0]))

    X, Y, Z = Disassemble(points)

    # OBB生成
    _, _, length = buildOBB(points)
    print("OBB_length: {}".format(length))

    return points, X, Y, Z, normals, length
Ejemplo n.º 23
0
def test_ball_query():
    pc = torch.from_numpy(
        np.asarray(opend.read_point_cloud("test_pc.ply").points)).unsqueeze(
            0).float().cuda()
    centroids = torch.from_numpy(np.load('centroids.npy')).cuda()
    new_xyz = index_points(pc, centroids)
    ball_query(0.1, 32, pc, new_xyz)
def load_cloud(cloud_loc: os.path):
    if os.path.isfile(cloud_loc):
        point_cloud = open3d.read_point_cloud(cloud_loc)
        points = np.asarray(point_cloud.points)
        points = np.reshape(points, (240, 320, 3)).astype(np.float32)
        return points
    else:
        return np.zeros((240, 320, 3), dtype=np.float32)
Ejemplo n.º 25
0
    def compare_with_room(self):
        pc_room = o3.read_point_cloud('static_data/room_A.ply')
        pcd = self.get_pcd()

        P = np.loadtxt('static_data/T.csv', delimiter=',')
        pcd.transform(P)

        o3.draw_geometries([pc_room, pcd])
Ejemplo n.º 26
0
def cb_step1(ev):
  global sceneDat
  print "Step1/take a scene"
  sceneDat=solver.toNumpy(o3d.read_point_cloud(Args["scene"]))
  P=copy.deepcopy(sceneDat)
  pub_scene.publish(np2F(P))
  pub_model.publish(np2F(P0()))
  rospy.Timer(rospy.Duration(5), cb_step2, oneshot=True)
Ejemplo n.º 27
0
def cb_load_ply(msg):
    global outPn
    pcd = o3d.read_point_cloud(Args["wd"] + "/sample.ply")
    outPn = np.reshape(np.asarray(pcd.points), (-1, 3))
    pub.publish(np2F(outPn))
    f = Bool()
    f.data = True
    pub_ld.publish(f)
Ejemplo n.º 28
0
def readFiles(args):
    pc = open3d.read_point_cloud(args.pcfile1)
    v1 = np.asarray(pc.points)
    pc = open3d.read_point_cloud(args.pcfile2)
    v2 = np.asarray(pc.points)
    vertices = [v1, v2]
    if args.labelfile1 != "" and args.labelfile2 != "":
        l1 = np.loadtxt(args.labelfile1, dtype=int)
        l2 = np.loadtxt(args.labelfile2, dtype=int)
    else:
        l1 = np.zeros(v1.shape[0])
        l2 = np.zeros(v2.shape[0])
    # shift labels:
    l1 -= l1.min()
    l2 -= l2.min()
    labels = [l1, l2]
    return vertices, labels
Ejemplo n.º 29
0
def load_ply_as_pc(file_path: Union[str, Path]) -> op3.PointCloud:
    """
    Load a point cloud from a .ply file
    :param file_path: a string, path to the .ply file
    :return: a point cloud object of Open3D
    """
    point_cloud = op3.read_point_cloud(filename=path2str(file_path))
    return point_cloud
Ejemplo n.º 30
0
def parse_pcd_open3d(filename):
    """
    Parses a pcd file using Open3D
    :param filename: the file to be parsed
    :return: an open3d PointCloud class
    """
    pcd = open3d.read_point_cloud(filename)
    return pcd