PCL-Python の実行テスト

testsの中身

flydracyl.pcd                                test_kdtree.py        test_sampleconsensus.py
table_scene_mug_stereo_textured_noplane.pcd  test_keypoints.py     test_segmentation.py
test_features.py                             test_octree.py        test_surface.py
test_filters.py                              test_recognition.py   tutorials
test_io.py                                   test_registration.py

tests/test_features.py

In [4]:
import os
os.chdir('./python-pcl-master')  # 同じディレクトリに python-pcl-masterデイレクトリがあるとする
In [11]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np

from nose.plugins.attrib import attr


_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
           1.0, 2.0, 3.2;
           2.0, 4.0, 6.2;
           3.0, 6.0, 9.2;
           4.0, 8.0, 12.2"""

print(_data)

# features
### DifferenceOfNormalsEstimation ###
@attr('pcl_ver_0_4')
class TestDifferenceOfNormalsEstimation(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        # self.feat = pcl.DifferenceOfNormalsEstimation()

    def testException(self):
        # self.assertRaises(TypeError, pcl.DifferenceOfNormalsEstimation)
        pass


### IntegralImageNormalEstimation ###
@attr('pcl_ver_0_4')
class TestIntegralImageNormalEstimation(unittest.TestCase):
    def setUp(self):
        # self.p = pcl.PointCloud(_data)
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "table_scene_mug_stereo_textured.pcd")
        # self.feat = pcl.IntegralImageNormalEstimation(self.p)
        self.feat = self.p.make_IntegralImageNormalEstimation()

    # base : normal_estimation_using_integral_images.cpp
    # @unittest.skip
    def test_Tutorial(self):
        # before chack
        self.assertEqual(self.p.size, 307200)
        self.assertEqual(self.p.width, 640)
        self.assertEqual(self.p.height, 480)

        self.feat.set_NormalEstimation_Method_AVERAGE_3D_GRADIENT()
        self.feat.set_MaxDepthChange_Factor(0.02)
        self.feat.set_NormalSmoothingSize(10.0)
        # height = 1 pointdata set ng
        normals = self.feat.compute()
        # print(normals)

        # check - normals data
        # 1. return type
        # self.assertRaises(normals, pcl.PointCloud_Normal)
        # 2. point size
        # self.assertEqual(self.p.size, normals.size)

        # 3. same Tutorial data
        # size ->
        # self.assertEqual(self.p.size, normals.size)
        # for i in range(0, normals.size):
        #   print ('normal_x: '  + str(normals[i][0]) + ', normal_y : ' + str(normals[i][1])  + ', normal_z : ' + str(normals[i][2]))
        # print('end')


#     def test_set_NormalEstimation_Method_AVERAGE_3D_GRADIENT(self):
#         self.feat.set_NormalEstimation_Method_AVERAGE_3D_GRADIENT()
#         self.feat.setMaxDepthChangeFactor(0.02f)
#         self.feat.setNormalSmoothingSize(10.0)
#         f = self.feat.compute(self.p)
#
#         # check
#         # new instance is returned
#         # self.assertNotEqual(self.p, f)
#         # filter retains the same number of points
#         # self.assertEqual(self.p.size, f.size)
#
#
#     def test_set_NormalEstimation_Method_COVARIANCE_MATRIX(self):
#         self.feat.set_NormalEstimation_Method_COVARIANCE_MATRIX()
#         # f = self.feat.compute(self.p)
#
#         # check
#         # new instance is returned
#         # self.assertNotEqual(self.p, f)
#         # filter retains the same number of points
#         # self.assertEqual(self.p.size, f.size)
#
#     def test_set_NormalEstimation_Method_AVERAGE_DEPTH_CHANGE(self):
#         self.feat.set_NormalEstimation_Method_AVERAGE_DEPTH_CHANGE()
#         # f = self.feat.compute(self.p)
#
#         # check
#         # new instance is returned
#         # self.assertNotEqual(self.p, f)
#         # filter retains the same number of points
#         # self.assertEqual(self.p.size, f.size)
#
#     def test_set_NormalEstimation_Method_SIMPLE_3D_GRADIENT(self):
#         self.feat.set_NormalEstimation_Method_SIMPLE_3D_GRADIENT()
#         # f = self.feat.compute(self.p)
#
#         # check
#         # new instance is returned
#         # self.assertNotEqual(self.p, f)
#         # filter retains the same number of points
#         # self.assertEqual(self.p.size, f.size)
#
#     #
#     def test_set_MaxDepthChange_Factor(self):
#         param = 0.0
#         self.feat.set_MaxDepthChange_Factor(param)
#         # f = self.feat.compute(self.p)
#
#         # check
#         # new instance is returned
#         # self.assertNotEqual(self.p, f)
#         # filter retains the same number of points
#         # self.assertEqual(self.p.size, f.size)
#
#     def test_set_NormalSmoothingSize(self):
#         param = 5.0  # default 10.0
#         self.feat.set_NormalSmoothingSize(param)
#         # f = self.feat.compute(self.p)
#         # result point param?
#
#         # check
#         # new instance is returned
#         # self.assertNotEqual(self.p, f)
#         # filter retains the same number of points
#         # self.assertEqual(self.p.size, f.size)


### MomentOfInertiaEstimation ###
@attr('pcl_over_18')
class TestMomentOfInertiaEstimation(unittest.TestCase):
    def setUp(self):
        # self.p = pcl.PointCloud(_data)
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "lamppost.pcd")
        # 1.8.0
        # self.feat = pcl.MomentOfInertiaEstimation()
        self.feat = self.p.make_MomentOfInertiaEstimation()

    def test_Tutorials(self):
        self.feat.compute()

        # Get Parameters
        moment_of_inertia = self.feat.get_MomentOfInertia()
        eccentricity = self.feat.get_Eccentricity()
        [min_point_AABB, max_point_AABB] = self.feat.get_AABB()
        # [min_point_OBB, max_point_OBB, position_OBB, rotational_matrix_OBB] = self.feat.get_OBB ()
        [major_value, middle_value, minor_value] = self.feat.get_EigenValues()
        [major_vector, middle_vector, minor_vector] = self.feat.get_EigenVectors()
        mass_center = self.feat.get_MassCenter()

        # check parameter
        #print("%f %f %f.\n"%(mass_center (0), mass_center (1), mass_center (2)))
        print(mass_center)
        # -10.104160 0.074005 -2.144748.
        #print("%f %f %f.\n"%( major_vector (0), major_vector (1), major_vector (2)))
        print(major_vector)
        # 0.164287 -0.044990 -0.985386.
        #print("%f %f %f.\n"%( middle_vector (0), middle_vector (1), middle_vector (2)))
        print(middle_vector)
        # 0.920083 -0.353143 0.169523.
        #print("%f %f %f.\n"%(inor_vector (0), minor_vector (1), minor_vector (2)))
        print(minor_vector)
        # -0.355608 -0.934488 -0.016622.

        # expected = [-10.104160, 0.074005, -2.144748]
        expected = np.array([-10.104160, 0.074005, -2.144748])
        # print(str(mass_center[0][0].dtype))
        datas = np.around(mass_center[0].tolist(), decimals=6)
        # print("test : " + str(datas))
        self.assertEqual(datas.tolist(), expected.tolist())
        # self.assertEqual(datas, expected)

        expected2 = np.array([0.164287, -0.044990, -0.985386])
        datas = np.around(major_vector[0].tolist(), decimals=6)
        self.assertEqual(datas.tolist(), expected2.tolist())

        expected3 = np.array([0.920083, -0.353143, 0.169523])
        datas = np.around(middle_vector[0].tolist(), decimals=6)
        self.assertEqual(datas.tolist(), expected3.tolist())

        expected4 = np.array([-0.355608, -0.934488, -0.016622])
        datas = np.around(minor_vector[0].tolist(), decimals=6)
        self.assertEqual(datas.tolist(), expected4.tolist())


#     def test_get_MomentOfInertia(self):
#         param = self.feat.get_MomentOfInertia()
#
#     def test_get_Eccentricity(self):
#         param = self.feat.get_Eccentricity()
#
#     def test_get_AABB(self):
#         param = self.feat.get_AABB()
#
#     def test_get_EigenValues(self):
#         param = self.feat.get_EigenValues()


### NormalEstimation ###
class TestNormalEstimation(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        # self.feat = pcl.NormalEstimation()
        # self.feat.setInputCloud(selp.p)
        self.feat = self.p.make_NormalEstimation()

    def test_Tutorials_Radius(self):
        self.feat.set_RadiusSearch(0.03)
        normals = self.feat.compute()

        # check - normals data
        # 1. return type
        # self.assertEqual(type(normals), type(pcl.PointCloud_Normal))
        # 2. point size
        self.assertEqual(self.p.size, normals.size)

        # 3. same Tutorial data
        # size ->
        # self.assertEqual(self.p.size, normals.size)
        # for i in range(0, normals.size):
        #   print ('normal_x: '  + str(normals[i][0]) + ', normal_y : ' + str(normals[i][1])  + ', normal_z : ' + str(normals[i][2]))
        # print('end')

    def test_Tutorials_KSearch(self):
        tree = self.p.make_kdtree()
        self.feat.set_SearchMethod(tree)
        self.feat.set_KSearch(10)
        normals = self.feat.compute()
        # check - normals data
        # 1. return type
        # self.assertEqual(type(normals), type(pcl.PointCloud_Normal))
        # 2. point size is same
        self.assertEqual(self.p.size, normals.size)

        # 3. same Tutorial data
        # size ->
        # self.assertEqual(self.p.size, normals.size)
        # for i in range(0, normals.size):
        #   print ('normal_x: '  + str(normals[i][0]) + ', normal_y : ' + str(normals[i][1])  + ', normal_z : ' + str(normals[i][2]))
        # print('end')


### RangeImageBorderExtractor ###
@attr('pcl_ver_0_4')
class TestRangeImageBorderExtractor(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        # self.feat = pcl.RangeImageBorderExtractor()

    def test_set_RangeImage(self):
        # rangeImage = pcl.RangeImage()
        # self.feat.set_RangeImage(rangeImage)
        pass

    def test_ClearData(self):
        # self.feat.clearData ()
        pass


### VFHEstimation ###
class TestVFHEstimation(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        # self.feat = pcl.VFHEstimation()
        # self.feat.setInputCloud(self.p)
        self.feat = self.p.make_VFHEstimation()

    def test_set_SearchMethod(self):
        # kdTree = pcl.KdTree()
        # self.feat.set_SearchMethod(kdTree)
        # f = self.feat.compute()

        # new instance is returned
        # self.assertNotEqual(self.p, f)
        # filter retains the same number of points
        # self.assertEqual(self.p.size, f.size)
        pass

    def test_set_KSearch(self):
        param = 0.0
        # self.me.set_KSearch (param)
        # self.feat.compute()

        # check
        # new instance is returned
        # self.assertNotEqual(self.p, f)
        # filter retains the same number of points
        # self.assertEqual(self.p.size, f.size)
        pass


def suite():
    suite = unittest.TestSuite()
    # features
    # compute - exception
    # suite.addTests(unittest.makeSuite(TestIntegralImageNormalEstimation))
    suite.addTests(unittest.makeSuite(TestMomentOfInertiaEstimation))
    suite.addTests(unittest.makeSuite(TestNormalEstimation))
    suite.addTests(unittest.makeSuite(TestVFHEstimation))
    # no add pxiInclude
    # suite.addTests(unittest.makeSuite(TestDifferenceOfNormalsEstimation))
    # suite.addTests(unittest.makeSuite(TestRangeImageBorderExtractor))
    return suite


if __name__ == '__main__':
    # unittest.main()
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
F....
[(0, 0, 0.2), (1, 2, 3.2), (2, 4, 6.2), (3, 6, 9.2), (4, 8, 12.2)]
[[-1.0104160e+01  3.3665344e+07  6.2516429e+10]]
[[ 0.1642869   0.92008287 -0.35560855]]
[[ 9.2008287e-01 -3.5560855e-01  2.5355022e-28]]
[[-3.5560855e-01  2.5355022e-28  3.3665344e+07]]
======================================================================
FAIL: test_Tutorials (__main__.TestMomentOfInertiaEstimation)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython-input-11-52f8110f17f9>", line 192, in test_Tutorials
    self.assertEqual(datas.tolist(), expected.tolist())
AssertionError: Lists differ: [-10.10416, 33665344.0, 62516428800.0] != [-10.10416, 0.074005, -2.144748]

First differing element 1:
33665344.0
0.074005

- [-10.10416, 33665344.0, 62516428800.0]
+ [-10.10416, 0.074005, -2.144748]

----------------------------------------------------------------------
Ran 5 tests in 0.036s

FAILED (failures=1)

どうもx軸はよいが、他の軸、特にz軸の値がおかしくて、5つのテストが動くはずだが最初でつまずいたようである

tests/test_filters.py

In [13]:
import os
os.chdir('/home/sirai/2018/PCL/python-pcl-master')
In [14]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np

from nose.plugins.attrib import attr


_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
           1.0, 2.0, 3.2;
           2.0, 4.0, 6.2;
           3.0, 6.0, 9.2;
           4.0, 8.0, 12.2"""


_data2 = np.array(
    [[0.0080142, 0.694695, -0.26015],
     [-0.342265, -0.446349, 0.214207],
     [0.173687, -0.84253, -0.400481],
     [-0.874475, 0.706127, -0.117635],
     [0.908514, -0.598159, 0.744714]], dtype=np.float32)


# Filter
### ApproximateVoxelGrid ###


class TestApproximateVoxelGrid(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "table_scene_lms400.pcd")
        self.fil = self.p.make_ApproximateVoxelGrid()
        # self.fil = pcl.ApproximateVoxelGrid()
        # self.fil.set_InputCloud(self.p)

    def test_VoxelGrid(self):
        x = 0.01
        y = 0.01
        z = 0.01
        self.fil.set_leaf_size(x, y, z)
        result = self.fil.filter()
        # check
        self.assertTrue(result.size < self.p.size)
        # self.assertEqual(result.size, 719)


### ConditionalRemoval ###
# Appveyor NG
@attr('pcl_ver_0_4')
@attr('pcl_over_17')
class TestConditionalRemoval(unittest.TestCase):
    def setUp(self):
        # self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        # self.p = pcl.PointCloud(_data)
        self.p = pcl.PointCloud(_data2)
        self.fil = self.p.make_ConditionalRemoval(pcl.ConditionAnd())

    # result
    # nan nan nan
    # -0.342265 -0.446349 0.214207
    # nan nan nan
    # nan nan nan
    # 0.908514 -0.598159 0.744714
    def test_Condition(self):
        range_cond = self.p.make_ConditionAnd()
        range_cond.add_Comparison2('z', pcl.CythonCompareOp_Type.GT, 0.0)
        range_cond.add_Comparison2('z', pcl.CythonCompareOp_Type.LT, 0.8)
        # build the filter
        self.fil.set_KeepOrganized(True)
        # apply filter
        cloud_filtered = self.fil.filter()

        # check
        expected = np.array([-0.342265, -0.446349, 0.214207])
        datas = np.around(cloud_filtered.to_array()[1].tolist(), decimals=6)
        self.assertEqual(datas.tolist(), expected.tolist())

        expected2 = np.array([0.908514, -0.598159, 0.744714])
        datas = np.around(cloud_filtered.to_array()[4].tolist(), decimals=6)
        self.assertEqual(datas.tolist(), expected2.tolist())


#     def set_KeepOrganized(self, flag):
#         self.fil.setKeepOrganized(flag)
#
#     def filter(self):
#         """
#         Apply the filter according to the previously set parameters and return
#         a new pointcloud
#         """
#         cdef PointCloud pc = PointCloud()
#         self.fil.filter(pc.thisptr()[0])
#         return pc


### ConditionAnd ###
class TestConditionAnd(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")

    def test_Tutorial(self):
        pass


### CropBox ###
# base : pcl/tests cpp source code[TEST (CropBox, Filters)]
class TestCropBox(unittest.TestCase):

    def setUp(self):
        input = pcl.PointCloud()
        points = np.zeros((9, 3), dtype=np.float32)
        points[0] = 0.0, 0.0, 0.0
        points[1] = 0.9, 0.9, 0.9
        points[2] = 0.9, 0.9, -0.9
        points[3] = 0.9, -0.9, 0.9
        points[4] = -0.9, 0.9, 0.9
        points[5] = 0.9, -0.9, -0.9
        points[6] = -0.9, -0.9, 0.9
        points[7] = -0.9, 0.9, -0.9
        points[8] = -0.9, -0.9, -0.9
        input.from_array(points)
        self.p = input

    def testException(self):
        self.assertRaises(TypeError, pcl.CropHull)

    def testCrop(self):
        cropBoxFilter = self.p.make_cropbox()
        # Cropbox slighlty bigger then bounding box of points
        cropBoxFilter.set_Min(-1.0, -1.0, -1.0, 1.0)
        cropBoxFilter.set_Max(1.0, 1.0, 1.0, 1.0)

        # Indices
        # vector<int> indices;
        # cropBoxFilter.filter(indices)

        # Cloud
        cloud_out = cropBoxFilter.filter()

        # Should contain all
        # self.assertEqual(indices.size, 9)
        self.assertEqual(cloud_out.size, 9)
        self.assertEqual(cloud_out.width, 9)
        self.assertEqual(cloud_out.height, 1)

        # IndicesConstPtr removed_indices;
        # removed_indices = cropBoxFilter.get_RemovedIndices ()
        cropBoxFilter.get_RemovedIndices()
        # self.assertEqual(removed_indices.size, 0)
        # self.assertEqual(lemn(removed_indices), 0)

        # Test setNegative
        cropBoxFilter.set_Negative(True)
        cloud_out_negative = cropBoxFilter.filter()
        # self.assertEqual(cloud_out_negative.size, 0)

        # cropBoxFilter.filter(indices)
        # self.assertEqual(indices.size, 0)

        cropBoxFilter.set_Negative(False)
        cloud_out = cropBoxFilter.filter()

        # Translate crop box up by 1
        tx = 0
        ty = 1
        tz = 0
        cropBoxFilter.set_Translation(tx, ty, tz)
        # indices = cropBoxFilter.filter()
        cloud_out = cropBoxFilter.filter()

        # self.assertEqual(indices.size, 5)
        self.assertEqual(cloud_out.size, 5)

        # removed_indices = cropBoxFilter.get_RemovedIndices ()
        cropBoxFilter.get_RemovedIndices()
        # self.assertEqual(removed_indices.size, 4)

        # Test setNegative
        cropBoxFilter.set_Negative(True)
        cloud_out_negative = cropBoxFilter.filter()
        # self.assertEqual(cloud_out_negative.size, 4)

        # indices = cropBoxFilter.filter()
        # self.assertEqual(indices.size, 4)

        cropBoxFilter.set_Negative(False)
        cloud_out = cropBoxFilter.filter()

        #  Rotate crop box up by 45
        # cropBoxFilter.setRotation (Eigen::Vector3f (0.0, 45.0f * float (M_PI) / 180.0, 0.0f))
        # cropBoxFilter.filter(indices)
        # cropBoxFilter.filter(cloud_out)
        rx = 0.0
        ry = 45.0 * (3.141592 / 180.0)
        rz = 0.0
        cropBoxFilter.set_Rotation(rx, ry, rz)
        # indices = cropBoxFilter.filter()
        cloud_out = cropBoxFilter.filter()

        # self.assertEqual(indices.size, 1)
        self.assertEqual(cloud_out.size, 1)
        self.assertEqual(cloud_out.width, 1)
        self.assertEqual(cloud_out.height, 1)

        # removed_indices = cropBoxFilter.get_RemovedIndices ()
        # self.assertEqual(removed_indices.size, 8)
        cropBoxFilter.get_RemovedIndices()

        #  Test setNegative
        cropBoxFilter.set_Negative(True)
        cloud_out_negative = cropBoxFilter.filter()
        # self.assertEqual(cloud_out_negative.size, 8)

        # indices = cropBoxFilter.filter()
        # self.assertEqual(indices.size, 8)

        cropBoxFilter.set_Negative(False)
        cloud_out = cropBoxFilter.filter()

        # // Rotate point cloud by -45
        # cropBoxFilter.set_Transform (getTransformation (0.0, 0.0, 0.0, 0.0, 0.0, -45.0f * float (M_PI) / 180.0f))
        # indices = cropBoxFilter.filter()
        # cloud_out = cropBoxFilter.filter()
        #
        # # self.assertEqual(indices.size, 3)
        # self.assertEqual(cloud_out.size, 3)
        # self.assertEqual(cloud_out.width, 3)
        # self.assertEqual(cloud_out.height, 1)
        ##

        # removed_indices = cropBoxFilter.get_RemovedIndices ()
        # self.assertEqual(removed_indices.size, 6)
        cropBoxFilter.get_RemovedIndices()

        # // Test setNegative
        cropBoxFilter.set_Negative(True)
        cloud_out_negative = cropBoxFilter.filter()
        # self.assertEqual(cloud_out_negative.size, 6)

        # indices = cropBoxFilter.filter()
        # self.assertEqual(indices.size, 6)

        cropBoxFilter.set_Negative(False)
        cloud_out = cropBoxFilter.filter()

        # Translate point cloud down by -1
        # # cropBoxFilter.setTransform (getTransformation(0, -1, 0, 0, 0, -45.0 * float (M_PI) / 180.0))
        # # cropBoxFilter.filter(indices)
        # cropBoxFilter.filter(cloud_out)
        #
        # # self.assertEqual(indices.size, 2)
        # self.assertEqual(cloud_out.size, 2)
        # self.assertEqual(cloud_out.width, 2)
        # self.assertEqual(cloud_out.height, 1)
        ##

        # removed_indices = cropBoxFilter.get_RemovedIndices ()
        # self.assertEqual(removed_indices.size, 7)

        # Test setNegative
        cropBoxFilter.set_Negative(True)
        cloud_out_negative = cropBoxFilter.filter()
        # self.assertEqual(cloud_out_negative.size, 7)

        # indices = cropBoxFilter.filter()
        # self.assertEqual(indices.size, 7)

        cropBoxFilter.set_Negative(False)
        cloud_out = cropBoxFilter.filter()

        # // Remove point cloud rotation
        # cropBoxFilter.set_Transform (getTransformation(0, -1, 0, 0, 0, 0))
        # indices = cropBoxFilter.filter()
        # cloud_out = cropBoxFilter.filter()

        # self.assertEqual(indices.size, 0)
        # self.assertEqual(cloud_out.size, 0)
        # self.assertEqual(cloud_out.width, 0)
        # self.assertEqual(cloud_out.height, 1)

        # removed_indices = cropBoxFilter.get_RemovedIndices ()
        # self.assertEqual(removed_indices.size, 9)

        # Test setNegative
        cropBoxFilter.set_Negative(True)
        cloud_out_negative = cropBoxFilter.filter()
        # self.assertEqual(cloud_out_negative.size, 9)

        # indices = cropBoxFilter.filter()
        # self.assertEqual(indices.size, 9)

        # PCLPointCloud2
        # // ------------------------------------------------------------------
        # Create cloud with center point and corner points
        # PCLPointCloud2::Ptr input2 (new PCLPointCloud2)
        # pcl::toPCLPointCloud2 (*input, *input2)
        #
        # Test the PointCloud<PointT> method
        # CropBox<PCLPointCloud2> cropBoxFilter2(true)
        # cropBoxFilter2.setInputCloud (input2)
        #
        # Cropbox slighlty bigger then bounding box of points
        # cropBoxFilter2.setMin (min_pt)
        # cropBoxFilter2.setMax (max_pt)
        #
        # Indices
        # vector<int> indices2;
        # cropBoxFilter2.filter (indices2)
        #
        # Cloud
        # PCLPointCloud2 cloud_out2;
        # cropBoxFilter2.filter (cloud_out2)
        #
        # // Should contain all
        # self.assertEqual(indices2.size, 9)
        # self.assertEqual(indices2.size, int (cloud_out2.width * cloud_out2.height))
        #
        # IndicesConstPtr removed_indices2;
        # removed_indices2 = cropBoxFilter2.get_RemovedIndices ()
        # self.assertEqual(removed_indices2.size, 0)
        #
        # // Test setNegative
        # PCLPointCloud2 cloud_out2_negative;
        # cropBoxFilter2.setNegative (true)
        # cropBoxFilter2.filter (cloud_out2_negative)
        # self.assertEqual(cloud_out2_negative.width), 0)
        #
        # cropBoxFilter2.filter (indices2)
        # self.assertEqual(indices2.size, 0)
        #
        # cropBoxFilter2.setNegative (false)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # // Translate crop box up by 1
        # cropBoxFilter2.setTranslation (Eigen::Vector3f(0, 1, 0))
        # cropBoxFilter2.filter (indices2)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # self.assertEqual(indices2.size, 5)
        # self.assertEqual(indices2.size, int (cloud_out2.width * cloud_out2.height))
        #
        # removed_indices2 = cropBoxFilter2.get_RemovedIndices ()
        # self.assertEqual(removed_indices2.size, 4)
        #
        # // Test setNegative
        # cropBoxFilter2.setNegative (true)
        # cropBoxFilter2.filter (cloud_out2_negative)
        # self.assertEqual(cloud_out2_negative.width), 4)
        #
        # cropBoxFilter2.filter (indices2)
        # self.assertEqual(indices2.size, 4)
        #
        # cropBoxFilter2.setNegative (false)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # // Rotate crop box up by 45
        # cropBoxFilter2.setRotation (Eigen::Vector3f (0.0, 45.0f * float (M_PI) / 180.0, 0.0f))
        # cropBoxFilter2.filter (indices2)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # self.assertEqual(indices2.size, 1)
        # self.assertEqual(indices2.size, int (cloud_out2.width * cloud_out2.height))
        #
        # // Rotate point cloud by -45
        # cropBoxFilter2.setTransform (getTransformation (0.0, 0.0, 0.0, 0.0, 0.0, -45.0f * float (M_PI) / 180.0f))
        # cropBoxFilter2.filter (indices2)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # self.assertEqual(indices2.size, 3)
        # self.assertEqual(cloud_out2.width * cloud_out2.height), 3)
        #
        # removed_indices2 = cropBoxFilter2.get_RemovedIndices ()
        # self.assertEqual(removed_indices2.size, 6)
        #
        # // Test setNegative
        # cropBoxFilter2.setNegative (true)
        # cropBoxFilter2.filter (cloud_out2_negative)
        # self.assertEqual(cloud_out2_negative.width), 6)
        #
        # cropBoxFilter2.filter (indices2)
        # self.assertEqual(indices2.size, 6)
        #
        # cropBoxFilter2.setNegative (false)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # // Translate point cloud down by -1
        # cropBoxFilter2.setTransform (getTransformation (0.0, -1.0, 0.0, 0.0, 0.0, -45.0f * float (M_PI) / 180.0f))
        # cropBoxFilter2.filter (indices2)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # self.assertEqual(indices2.size, 2)
        # self.assertEqual(cloud_out2.width * cloud_out2.height), 2)
        #
        # removed_indices2 = cropBoxFilter2.get_RemovedIndices ()
        # self.assertEqual(removed_indices2.size, 7)
        #
        # // Test setNegative
        # cropBoxFilter2.setNegative (true)
        # cropBoxFilter2.filter (cloud_out2_negative)
        # self.assertEqual(cloud_out2_negative.width), 7)
        #
        # cropBoxFilter2.filter (indices2)
        # self.assertEqual(indices2.size, 7)
        #
        # cropBoxFilter2.setNegative (false)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # // Remove point cloud rotation
        # cropBoxFilter2.setTransform (getTransformation(0, -1, 0, 0, 0, 0))
        # cropBoxFilter2.filter (indices2)
        # cropBoxFilter2.filter (cloud_out2)
        #
        # self.assertEqual(indices2.size, 0)
        # self.assertEqual(cloud_out2.width * cloud_out2.height), 0)
        #
        # removed_indices2 = cropBoxFilter2.get_RemovedIndices ()
        # self.assertEqual(removed_indices2.size, 9)
        #
        # // Test setNegative
        # cropBoxFilter2.setNegative (true)
        # cropBoxFilter2.filter (cloud_out2_negative)
        # self.assertEqual(cloud_out2_negative.width), 9)
        #
        # cropBoxFilter2.filter (indices2)
        # self.assertEqual(indices2.size, 9)
        #
        # cropBoxFilter2.setNegative (false)
        # cropBoxFilter2.filter (cloud_out2)


### CropHull ###
class TestCropHull(unittest.TestCase):

    def setUp(self):
        self.pc = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "table_scene_mug_stereo_textured.pcd")

    def testException(self):
        self.assertRaises(TypeError, pcl.CropHull)

    def testCropHull(self):
        filterCloud = pcl.PointCloud()
        vt = pcl.Vertices()
#         # // inside point
#         # cloud->push_back(pcl::PointXYZ(M_PI * 0.3, M_PI * 0.3, 0))
#         # // hull points
#         # cloud->push_back(pcl::PointXYZ(0,0,0))
#         # cloud->push_back(pcl::PointXYZ(M_PI,0,0))
#         # cloud->push_back(pcl::PointXYZ(M_PI,M_PI*0.5,0))
#         # cloud->push_back(pcl::PointXYZ(0,M_PI*0.5,0))
#         # cloud->push_back(pcl::PointXYZ(0,0,0))
#         # // outside point
#         # cloud->push_back(pcl::PointXYZ(-M_PI * 0.3, -M_PI * 0.3, 0))
#         points_2 = np.array([
#                         [1 * 0.3, 1 * 0.3, 0],
#                         [0, 0, 0],
#                         [1, 0, 0],
#                         [1, 1 * 0.5, 0],
#                         [0, 1 * 0.5, 0],
#                         [0, 0, 0],
#                         # [-1 * 0.3 , -1 * 0.3, 0]
#                     ], dtype=np.float32)
#         filterCloud.from_array(points_2)
#         # print(filterCloud)
#
#         vertices_point_1 = np.array([1, 2, 3, 4, 5], dtype=np.int)
#         vt.from_array(vertices_point_1)
#         # print(vt)
#         # vt.vertices.push_back(1)
#         # vt.vertices.push_back(2)
#         # vt.vertices.push_back(3)
#         # vt.vertices.push_back(4)
#         # vt.vertices.push_back(5)
#         # vertices = vector[pcl.Vertices]
#         # vertices.push_back(vt)
#
#         outputCloud = pcl.PointCloud()
#         # crophull = pcl.CropHull()
#         # crophull.setInputCloud(self.pc)
#         crophull = self.pc.make_crophull()
#         # crophull.setHullIndices(vertices)
#         # crophull.setHullIndices(vt)
#         # crophull.setHullCloud(filterCloud)
#         # crophull.setDim(2)
#         # crophull.setCropOutside(false)
#         crophull.SetParameter(filterCloud, vt)
#         # indices = vector[int]
#         # cropHull.filter(indices)
#         # outputCloud = cropHull.filter()
#         # print("before: " + outputCloud)
#         crophull.filter(outputCloud)
#         # print(outputCloud)


### FieldComparison ###
class TestFieldComparison(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load("tests/table_scene_mug_stereo_textured_noplane.pcd")
        compare = CompareOp2
        thresh = 1.0
        self.fil = pcl.FieldComparison(compare, thresh)


### PassThroughFilter ###
class TestPassthroughFilter(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load("tests/table_scene_mug_stereo_textured_noplane.pcd")

    def testFilter(self):
        fil = self.p.make_passthrough_filter()
        fil.set_filter_field_name("z")
        fil.set_filter_limits(0, 0.75)
        c = fil.filter()
        self.assertTrue(c.size < self.p.size)
        self.assertEqual(c.size, 7751)

    def testFilterBoth(self):
        total = self.p.size
        fil = self.p.make_passthrough_filter()
        fil.set_filter_field_name("z")
        fil.set_filter_limits(0, 0.75)
        front = fil.filter().size
        fil.set_filter_limits(0.75, 100)
        back = fil.filter().size
        self.assertEqual(total, front + back)


### ProjectInliers ###
class TestProjectInliers(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load("tests/table_scene_mug_stereo_textured_noplane.pcd")
        self.fil = self.p.make_ProjectInliers()
        # self.fil = pcl.ProjectInliers()
        # self.fil.set_InputCloud(self.p)

    def test_model_type(self):
        # param1
        m = pcl.SACMODEL_PLANE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_PLANE)

        # param2
        m = pcl.SACMODEL_LINE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_LINE)

        # param3
        m = pcl.SACMODEL_CIRCLE2D
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_CIRCLE2D)

        # param4
        m = pcl.SACMODEL_CIRCLE3D
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_CIRCLE3D)

        # param5
        m = pcl.SACMODEL_SPHERE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_SPHERE)

        # param6
        m = pcl.SACMODEL_CYLINDER
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_CYLINDER)

        # param7
        m = pcl.SACMODEL_CONE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_CONE)

        # param8
        m = pcl.SACMODEL_TORUS
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_TORUS)

        # param9
        m = pcl.SACMODEL_PARALLEL_LINE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_PARALLEL_LINE)

        # param10
        m = pcl.SACMODEL_PERPENDICULAR_PLANE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_PERPENDICULAR_PLANE)

        # param11
        m = pcl.SACMODEL_PARALLEL_LINES
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_PARALLEL_LINES)

        # param12
        m = pcl.SACMODEL_NORMAL_PLANE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_NORMAL_PLANE)

        # param13
        m = pcl.SACMODEL_NORMAL_SPHERE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_NORMAL_SPHERE)

        # param14
        m = pcl.SACMODEL_REGISTRATION
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_REGISTRATION)

        # param15
        m = pcl.SACMODEL_PARALLEL_PLANE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_PARALLEL_PLANE)

        # param16
        m = pcl.SACMODEL_NORMAL_PARALLEL_PLANE
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_NORMAL_PARALLEL_PLANE)

        # param17
        m = pcl.SACMODEL_STICK
        self.fil.set_model_type(m)
        result_param = self.fil.get_model_type()
        self.assertEqual(result_param, pcl.SACMODEL_STICK)
        pass

    def test_copy_all_data(self):
        self.fil.set_copy_all_data(True)
        datas = self.fil.get_copy_all_data()
        # result
        self.assertEqual(datas, True)

        self.fil.set_copy_all_data(False)
        datas = self.fil.get_copy_all_data()
        # result2
        self.assertEqual(datas, False)


### RadiusOutlierRemoval ###
class TestRadiusOutlierRemoval(unittest.TestCase):

    def setUp(self):
        # self.p = pcl.load("tests/table_scene_mug_stereo_textured_noplane.pcd")
        self.p = pcl.PointCloud(_data2)
        print(self.p.size)
        self.fil = self.p.make_RadiusOutlierRemoval()
        # self.fil = pcl.RadiusOutlierRemoval()
        # self.fil.set_InputCloud(self.p)

    def test_radius_seach(self):
        radius = 15.8
        self.fil.set_radius_search(radius)
        result = self.fil.get_radius_search()
        self.assertEqual(radius, result)

        min_pts = 2
        self.fil.set_MinNeighborsInRadius(2)
        result = self.fil.get_MinNeighborsInRadius()
        self.assertEqual(min_pts, result)

        result_point = self.fil.filter()

        # check
        # new instance is returned
        # self.assertNotEqual(self.p, result)
        # filter retains the same number of points
        # self.assertNotEqual(result_point.size, 0)
        # self.assertNotEqual(self.p.size, result_point.size)


### StatisticalOutlierRemovalFilter ###
class TestStatisticalOutlierRemovalFilter(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "table_scene_mug_stereo_textured_noplane.pcd")
        self.fil = self.p.make_statistical_outlier_filter()
        # self.fil = pcl.StatisticalOutlierRemovalFilter()
        # self.fil.set_InputCloud(self.p)

    def _tpos(self, c):
        self.assertEqual(c.size, 22745)
        self.assertEqual(c.width, 22745)
        self.assertEqual(c.height, 1)
        self.assertTrue(c.is_dense)

    def _tneg(self, c):
        self.assertEqual(c.size, 1015)
        self.assertEqual(c.width, 1015)
        self.assertEqual(c.height, 1)
        self.assertTrue(c.is_dense)

    def testFilterPos(self):
        fil = self.p.make_statistical_outlier_filter()
        fil.set_mean_k(50)
        self.assertEqual(fil.mean_k, 50)
        fil.set_std_dev_mul_thresh(1.0)
        self.assertEqual(fil.stddev_mul_thresh, 1.0)
        c = fil.filter()
        self._tpos(c)

    def testFilterNeg(self):
        fil = self.p.make_statistical_outlier_filter()
        fil.set_mean_k(50)
        fil.set_std_dev_mul_thresh(1.0)
        self.assertEqual(fil.negative, False)
        fil.set_negative(True)
        self.assertEqual(fil.negative, True)
        c = fil.filter()
        self._tneg(c)

    def testFilterPosNeg(self):
        fil = self.p.make_statistical_outlier_filter()
        fil.set_mean_k(50)
        fil.set_std_dev_mul_thresh(1.0)
        c = fil.filter()
        self._tpos(c)
        fil.set_negative(True)
        c = fil.filter()
        self._tneg(c)


### VoxelGridFilter ###
class TestVoxelGridFilter(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "table_scene_mug_stereo_textured_noplane.pcd")
        self.fil = self.p.make_voxel_grid_filter()
        # self.fil = pcl.VoxelGridFilter()
        # self.fil.set_InputCloud(self.p)

    def testFilter(self):
        self.fil.set_leaf_size(0.01, 0.01, 0.01)
        c = self.fil.filter()
        self.assertTrue(c.size < self.p.size)
        self.assertEqual(c.size, 719)


### Official Test Base ###
p_65558 = np.array([-0.058448, -0.189095, 0.723415], dtype=np.float32)
p_84737 = np.array([-0.088929, -0.152957, 0.746095], dtype=np.float32)
p_57966 = np.array([0.123646, -0.397528, 1.393187], dtype=np.float32)
p_39543 = np.array([0.560287, -0.545020, 1.602833], dtype=np.float32)
p_17766 = np.array([0.557854, -0.711976, 1.762013], dtype=np.float32)
p_70202 = np.array([0.150500, -0.160329, 0.646596], dtype=np.float32)
p_102219 = np.array([0.175637, -0.101353, 0.661631], dtype=np.float32)
p_81765 = np.array([0.223189, -0.151714, 0.708332], dtype=np.float32)

# class TESTFastBilateralFilter(unittest.TestCase):
#     def setUp(self):
#         self.p = pcl.load("tests" + os.path.sep + "milk_cartoon_all_small_clorox.pcd")
#
#     def testFastBilateralFilter(self):
#         fbf = pcl.FastBilateralFilter()
#         fbf.setInputCloud(cloud)
#         fbf.setSigmaS (5)
#         fbf.setSigmaR (0.03f)
#         cloud_filtered = fbf.filter()
#         # for (size_t dim = 0; dim < 3; ++dim):
#         for dim range(0:3):
#             EXPECT_NEAR (p_84737[dim],  cloud_filtered[84737][dim], 1e-3)
#             EXPECT_NEAR (p_57966[dim],  cloud_filtered[57966][dim], 1e-3)
#             EXPECT_NEAR (p_39543[dim],  cloud_filtered[39543][dim], 1e-3)
#             EXPECT_NEAR (p_17766[dim],  cloud_filtered[17766][dim], 1e-3)
#             EXPECT_NEAR (p_70202[dim],  cloud_filtered[70202][dim], 1e-3)
#             EXPECT_NEAR (p_102219[dim], cloud_filtered[102219][dim], 1e-3)
#             EXPECT_NEAR (p_81765[dim],  cloud_filtered[81765][dim], 1e-3)
#         pass


# class TESTFastBilateralFilterOMP(unittest.TestCase):
#
#     def setUp(self):
#         self.p = pcl.load("tests" + os.path.sep + "milk_cartoon_all_small_clorox.pcd")
#
#         sigma_s = [2.341,  5.2342, 10.29380]
#         sigma_r = [0.0123, 0.023,  0.0345]
#         for (size_t i = 0; i < 3; i++)
#             FastBilateralFilter<PointXYZ> fbf;
#             fbf.setInputCloud (cloud);
#             fbf.setSigmaS (sigma_s[i]);
#             fbf.setSigmaR (sigma_r[i]);
#             PointCloud<PointXYZ>::Ptr cloud_filtered (new PointCloud<PointXYZ> ());
#             fbf.filter (*cloud_filtered);
#
#             FastBilateralFilterOMP<PointXYZ> fbf_omp (0);
#             fbf_omp.setInputCloud (cloud);
#             fbf_omp.setSigmaS (sigma_s[i]);
#             fbf_omp.setSigmaR (sigma_r[i]);
#     PointCloud<PointXYZ>::Ptr cloud_filtered_omp (new PointCloud<PointXYZ> ());
#     fbf_omp.filter (*cloud_filtered_omp);
#     PCL_INFO ("[FastBilateralFilterOMP] filtering took %f ms\n", tt.toc ());
#
#
#     EXPECT_EQ (cloud_filtered_omp->points.size (), cloud_filtered->points.size ());
#     for (size_t j = 0; j < cloud_filtered_omp->size (); ++j)
#     {
#       if (pcl_isnan (cloud_filtered_omp->at (j).x))
#         EXPECT_TRUE (pcl_isnan (cloud_filtered->at (j).x));
#       else
#       {
#         EXPECT_NEAR (cloud_filtered_omp->at (j).x, cloud_filtered->at (j).x, 1e-3);
#         EXPECT_NEAR (cloud_filtered_omp->at (j).y, cloud_filtered->at (j).y, 1e-3);
#         EXPECT_NEAR (cloud_filtered_omp->at (j).z, cloud_filtered->at (j).z, 1e-3);
#       }
#     }


def suite():
    suite = unittest.TestSuite()

    # Filter
    suite.addTests(unittest.makeSuite(TestApproximateVoxelGrid))
    suite.addTests(unittest.makeSuite(TestConditionalRemoval))
    # suite.addTests(unittest.makeSuite(TestConditionAnd))
    suite.addTests(unittest.makeSuite(TestCropBox))
    suite.addTests(unittest.makeSuite(TestCropHull))
    suite.addTests(unittest.makeSuite(TestFieldComparison))
    suite.addTests(unittest.makeSuite(TestPassthroughFilter))
    suite.addTests(unittest.makeSuite(TestProjectInliers))
    # suite.addTests(unittest.makeSuite(TestRadiusOutlierRemoval))
    suite.addTests(unittest.makeSuite(TestStatisticalOutlierRemovalFilter))
    suite.addTests(unittest.makeSuite(TestVoxelGridFilter))

    # PointCloudLibrary Official Base Test?
    # suite.addTests(unittest.makeSuite(TestFastBilateralFilter))

    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
..............
----------------------------------------------------------------------
Ran 14 tests in 2.004s

OK

tests/test_kdtree.py

In [16]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np

from nose.plugins.attrib import attr


class TestKdTree(unittest.TestCase):
    def setUp(self):
        rng = np.random.RandomState(42)
        # Define two dense sets of points of sizes 30 and 170, resp.
        a = rng.randn(100, 3).astype(np.float32)
        a[:30] -= 42

        self.pc = pcl.PointCloud(a)
        self.kd = pcl.KdTreeFLANN(self.pc)

    def testException(self):
        self.assertRaises(TypeError, pcl.KdTreeFLANN)
        self.assertRaises(TypeError, self.kd.nearest_k_search_for_cloud, None)

    def testKNN(self):
        # Small cluster
        ind, sqdist = self.kd.nearest_k_search_for_point(self.pc, 0, k=2)
        for i in ind:
            self.assertGreaterEqual(i, 0)
            self.assertLess(i, 30)
        for d in sqdist:
            self.assertGreaterEqual(d, 0)

        # Big cluster
        for ref, k in ((80, 1), (59, 3), (60, 10)):
            ind, sqdist = self.kd.nearest_k_search_for_point(self.pc, ref, k=k)
            for i in ind:
                self.assertGreaterEqual(i, 30)
            for d in sqdist:
                self.assertGreaterEqual(d, 0)


class TestKdTreeFLANN(unittest.TestCase):
    def setUp(self):
        rng = np.random.RandomState(42)
        # Define two dense sets of points of sizes 30 and 170, resp.
        a = rng.randn(100, 3).astype(np.float32)
        a[:30] -= 42

        self.pc = pcl.PointCloud(a)
        self.kd = pcl.KdTreeFLANN(self.pc)

    def testException(self):
        self.assertRaises(TypeError, pcl.KdTreeFLANN)
        self.assertRaises(TypeError, self.kd.nearest_k_search_for_cloud, None)

    def testKNN(self):
        # Small cluster
        ind, sqdist = self.kd.nearest_k_search_for_point(self.pc, 0, k=2)
        for i in ind:
            self.assertGreaterEqual(i, 0)
            self.assertLess(i, 30)
        for d in sqdist:
            self.assertGreaterEqual(d, 0)

        # Big cluster
        for ref, k in ((80, 1), (59, 3), (60, 10)):
            ind, sqdist = self.kd.nearest_k_search_for_point(self.pc, ref, k=k)
            for i in ind:
                self.assertGreaterEqual(i, 30)
            for d in sqdist:
                self.assertGreaterEqual(d, 0)


def suite():
    suite = unittest.TestSuite()
    # ketree
    suite.addTests(unittest.makeSuite(TestKdTree))
    suite.addTests(unittest.makeSuite(TestKdTreeFLANN))
    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
....
----------------------------------------------------------------------
Ran 4 tests in 0.007s

OK

tests/test_keypoints.py

In [17]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np


from nose.plugins.attrib import attr


_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
           1.0, 2.0, 3.2;
           2.0, 4.0, 6.2;
           3.0, 6.0, 9.2;
           4.0, 8.0, 12.2"""


# keyPoints
### HarrisKeypoint3D ###


class TestHarrisKeypoint3D(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "bunny.pcd")
        self.kp = self.p.make_HarrisKeypoint3D()

    def test_HarrisKeyPoint3D(self):
        # 397
        base_point_count = 397
        self.assertEqual(self.p.size, base_point_count)

        self.kp.set_NonMaxSupression(True)
        self.kp.set_Radius(0.01)
        # self.kp.set_RadiusSearch (0.01)
        keypoints = self.kp.compute()

        # pcl - 1.8, 51
        # pcl - 1.7, 48
        # keypoint_count = 51
        # self.assertEqual(keypoints.size, keypoint_count)
        self.assertNotEqual(keypoints.size, 0)

        count = 0
        minIts = 999.00
        maxIts = -999.00
        points = np.zeros((keypoints.size, 3), dtype=np.float32)
        # Generate the data
        for i in range(0, keypoints.size):
            # set Point Plane
            points[i][0] = keypoints[i][0]
            points[i][1] = keypoints[i][1]
            points[i][2] = keypoints[i][2]
            intensity = keypoints[i][3]
            if intensity > maxIts:
                print("coords: " +
                      str(keypoints[i][0]) +
                      ";" +
                      str(keypoints[i][1]) +
                      ";" +
                      str(keypoints[i][2]))
                maxIts = intensity

            if intensity < minIts:
                minIts = intensity

            count = count + 1

        # points.resize(count, 3)
        # print(points)
        # keypoints3D.from_array(points)
        # print("maximal responce: " + str(maxIts) + " min responce:  " +  str(minIts) )
        ##
        # coords: 0.008801460266113281;0.12533344328403473;0.03247201442718506
        # coords: 0.02295708656311035;0.12180554866790771;0.029724061489105225
        # coords: -0.06679701805114746;0.15040874481201172;0.03854072093963623
        # coords: -0.0672549456357956;0.11913366615772247;0.05214547738432884
        # coords: -0.05888630822300911;0.1165248453617096;0.03698881343007088
        # coords: 0.04757949709892273;0.07463110238313675;0.018482372164726257
        # maximal responce: 0.0162825807929039 min responce:  0.0

        # pcl 1.7 : 0.01632295921444893
        # self.assertEqual(maxIts, 0.0162825807929039)
        self.assertGreaterEqual(maxIts, 0.0)
        self.assertEqual(minIts, 0.0)


### NarfKeypoint ###
@attr('pcl_ver_0_4')
class TestNarfKeypoint(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        # self.kp = pcl.NarfKeypoint()
        # self.kp.setInputCloud(self.p)

    def test_NarfKeypoint(self):
        pass


### UniformSampling ###
@attr('pcl_ver_0_4')
class TestUniformSampling(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        # self.kp = pcl.UniformSampling()

    def test_UniformSampling(self):
        pass


def suite():
    suite = unittest.TestSuite()

    # keypoints
    suite.addTests(unittest.makeSuite(TestHarrisKeypoint3D))
    # RangeImage no set
    # suite.addTests(unittest.makeSuite(TestNarfKeypoint))
    # no add pxiInclude
    # suite.addTests(unittest.makeSuite(TestUniformSampling))

    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
.
coords: 0.008803367614746094;0.12533354759216309;0.032472848892211914
coords: 0.022958189249038696;0.12180620431900024;0.029725193977355957
coords: -0.06679463386535645;0.15040969848632812;0.03853964805603027
coords: -0.0672549307346344;0.11913353204727173;0.05214541777968407
coords: -0.05888630822300911;0.11652494221925735;0.0369887575507164
coords: 0.04757946729660034;0.07463118433952332;0.018482357263565063
----------------------------------------------------------------------
Ran 1 test in 0.006s

OK

tests/test_octree.py

In [18]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np

_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
           1.0, 2.0, 3.2;
           2.0, 4.0, 6.2;
           3.0, 6.0, 9.2;
           4.0, 8.0, 12.2"""


from nose.plugins.attrib import attr


# class TestOctreePointCloud(unittest.TestCase):
#
#     def setUp(self):
#         self.p = pcl.load("tests" + os.path.sep + "table_scene_mug_stereo_textured_noplane.pcd")
#         self.octree = pcl.OctreePointCloud(0.1)
#
#     def testLoad(self):
#         self.octree.set_input_cloud(self.p)
#         self.octree.define_bounding_box()
#         self.octree.add_points_from_input_cloud()
#         good_point = [0.035296999, -0.074322999, 1.2074]
#         rs = self.octree.is_voxel_occupied_at_point(good_point)
#         self.assertTrue(rs)
#         bad_point = [0.5, 0.5, 0.5]
#         rs = self.octree.is_voxel_occupied_at_point(bad_point)
#         self.assertFalse(rs)
#         voxels_len = 44
#         self.assertEqual(len(self.octree.get_occupied_voxel_centers()), voxels_len)
#         self.octree.delete_voxel_at_point(good_point)
#         self.assertEqual(len(self.octree.get_occupied_voxel_centers()), voxels_len - 1)


class TestOctreePointCloudSearch(unittest.TestCase):

    def setUp(self):
        self.octree = pcl.OctreePointCloudSearch(0.1)
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "table_scene_mug_stereo_textured_noplane.pcd")
        self.octree.set_input_cloud(self.p)
        self.octree.define_bounding_box()
        self.octree.add_points_from_input_cloud()

    def testConstructor(self):
        self.assertRaises(ValueError, pcl.OctreePointCloudSearch, 0.)

    def testRadiusSearch(self):
        good_point = (0.035296999, -0.074322999, 1.2074)
        rs = self.octree.radius_search(good_point, 0.5, 1)
        self.assertEqual(len(rs[0]), 1)
        self.assertEqual(len(rs[1]), 1)
        rs = self.octree.radius_search(good_point, 0.5)
        self.assertEqual(len(rs[0]), 19730)
        self.assertEqual(len(rs[1]), 19730)


class TestOctreePointCloudChangeDetector(unittest.TestCase):

    def setUp(self):
        self.octree = pcl.OctreePointCloudSearch(0.1)
        self.p = pcl.load(
            "tests" +
            os.path.sep +
            "tutorials" +
            os.path.sep +
            "table_scene_mug_stereo_textured_noplane.pcd")
        self.octree.set_input_cloud(self.p)
        self.octree.define_bounding_box()
        self.octree.add_points_from_input_cloud()

    def testConstructor(self):
        self.assertRaises(ValueError, pcl.OctreePointCloudChangeDetector, 0.)

    def testRadiusSearch(self):
        good_point = (0.035296999, -0.074322999, 1.2074)
        rs = self.octree.radius_search(good_point, 0.5, 1)
        self.assertEqual(len(rs[0]), 1)
        self.assertEqual(len(rs[1]), 1)
        rs = self.octree.radius_search(good_point, 0.5)
        self.assertEqual(len(rs[0]), 19730)
        self.assertEqual(len(rs[1]), 19730)


def suite():
    suite = unittest.TestSuite()
    # octree
    # base class
    # suite.addTests(unittest.makeSuite(TestOctreePointCloud))
    suite.addTests(unittest.makeSuite(TestOctreePointCloudSearch))
    suite.addTests(unittest.makeSuite(TestOctreePointCloudChangeDetector))
    return suite


if __name__ == '__main__':
    # unittest.main()
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
....
----------------------------------------------------------------------
Ran 4 tests in 0.561s

OK

tests/test_recognition.py

内容なし

tests/test_registration.py

In [19]:
from __future__ import print_function

import numpy as np
from numpy import cos, sin
from numpy.testing import assert_equal
import unittest

import pcl
# from pcl.pcl_registration import icp, gicp, icp_nl
from pcl import IterativeClosestPoint, GeneralizedIterativeClosestPoint, IterativeClosestPointNonLinear


class TestICP(unittest.TestCase):
    def setUp(self):
        # Check if ICP can find a mild rotation.
        theta = [-.031, .4, .59]
        rot_x = [[1, 0, 0],
                 [0, cos(theta[0]), -sin(theta[0])],
                 [0, sin(theta[0]), cos(theta[0])]]
        rot_y = [[cos(theta[1]), 0, sin(theta[1])],
                 [0, 1, 0],
                 [-sin(theta[1]), 0, cos(theta[1])]]
        rot_z = [[cos(theta[2]), -sin(theta[1]), 0],
                 [sin(theta[2]), cos(theta[1]), 0],
                 [0, 0, 1]]
        transform = np.dot(rot_x, np.dot(rot_y, rot_z))

        source = np.random.RandomState(42).randn(900, 3)
        self.source = pcl.PointCloud(source.astype(np.float32))

        target = np.dot(source, transform)
        self.target = pcl.PointCloud(target.astype(np.float32))

    def testICP(self):
        icp = self.source.make_IterativeClosestPoint()
        converged, transf, estimate, fitness = icp.icp(
            self.source, self.target, max_iter=1000)

        self.assertTrue(converged is True)
        self.assertLess(fitness, .1)

        self.assertTrue(isinstance(transf, np.ndarray))
        self.assertEqual(transf.shape, (4, 4))

        self.assertFalse(np.any(transf[:3] == 0))
        assert_equal(transf[3], [0, 0, 0, 1])

        # XXX I think I misunderstand fitness, it's not equal to the following MSS.
        # mss = (np.linalg.norm(estimate.to_array()
        #                       - self.source.to_array(), axis=1) ** 2).mean()
        # self.assertLess(mss, 1)

        # print("------", algo)
        # print("Converged: ", converged, "Estimate: ", estimate,
        #       "Fitness: ", fitness)
        # print("Rotation: ")
        # print(transf[0:3,0:3])
        # print("Translation: ", transf[3, 0:3])
        # print("---------")


class TestGICP(unittest.TestCase):
    def setUp(self):
        # Check if ICP can find a mild rotation.
        theta = [-.031, .4, .59]
        rot_x = [[1, 0, 0],
                 [0, cos(theta[0]), -sin(theta[0])],
                 [0, sin(theta[0]), cos(theta[0])]]
        rot_y = [[cos(theta[1]), 0, sin(theta[1])],
                 [0, 1, 0],
                 [-sin(theta[1]), 0, cos(theta[1])]]
        rot_z = [[cos(theta[2]), -sin(theta[1]), 0],
                 [sin(theta[2]), cos(theta[1]), 0],
                 [0, 0, 1]]
        transform = np.dot(rot_x, np.dot(rot_y, rot_z))

        source = np.random.RandomState(42).randn(900, 3)
        self.source = pcl.PointCloud(source.astype(np.float32))

        target = np.dot(source, transform)
        self.target = pcl.PointCloud(target.astype(np.float32))

    def testGICP(self):
        gicp = self.source.make_GeneralizedIterativeClosestPoint()
        converged, transf, estimate, fitness = gicp.gicp(
            self.source, self.target, max_iter=1000)

        self.assertTrue(converged is True)
        self.assertLess(fitness, .1)

        self.assertTrue(isinstance(transf, np.ndarray))
        self.assertEqual(transf.shape, (4, 4))

        self.assertFalse(np.any(transf[:3] == 0))
        assert_equal(transf[3], [0, 0, 0, 1])

        # XXX I think I misunderstand fitness, it's not equal to the following
        # MSS.
        # mss = (np.linalg.norm(estimate.to_array()
        #                       - self.source.to_array(), axis=1) ** 2).mean()
        # self.assertLess(mss, 1)

        # print("------", algo)
        # print("Converged: ", converged, "Estimate: ", estimate, "Fitness: ", fitness)
        # print("Rotation: ")
        # print(transf[0:3,0:3])
        # print("Translation: ", transf[3, 0:3])
        # print("---------")


class TestICP_NL(unittest.TestCase):
    def setUp(self):
        # Check if ICP can find a mild rotation.
        theta = [-.031, .4, .59]
        rot_x = [[1, 0, 0],
                 [0, cos(theta[0]), -sin(theta[0])],
                 [0, sin(theta[0]), cos(theta[0])]]
        rot_y = [[cos(theta[1]), 0, sin(theta[1])],
                 [0, 1, 0],
                 [-sin(theta[1]), 0, cos(theta[1])]]
        rot_z = [[cos(theta[2]), -sin(theta[1]), 0],
                 [sin(theta[2]), cos(theta[1]), 0],
                 [0, 0, 1]]
        transform = np.dot(rot_x, np.dot(rot_y, rot_z))

        source = np.random.RandomState(42).randn(900, 3)
        self.source = pcl.PointCloud(source.astype(np.float32))

        target = np.dot(source, transform)
        self.target = pcl.PointCloud(target.astype(np.float32))

    def testICP_NL(self):
        icp_nl = self.source.make_IterativeClosestPointNonLinear()
        converged, transf, estimate, fitness = icp_nl.icp_nl(
            self.source, self.target, max_iter=1000)

        self.assertTrue(converged is True)
        self.assertLess(fitness, .1)

        self.assertTrue(isinstance(transf, np.ndarray))
        self.assertEqual(transf.shape, (4, 4))

        self.assertFalse(np.any(transf[:3] == 0))
        assert_equal(transf[3], [0, 0, 0, 1])

        # XXX I think I misunderstand fitness, it's not equal to the following
        # MSS.
        # mss = (np.linalg.norm(estimate.to_array()
        #                       - self.source.to_array(), axis=1) ** 2).mean()
        # self.assertLess(mss, 1)
        # print("------", algo)
        # print("Converged: ", converged, "Estimate: ", estimate,
        #       "Fitness: ", fitness)
        # print("Rotation: ")
        # print(transf[0:3,0:3])
        # print("Translation: ", transf[3, 0:3])
        # print("---------")


_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
           1.0, 2.0, 3.2;
           2.0, 4.0, 6.2;
           3.0, 6.0, 9.2;
           4.0, 8.0, 12.2"""

# registration
### GeneralizedIterativeClosestPoint ###


class TestGeneralizedIterativeClosestPoint(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        self.reg = pcl.GeneralizedIterativeClosestPoint()


### IterativeClosestPoint ###
class TestIterativeClosestPoint(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        self.reg = pcl.IterativeClosestPoint()

#     def set_InputTarget(self, _pcl.PointCloud cloud):
#         self.me.setInputTarget (cloud.thisptr_shared)
#         pass
#
#     # def get_Resolution(self):
#     #     return self.me.getResolution()
#
#     # def get_StepSize(self):
#     #     return self.me.getStepSize()
#
#     # def set_StepSize(self, double step_size):
#     #     self.me.setStepSize(step_size)
#
#     # def get_OulierRatio(self):
#     #     return self.me.getOulierRatio()
#
#     # def set_OulierRatio(self, double outlier_ratio):
#     #     self.me.setOulierRatio(outlier_ratio)
#
#     # def get_TransformationProbability(self):
#     #     return self.me.getTransformationProbability()
#
#     # def get_FinalNumIteration(self):
#     #     return self.me.getFinalNumIteration()


### IterativeClosestPointNonLinear ###
class TestIterativeClosestPointNonLinear(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        self.reg = pcl.IterativeClosestPointNonLinear()


### NormalDistributionsTransform ###
class TestNormalDistributionsTransform(unittest.TestCase):
    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        self.reg = pcl.IterativeClosestPointNonLinear()


def suite():
    suite = unittest.TestSuite()
    suite.addTests(unittest.makeSuite(TestICP))
    suite.addTests(unittest.makeSuite(TestGICP))
    suite.addTests(unittest.makeSuite(TestICP_NL))
    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
/opt/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:37: DeprecationWarning: Non length-one string passed in for the array ordering. Please pass in 'C', 'F', 'A', or 'K' instead
./opt/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:86: DeprecationWarning: Non length-one string passed in for the array ordering. Please pass in 'C', 'F', 'A', or 'K' instead
./opt/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:135: DeprecationWarning: Non length-one string passed in for the array ordering. Please pass in 'C', 'F', 'A', or 'K' instead
.
----------------------------------------------------------------------
Ran 3 tests in 1.688s

OK

tests/test_sampleconsensus.py

In [20]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np


# _data = [(i, 2 * i, 3 * i + 0.2) for i in range(500)]

import random
_data = [(random.random(), random.random(), random.random())
         for i in range(500)]


# sample_consensus

### RandomSampleConsensus ###
class TestRandomSampleConsensus(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)

    # def test_SampleConsensusModel(self):
    #     model = pcl.SampleConsensusModel(self.p)
    #     ransac = pcl.RandomSampleConsensus (model)
    #     ransac.set_DistanceThreshold (.01)
    #     ransac.computeModel()
    #     inliers = ransac.get_Inliers()
    #
    #     # print(str(len(inliers)))
    #     self.assertNotEqual(len(inliers), 0)

    # def test_SampleConsensusModelCylinder(self):
    #     model_cy = pcl.SampleConsensusModelCylinder(self.p)
    #     ransac = pcl.RandomSampleConsensus (model_cy)
    #     ransac.set_DistanceThreshold (.01)
    #     ransac.computeModel()
    #     inliers = ransac.get_Inliers()
    #
    #     # print(str(len(inliers)))
    #     self.assertNotEqual(len(inliers), 0)

    def test_SampleConsensusModelLine(self):
        model_line = pcl.SampleConsensusModelLine(self.p)
        ransac = pcl.RandomSampleConsensus(model_line)
        ransac.set_DistanceThreshold(.01)
        ransac.computeModel()
        inliers = ransac.get_Inliers()

        # print(str(len(inliers)))
        self.assertNotEqual(len(inliers), 0)

    def test_ModelPlane(self):
        model_p = pcl.SampleConsensusModelPlane(self.p)
        ransac = pcl.RandomSampleConsensus(model_p)
        ransac.set_DistanceThreshold(.01)
        ransac.computeModel()
        inliers = ransac.get_Inliers()

        # print(str(len(inliers)))
        self.assertNotEqual(len(inliers), 0)

        final = pcl.PointCloud()

        if len(inliers) != 0:
            finalpoints = np.zeros((len(inliers), 3), dtype=np.float32)

            for i in range(0, len(inliers)):
                finalpoints[i][0] = self.p[inliers[i]][0]
                finalpoints[i][1] = self.p[inliers[i]][1]
                finalpoints[i][2] = self.p[inliers[i]][2]

            final.from_array(finalpoints)

        self.assertNotEqual(final.size, 0)
        pass

    # def test_SampleConsensusModelRegistration(self):
    #     model_reg = pcl.SampleConsensusModelRegistration(self.p)
    #     ransac = pcl.RandomSampleConsensus (model_reg)
    #     ransac.set_DistanceThreshold (.01)
    #     ransac.computeModel()
    #     inliers = ransac.get_Inliers()
    #
    #     # print(str(len(inliers)))
    #     self.assertNotEqual(len(inliers), 0)

    def test_ModelSphere(self):
        model_s = pcl.SampleConsensusModelSphere(self.p)
        ransac = pcl.RandomSampleConsensus(model_s)
        ransac.set_DistanceThreshold(.01)
        ransac.computeModel()
        inliers = ransac.get_Inliers()

        # print(str(len(inliers)))
        self.assertNotEqual(len(inliers), 0)

        final = pcl.PointCloud()

        if len(inliers) != 0:
            finalpoints = np.zeros((len(inliers), 3), dtype=np.float32)

            for i in range(0, len(inliers)):
                finalpoints[i][0] = self.p[inliers[i]][0]
                finalpoints[i][1] = self.p[inliers[i]][1]
                finalpoints[i][2] = self.p[inliers[i]][2]

            final.from_array(finalpoints)

        self.assertNotEqual(final.size, 0)
        pass

    def test_SampleConsensusModelStick(self):
        model_st = pcl.SampleConsensusModelStick(self.p)
        ransac = pcl.RandomSampleConsensus(model_st)
        ransac.set_DistanceThreshold(.01)
        ransac.computeModel()
        inliers = ransac.get_Inliers()

        # print(str(len(inliers)))
        self.assertNotEqual(len(inliers), 0)

    # def testException(self):
    #     self.assertRaises(TypeError, pcl.RandomSampleConsensus)
    #     pass


def suite():
    suite = unittest.TestSuite()

    # Sampleconsensus
    suite.addTests(unittest.makeSuite(TestRandomSampleConsensus))

    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
....
----------------------------------------------------------------------
Ran 4 tests in 0.148s

OK

tests/test_segmentation.py

In [21]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np


from nose.plugins.attrib import attr


_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
           1.0, 2.0, 3.2;
           2.0, 4.0, 6.2;
           3.0, 6.0, 9.2;
           4.0, 8.0, 12.2"""

# segmentation

### ConditionalEuclideanClustering(1.7.2/1.8.0) ###


@attr('pcl_over_17')
@attr('pcl_ver_0_4')
class TestConditionalEuclideanClustering(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        self.segment = pcl.ConditionalEuclideanClustering()

    def testInstance(self):
        assertIsInstance(type(self.segment), "ConditionalEuclideanClustering")


### EuclideanClusterExtraction ###
class TestEuclideanClusterExtraction(unittest.TestCase):
    def setUp(self):
        # self.p = pcl.PointCloud(_data)
        self.p = pcl.load(
            './examples/pcldata/tutorials/table_scene_lms400.pcd')
        # self.segment = self.p

    def testTutorial(self):
        vg = self.p.make_voxel_grid_filter()
        vg.set_leaf_size(0.01, 0.01, 0.01)
        cloud_filtered = vg.filter()
        tree = cloud_filtered.make_kdtree()

        self.segment = cloud_filtered.make_EuclideanClusterExtraction()
        self.segment.set_ClusterTolerance(0.02)
        self.segment.set_MinClusterSize(100)
        self.segment.set_MaxClusterSize(25000)
        self.segment.set_SearchMethod(tree)
        cluster_indices = self.segment.Extract()

        cloud_cluster = pcl.PointCloud()

        # print('cluster_indices : ' + str(cluster_indices.count) + " count.")
        cloud_cluster = pcl.PointCloud()
        for j, indices in enumerate(cluster_indices):
            # print('indices = ' + str(len(indices)))
            points = np.zeros((len(indices), 3), dtype=np.float32)

            for i, indice in enumerate(indices):
                points[i][0] = cloud_filtered[indice][0]
                points[i][1] = cloud_filtered[indice][1]
                points[i][2] = cloud_filtered[indice][2]

            cloud_cluster.from_array(points)


### MinCutSegmentation(1.7.2) ###
@attr('pcl_over_17')
@attr('pcl_ver_0_4')
class TestMinCutSegmentation(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        self.segment = pcl.MinCutSegmentation()

    def testTutorial(self):
        pass


### ProgressiveMorphologicalFilter ###
@attr('pcl_over_17')
@attr('pcl_ver_0_4')
class TestProgressiveMorphologicalFilter(unittest.TestCase):
    def setUp(self):
        self.p = pcl.PointCloud(_data)
        self.segment = pcl.ProgressiveMorphologicalFilter()

    def testTutorial(self):
        pass


# copy the output of seg
SEGDATA = """ 0.352222 -0.151883  2;
             -0.106395 -0.397406  1;
             -0.473106  0.292602  1;
             -0.731898  0.667105 -2;
              0.441304 -0.734766  1;
              0.854581 -0.0361733 1;
             -0.4607   -0.277468  4;
             -0.916762  0.183749  1;
              0.968809  0.512055  1;
             -0.998983 -0.463871  1;
              0.691785  0.716053  1;
              0.525135 -0.523004  1;
              0.439387  0.56706   1;
              0.905417 -0.579787  1;
              0.898706 -0.504929  1"""

SEGINLIERS = """-0.106395 -0.397406  1;
                -0.473106  0.292602  1;
                 0.441304 -0.734766  1;
                 0.854581 -0.0361733 1;
                -0.916762  0.183749  1;
                 0.968809  0.512055  1;
                -0.998983 -0.463871  1;
                 0.691785  0.716053  1;
                 0.525135 -0.523004  1;
                 0.439387  0.56706   1;
                 0.905417 -0.579787  1;
                 0.898706 -0.504929  1"""
SEGINLIERSIDX = [1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]

SEGCOEFF = [0.0, 0.0, 1.0, -1.0]

### Segmentation ###
# class TestSegmentation(unittest.TestCase):


class TestSegmentPlane(unittest.TestCase):

    def setUp(self):
        self.a = np.array(np.mat(SEGDATA, dtype=np.float32))
        self.p = pcl.PointCloud()
        self.p.from_array(self.a)
        self.segment = self.p.make_segmenter()

    def testLoad(self):
        npts = self.a.shape[0]
        self.assertEqual(npts, self.p.size)
        self.assertEqual(npts, self.p.width)
        self.assertEqual(1, self.p.height)

    def testSegmentPlaneObject(self):
        seg = self.p.make_segmenter()
        seg.set_optimize_coefficients(True)
        seg.set_model_type(pcl.SACMODEL_PLANE)
        seg.set_method_type(pcl.SAC_RANSAC)
        seg.set_distance_threshold(0.01)

        indices, coefficients = seg.segment()
        self.assertListEqual(indices, SEGINLIERSIDX)
        self.assertListEqual(coefficients, SEGCOEFF)
        pass


### SegmentationNormal ###
class TestSegmentationNormal(unittest.TestCase):
    def setUp(self):
        # self.a = np.array(np.mat(SEGDATA, dtype=np.float32))
        # self.p = pcl.PointCloud()
        # self.p.from_array(self.a)
        cloud = pcl.load('tests'  + os.path.sep + 'tutorials'  + os.path.sep + 'table_scene_mug_stereo_textured.pcd')
        
        fil = cloud.make_passthrough_filter()
        fil.set_filter_field_name("z")
        fil.set_filter_limits(0, 1.5)
        cloud_filtered = fil.filter()

        seg = cloud_filtered.make_segmenter_normals(ksearch=50)
        seg.set_optimize_coefficients(True)
        seg.set_model_type(pcl.SACMODEL_NORMAL_PLANE)
        seg.set_normal_distance_weight(0.1)
        seg.set_method_type(pcl.SAC_RANSAC)
        seg.set_max_iterations(100)
        seg.set_distance_threshold(0.03)
        indices, model = seg.segment()
        
        self.p = cloud_filtered.extract(indices, negative=True)
        
        self.segment = self.p.make_segmenter_normals(ksearch=50)
        # self.segment = pcl.SegmentationNormal()
        # self.segment.setInputCloud(self.p)

    # def testLoad(self):
    #     npts = self.a.shape[0]
    #     self.assertEqual(npts, self.p.size)
    #     self.assertEqual(npts, self.p.width)
    #     self.assertEqual(1, self.p.height)


    def testSegmentNormalCylinderObject(self):
        self.segment.set_optimize_coefficients(True)
        self.segment.set_model_type(pcl.SACMODEL_CYLINDER)
        self.segment.set_normal_distance_weight(0.1)
        self.segment.set_method_type(pcl.SAC_RANSAC)
        self.segment.set_max_iterations(10000)
        self.segment.set_distance_threshold(0.05)
        self.segment.set_radius_limits(0, 0.1)

        self.segment.set_axis(1.0, 0.0, 0.0)
        expected = np.array([1.0, 0.0, 0.0])
        param = self.segment.get_axis()
        self.assertEqual(param.tolist(), expected.tolist())
        epsAngle = 35.0
        expected = epsAngle / 180.0 * 3.14
        self.segment.set_eps_angle(epsAngle / 180.0 * 3.14)
        param = self.segment.get_eps_angle()
        self.assertEqual(param, expected)

        indices, coefficients = self.segment.segment()
        # self.assertListEqual(indices, SEGINLIERSIDX)
        # self.assertListEqual(coefficients, SEGCOEFF)

        epsAngle = 50.0
        expected2 = epsAngle / 180.0 * 3.14
        self.segment.set_eps_angle(epsAngle / 180.0 * 3.14)
        param2 = self.segment.get_eps_angle()
        self.assertEqual(param2, expected2)
        self.assertNotEqual(param, param2)
        
        indices2, coefficients2 = self.segment.segment()
        # self.assertListEqual(indices2, SEGINLIERSIDX)
        # self.assertListEqual(coefficients2, SEGCOEFF)
        
        # print(len(indices))
        # print(coefficients)
        
        # print(len(indices2))
        # print(coefficients2)
        
        self.assertNotEqual(len(indices), len(indices2))
        # self.assertListNotEqual(coefficients, coefficients2)
        pass


def suite():
    suite = unittest.TestSuite()

    # segmentation
    suite.addTests(unittest.makeSuite(TestEuclideanClusterExtraction))
    # suite.addTests(unittest.makeSuite(TestSegmentation))
    suite.addTests(unittest.makeSuite(TestSegmentPlane))
    suite.addTests(unittest.makeSuite(TestSegmentationNormal))
    # 1.7.2/1.8.0
    # suite.addTests(unittest.makeSuite(TestConditionalEuclideanClustering))
    # suite.addTests(unittest.makeSuite(TestMinCutSegmentation))
    # suite.addTests(unittest.makeSuite(TestProgressiveMorphologicalFilter))

    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
....
----------------------------------------------------------------------
Ran 4 tests in 1.844s

OK

tests/test_surface.py

In [2]:
import os
os.chdir('./python-pcl-master')  # 同じディレクトリに python-pcl-masterデイレクトリがあるとする
In [3]:
import os.path
import pickle
import shutil
import tempfile
import unittest

import pcl
import numpy as np


from nose.plugins.attrib import attr


# surface
### ConcaveHull ###
class TestConcaveHull(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        self.surf = self.p.make_ConcaveHull()
        # self.surf = pcl.ConcaveHull()
        # self.surf.setInputCloud()

    def testreconstruct(self):
        alpha = 1.0
        self.surf.set_Alpha(alpha)
        clonepc = self.surf.reconstruct()
        # new instance is returned
        self.assertNotEqual(self.p, clonepc)
        # concavehull retains the same number of points?
        self.assertNotEqual(self.p.size, clonepc.size)


### MovingLeastSquares ###
class TestMovingLeastSquares(unittest.TestCase):

    def setUp(self):
        self.p = pcl.load("tests" + os.path.sep + "flydracyl.pcd")
        self.surf = self.p.make_moving_least_squares()

    def testFilter(self):
        self.surf.set_search_radius(0.5)
        self.surf.set_polynomial_order(2)
        self.surf.set_polynomial_fit(True)
        f = self.surf.process()
        # new instance is returned
        self.assertNotEqual(self.p, f)
        # mls filter retains the same number of points
        self.assertEqual(self.p.size, f.size)


def suite():
    suite = unittest.TestSuite()

    # surface
    suite.addTests(unittest.makeSuite(TestConcaveHull))
    suite.addTests(unittest.makeSuite(TestMovingLeastSquares))

    return suite


if __name__ == '__main__':
    testSuite = suite()
    unittest.TextTestRunner().run(testSuite)
..
----------------------------------------------------------------------
Ran 2 tests in 0.403s

OK

examples

3dharris.py             crophull.py  official              simple_visualize.py
GrabberCallbackTest.py  example.py   pcldata               statistical_outlier_fiter.py
HarrisKeypoint3D.py     external     segment_cyl_plane.py  visualization.py
cropbox.py              kdtree.py    sift.py

examples/visualization.py

Viewerの操作方法

  • 左ドラッグ:視点の回転
  • Shift+左ドラッグ:視点の平行移動
  • Ctrl+左ドラッグ:画面上の回転
  • 右ドラッグ:ズーム
  • g:メジャーの表示
  • j:スクリーンショットの保存
In [12]:
import os
os.chdir('./python-pcl-master')  # 同じディレクトリに python-pcl-masterデイレクトリがあるとする
In [5]:
# -*- coding: utf-8 -*-
from __future__ import print_function

import numpy as np
import pcl

import pcl.pcl_visualization
# from pcl.pcl_registration import icp, gicp, icp_nl

cloud = pcl.load_XYZRGB('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd')
visual = pcl.pcl_visualization.CloudViewing()

# PointXYZ
# visual.ShowMonochromeCloud(cloud)

# visual.ShowGrayCloud(cloud, b'cloud')
visual.ShowColorCloud(cloud, b'cloud')
# visual.ShowColorACloud(cloud, b'cloud')

# while True:
#     visual.WasStopped()
# end

flag = True
while flag:
    flag != visual.WasStopped()
end
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-5-70cf994ea617> in <module>()
     24 flag = True
     25 while flag:
---> 26     flag != visual.WasStopped()
     27 end
     28 

KeyboardInterrupt: 

マウス操作を工夫すると次のようなものが見える: example_visualization.png

examples/simple_visualize.py

動かず(エラーあり)

examples/statistical_outlier_fiter.py

In [3]:
# -*- coding: utf-8 -*-
# port of
# http://pointclouds.org/documentation/tutorials/statistical_outlier.php
# you need to download
# http://svn.pointclouds.org/data/tutorials/table_scene_lms400.pcd

import pcl
p = pcl.load("table_scene_lms400.pcd")

fil = p.make_statistical_outlier_filter()
fil.set_mean_k(50)
fil.set_std_dev_mul_thresh(1.0)

pcl.save(fil.filter(), "table_scene_lms400_inliers.pcd")

fil.set_negative(True)
pcl.save(fil.filter(), "table_scene_lms400_outliers.pcd")

table_scene_lms400_outliers.pcdtable_scene_lms400_inliers.pcdが作られている。Open3Dを用いて表示させてみる; (この用途にはOpen3Dの方が楽そう)

In [7]:
import py3d
pcd = py3d.read_point_cloud("table_scene_lms400_outliers.pcd")
py3d.draw_geometries([pcd])
In [8]:
import py3d
pcd = py3d.read_point_cloud("table_scene_lms400_inliers.pcd")
py3d.draw_geometries([pcd])
In [10]:
import py3d
pcd = py3d.read_point_cloud("table_scene_lms400.pcd")
py3d.draw_geometries([pcd])

画像の見比べ: 元画像、外れ値、外れ値を除去したもの


examples/segment_cyl_plane.py

In [ ]:
import os
os.chdir('./python-pcl-master')  # 同じディレクトリに python-pcl-masterデイレクトリがあるとする
In [13]:
# -*- coding: utf-8 -*-
# port of
# http://pointclouds.org/documentation/tutorials/cylinder_segmentation.php
# you need to download
# http://svn.pointclouds.org/data/tutorials/table_scene_mug_stereo_textured.pcd

import pcl

cloud = pcl.load('table_scene_mug_stereo_textured.pcd')

print(cloud.size)

fil = cloud.make_passthrough_filter()
fil.set_filter_field_name("z")
fil.set_filter_limits(0, 1.5)
cloud_filtered = fil.filter()

print(cloud_filtered.size)

seg = cloud_filtered.make_segmenter_normals(ksearch=50)
seg.set_optimize_coefficients(True)
seg.set_model_type(pcl.SACMODEL_NORMAL_PLANE)
seg.set_normal_distance_weight(0.1)
seg.set_method_type(pcl.SAC_RANSAC)
seg.set_max_iterations(100)
seg.set_distance_threshold(0.03)
indices, model = seg.segment()

print(model)

cloud_plane = cloud_filtered.extract(indices, negative=False)
# NG : const char* not str
# cloud_plane.to_file('table_scene_mug_stereo_textured_plane.pcd')
pcl.save(cloud_plane, 'table_scene_mug_stereo_textured_plane.pcd')

cloud_cyl = cloud_filtered.extract(indices, negative=True)

seg = cloud_cyl.make_segmenter_normals(ksearch=50)
seg.set_optimize_coefficients(True)
seg.set_model_type(pcl.SACMODEL_CYLINDER)
seg.set_normal_distance_weight(0.1)
seg.set_method_type(pcl.SAC_RANSAC)
seg.set_max_iterations(10000)
seg.set_distance_threshold(0.05)
seg.set_radius_limits(0, 0.1)
indices, model = seg.segment()

print(model)

cloud_cylinder = cloud_cyl.extract(indices, negative=False)
# NG : const char* not str
# cloud_cylinder.to_file("table_scene_mug_stereo_textured_cylinder.pcd")
pcl.save(cloud_cylinder, 'table_scene_mug_stereo_textured_cylinder.pcd')
307200
139897
[0.01618809811770916, -0.8376763463020325, -0.5459269285202026, 0.5288504362106323]
[0.06194264069199562, -0.150542750954628, 0.6229067444801331, 0.027742745354771614, -0.8355609178543091, -0.5486971139907837, 0.03879779577255249]

table_scene_mug_stereo_textured.pcdからtable_scene_mug_stereo_textured_plane.pcdを作っている。2つを比べる:

In [15]:
import py3d
pcd = py3d.read_point_cloud("table_scene_mug_stereo_textured.pcd")
py3d.draw_geometries([pcd])
pcd2 = py3d.read_point_cloud("table_scene_mug_stereo_textured_plane.pcd")
py3d.draw_geometries([pcd2])

比較:

examples/kdtree.py

In [1]:
import os
os.chdir('./python-pcl-master')  # 同じディレクトリに python-pcl-masterデイレクトリがあるとする
In [2]:
# -*- coding: utf-8 -*-

from __future__ import print_function

import numpy as np
import pcl

points_1 = np.array([[0, 0, 0],
                     [1, 0, 0],
                     [0, 1, 0],
                     [1, 1, 0]], dtype=np.float32)
points_2 = np.array([[0, 0, 0.2],
                     [1, 0, 0],
                     [0, 1, 0],
                     [1.1, 1, 0.5]], dtype=np.float32)

pc_1 = pcl.PointCloud()
pc_1.from_array(points_1)
pc_2 = pcl.PointCloud()
pc_2.from_array(points_2)
kd = pcl.KdTreeFLANN(pc_1)

print('pc_1:')
print(points_1)
print('\npc_2:')
print(points_2)
print('\n')

pc_1 = pcl.PointCloud(points_1)
pc_2 = pcl.PointCloud(points_2)
kd = pc_1.make_kdtree_flann()

# find the single closest points to each point in point cloud 2
# (and the sqr distances)
indices, sqr_distances = kd.nearest_k_search_for_cloud(pc_2, 1)
for i in range(pc_1.size):
    print('index of the closest point in pc_1 to point %d in pc_2 is %d'
          % (i, indices[i, 0]))
    print('the squared distance between these two points is %f'
          % sqr_distances[i, 0])
pc_1:
[[0. 0. 0.]
 [1. 0. 0.]
 [0. 1. 0.]
 [1. 1. 0.]]

pc_2:
[[0.  0.  0.2]
 [1.  0.  0. ]
 [0.  1.  0. ]
 [1.1 1.  0.5]]


index of the closest point in pc_1 to point 0 in pc_2 is 0
the squared distance between these two points is 0.040000
index of the closest point in pc_1 to point 1 in pc_2 is 1
the squared distance between these two points is 0.000000
index of the closest point in pc_1 to point 2 in pc_2 is 2
the squared distance between these two points is 0.000000
index of the closest point in pc_1 to point 3 in pc_2 is 3
the squared distance between these two points is 0.260000

examples/crophull.py

In [4]:
# -*- coding: utf-8 -*-
from __future__ import print_function

import numpy as np
import pcl

# http://www.pcl-users.org/CropHull-filter-question-td4030345.html
datacloud = pcl.load('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd')

print(datacloud)

filterCloud = pcl.PointCloud()
vt = pcl.Vertices()

# // inside point
# cloud->push_back(pcl::PointXYZ(M_PI * 0.3, M_PI * 0.3, 0));
# // hull points
# cloud->push_back(pcl::PointXYZ(0,0,0));
# cloud->push_back(pcl::PointXYZ(M_PI,0,0));
# cloud->push_back(pcl::PointXYZ(M_PI,M_PI*0.5,0));
# cloud->push_back(pcl::PointXYZ(0,M_PI*0.5,0));
# cloud->push_back(pcl::PointXYZ(0,0,0));
# // outside point
# cloud->push_back(pcl::PointXYZ(-M_PI * 0.3, -M_PI * 0.3, 0));

points_2 = np.array([
                        [1 * 0.3, 1 * 0.3, 0],
                        [0, 0, 0],
                        [1, 0, 0],
                        [1, 1 * 0.5, 0],
                        [0, 1 * 0.5, 0],
                        [0, 0, 0],
                        [-1 * 0.3 , -1 * 0.3, 0]
                    ], dtype=np.float32)
filterCloud.from_array(points_2)
print(filterCloud)

vertices_point_1 = np.array([1, 2, 3, 4, 5], dtype=np.int)
vt.from_array(vertices_point_1)

# print(vt)
# vt.vertices.push_back(1)
# vt.vertices.push_back(2)
# vt.vertices.push_back(3)
# vt.vertices.push_back(4)
# vt.vertices.push_back(5)
# vertices = vector[pcl.Vertices]
# vertices.push_back(vt)

outputCloud = pcl.PointCloud()
# crophull = pcl.CropHull()
# crophull.setInputCloud(datacloud)
crophull = datacloud.make_crophull()
# crophull.setHullIndices(vertices)
# crophull.setHullIndices(vt)
# crophull.setHullCloud(filterCloud)
# crophull.setDim(2)
# crophull.setCropOutside(false)
crophull.SetParameter(filterCloud, vt)

# indices = vector[int]
# cropHull.filter(indices);
# outputCloud = cropHull.filter();
# print("before: " + outputCloud)
crophull.Filtering(outputCloud)
print(outputCloud)


# Viewer
# // pcl::visualization::CloudViewer viewer ("Cluster viewer");
# // viewer.showCloud(colored_cloud);

# pcl.visualization.CloudViewer

# Write Point
# pcl::PCDWriter writer;
# std::stringstream ss;
# ss << "min_cut_seg" << ".pcd";
# // writer.write<pcl::PointXYZRGB> (ss.str (), *cloud, false);
# pcl::io::savePCDFile(ss.str(), *outputCloud, false);
<PointCloud of 307200 points>
<PointCloud of 7 points>
filter: outputCloud size = 307200
<PointCloud of 307200 points>

examples/cropbox.py

clipper.Filtering(outcloud)でエラー

examples/HarrisKeypoint3D.py

In [10]:
# -*- coding: utf-8 -*-
# http://virtuemarket-lab.blogspot.jp/2015/03/harris.html

from __future__ import print_function

import numpy as np
import pcl

import pcl.pcl_visualization

# pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
# pcl::io::loadPCDFile<pcl::PointXYZ> (argv[1], *cloud);
# cloud = pcl.load_XYZRGB('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd')
cloud = pcl.load('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd')

# pcl::HarrisKeypoint3D<pcl::PointXYZ,pcl::PointXYZI> detector;
# detector.setNonMaxSupression (true);
# detector.setRadius (0.01);
# //detector.setRadiusSearch (100);
# detector.setInputCloud(cloud);
detector = cloud.make_HarrisKeypoint3D()

# pcl::PointCloud<pcl::PointXYZI>::Ptr keypoints(new pcl::PointCloud<pcl::PointXYZI>());
# detector.compute(*keypoints);
keypoints = detector.compute()

# std::cout << "keypoints detected: " << keypoints->size() << std::endl;

# pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints3D(new pcl::PointCloud<pcl::PointXYZ>());
# pcl::PointXYZ tmp;
# double max = 0,min=0;
# 
# for(pcl::PointCloud<pcl::PointXYZI>::iterator i = keypoints->begin(); i!= keypoints->end(); i++){
#     tmp = pcl::PointXYZ((*i).x,(*i).y,(*i).z);
#     if ((*i).intensity>max ){
#         std::cout << (*i) << " coords: " << (*i).x << ";" << (*i).y << ";" << (*i).z << std::endl;
#         max = (*i).intensity;
#     }
#     if ((*i).intensity<min){
#         min = (*i).intensity;
#     }
#     keypoints3D->push_back(tmp);
# }
# 
# std::cout << "maximal responce: "<< max << " min responce:  "<< min<<std::endl;
# 
# //show point cloud
# pcl::visualization::PCLVisualizer viewer ("3D Viewer");
viewer = pcl.pcl_visualization.PCLVisualizering(b"3D Viewer")

# pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> pccolor(cloud, 255, 255, 255);
# pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> kpcolor(keypoints3D, 255, 0, 0);
pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud, 255, 255, 255)
# kpcolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(keypoints3D, 255, 0, 0)
kpcolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(keypoints, 255, 0, 0)


viewer.addPointCloud(cloud,pccolor,"testimg.png");
viewer.addPointCloud(keypoints3D,kpcolor,"keypoints.png");
# viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "keypoints.png");


while True:
    # viewer.wasStopped()
    viewer.spinOnce()
    # pcl_sleep (0.01)
end
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-4314bd5142d2> in <module>()
     53 pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud, 255, 255, 255)
     54 # kpcolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(keypoints3D, 255, 0, 0)
---> 55 kpcolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(keypoints, 255, 0, 0)
     56 
     57 

TypeError: Argument 'pc' has incorrect type (expected pcl._pcl.PointCloud, got pcl._pcl.PointCloud_PointXYZI)
In [11]:
keypoints
Out[11]:
<PointCloud of 1570 points>
In [12]:
cloud
Out[12]:
<PointCloud of 307200 points>

エラーは出ているが、keypointsは得られているようである。

examples/3dharris.py

In [1]:
import os
os.chdir('./python-pcl-master')  # 同じディレクトリに python-pcl-masterデイレクトリがあるとする
In [2]:
# -*- coding: utf-8 -*-
# http://virtuemarket-lab.blogspot.jp/2015/03/harris.html
import pcl
import numpy as np
import pcl.pcl_visualization

# pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
# pcl::io::loadPCDFile<pcl::PointXYZ> (argv[1], *cloud);
# cloud = pcl.load("table_scene_mug_stereo_textured.pcd")
# cloud = pcl.load('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd')
cloud = pcl.load('./bunny.pcd')
print("cloud points : " + str(cloud.size))

# pcl::HarrisKeypoint3D<pcl::PointXYZ, pcl::PointXYZI> detector;
# detector.setNonMaxSupression (true);
# detector.setRadius (0.01);
# //detector.setRadiusSearch (100);
# detector.setInputCloud(cloud);
# pcl::PointCloud<pcl::PointXYZI>::Ptr keypoints(new pcl::PointCloud<pcl::PointXYZI>());
# detector.compute(*keypoints);
###
detector = cloud.make_HarrisKeypoint3D()
detector.set_NonMaxSupression (True)
detector.set_Radius (0.01)
# detector.set_NonMaxSupression (False)
# detector.set_RadiusSearch (100)
keypoints = detector.compute()

# std::cout << "keypoints detected: " << keypoints->size() << std::endl;
print("keypoints detected: " + str(keypoints.size))

# pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints3D(new pcl::PointCloud<pcl::PointXYZ>());
# pcl::PointXYZ tmp;
# double max = 0,min=0;
# for(pcl::PointCloud<pcl::PointXYZI>::iterator i = keypoints->begin(); i!= keypoints->end(); i++)
#     tmp = pcl::PointXYZ((*i).x,(*i).y,(*i).z);
#     if ((*i).intensity>max )
#         std::cout << (*i) << " coords: " << (*i).x << ";" << (*i).y << ";" << (*i).z << std::endl;
#         max = (*i).intensity;
#     if ((*i).intensity<min)
#         min = (*i).intensity;
#     keypoints3D->push_back(tmp);
# 
# std::cout << "maximal responce: "<< max << " min responce:  "<< min<<std::endl;
###
keypoints3D = pcl.PointCloud()
max = -999
min = 999

count = 0
points = np.zeros((keypoints.size, 3), dtype=np.float32)
# Generate the data
for i in range(0, keypoints.size):
    # set Point Plane
    points[i][0] = keypoints[i][0]
    points[i][1] = keypoints[i][1]
    points[i][2] = keypoints[i][2]
    intensity = keypoints[i][3]
    if intensity > max:
        print("coords: " + str(keypoints[i][0]) + ";" + str(keypoints[i][1]) + ";" + str(keypoints[i][2]) )
        max = intensity
    
    if intensity < min:
        min = intensity
    
    count = count + 1

points.resize(count, 3)
print(points)
keypoints3D.from_array(points)
print("maximal responce: " + str(max) + " min responce:  " +  str(min) )

# //show point cloud
# pcl::visualization::PCLVisualizer viewer ("3D Viewer");
# pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> pccolor(cloud, 255, 255, 255);
# pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> kpcolor(keypoints3D, 255, 0, 0);
# viewer.addPointCloud(cloud, pccolor, "testimg.png");
# viewer.addPointCloud(keypoints3D, kpcolor,"keypoints.png");
# viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "keypoints.png");
##
viewer = pcl.pcl_visualization.PCLVisualizering('3D Viewer')
pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud, 255, 255, 255)
kpcolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(keypoints3D, 255, 0, 0)
# OK
viewer.AddPointCloud_ColorHandler(cloud, pccolor)
viewer.AddPointCloud_ColorHandler(keypoints3D, kpcolor, b'keypoints')

# viewer.AddPointCloud_ColorHandler(cloud, pccolor, "testimg.png", 0)
# viewer.AddPointCloud_ColorHandler(keypoints3D, kpcolor, str('keypoints.png'), 0)
# need? : AddPointCloud_ColorHandler Function Succeded
# viewer.SetPointCloudRenderingProperties (pcl.pcl_visualization.PCLVISUALIZER_POINT_SIZE, 7, b'keypoints.png')
###


# while (!viewer.wasStopped ())
# {
#     viewer.spinOnce();
#     pcl_sleep (0.01);
# }
flag = True
while flag:
    flag != viewer.WasStopped()
    viewer.SpinOnce()
    # pcl_sleep (0.01)
    # pass
end
cloud points : 397
keypoints detected: 48
coords: 0.008803367614746094;0.12533354759216309;0.032472848892211914
coords: 0.022958189249038696;0.12180620431900024;0.029725193977355957
coords: -0.06679463386535645;0.15040969848632812;0.03853964805603027
coords: -0.0672549307346344;0.11913353204727173;0.05214541777968407
coords: -0.05888630822300911;0.11652494221925735;0.0369887575507164
coords: 0.04757946729660034;0.07463118433952332;0.018482357263565063
[[ 8.80336761e-03  1.25333548e-01  3.24728489e-02]
 [ 2.29581892e-02  1.21806204e-01  2.97251940e-02]
 [-1.02650002e-02  1.24771118e-01  3.22611332e-02]
 [-5.65960258e-03  1.19927406e-01  3.86121869e-02]
 [-6.67946339e-02  1.50409698e-01  3.85396481e-02]
 [-6.72549307e-02  1.19133532e-01  5.21454178e-02]
 [-5.69235086e-02  1.53829098e-01  2.92544961e-02]
 [-7.66791403e-02  1.52377486e-01  3.58667374e-02]
 [-5.55229187e-02  1.42379761e-01  2.61909962e-02]
 [-2.57548094e-02  1.20699167e-01  2.91160345e-02]
 [-4.29817438e-02  1.25993729e-01  2.35350728e-02]
 [-1.26953125e-01  7.37304688e-02  7.69042969e-02]
 [-5.88863082e-02  1.16524942e-01  3.69887576e-02]
 [ 3.34615707e-02  9.25931036e-02  4.11060452e-02]
 [-1.78869963e-02  9.11418498e-02  5.56671321e-02]
 [-5.65960258e-03  1.19927406e-01  3.86121869e-02]
 [ 1.72705293e-01 -3.26472378e+00  4.03933048e-01]
 [ 1.89194679e-02  7.60166049e-02  5.19012213e-02]
 [ 1.72705293e-01 -3.26472378e+00  4.03933048e-01]
 [-1.59264654e-02  5.17210141e-02  4.97783720e-02]
 [ 9.65219736e-03  4.45775092e-02  4.68915105e-02]
 [ 3.35560739e-03  3.85417938e-02  4.59471345e-02]
 [ 4.31240797e-02  9.55500007e-02  2.36874819e-02]
 [ 4.75794673e-02  7.46311843e-02  1.84823573e-02]
 [ 3.56364250e-02  6.76779151e-02  3.82358432e-02]
 [ 4.44301218e-02  4.97595444e-02  3.18387672e-02]
 [ 3.09802778e-02  4.18864191e-02  2.91089304e-02]
 [-2.34087706e-02  8.63578990e-02  5.46382666e-02]
 [-3.28187943e-02  8.54410604e-02  4.44806516e-02]
 [-5.18250018e-02  8.68439972e-02  4.49329987e-02]
 [-5.80749512e-02  1.68609619e-01  8.52737427e-02]
 [-2.74107605e-02  4.37334776e-02  5.26887178e-02]
 [-4.18842845e-02  3.65111828e-02  4.45995331e-02]
 [-5.66771626e-02  3.89667749e-02  4.78265285e-02]
 [ 2.34375000e-02  1.43676758e-01 -1.46484375e-02]
 [-8.73274803e-02  9.06946138e-02  2.56974697e-02]
 [-8.00857544e-02  7.96121061e-02  3.25359702e-02]
 [-8.25000033e-02  7.46740028e-02  7.11750006e-03]
 [-2.77989805e-02  5.98949045e-02  3.73839363e-02]
 [-4.17973548e-02  5.03136814e-02  3.87026593e-02]
 [-5.61876297e-02  5.02843857e-02  9.42087173e-03]
 [-5.61876297e-02  5.02843857e-02  9.42087173e-03]
 [-1.21655464e-02  1.76343679e-01 -2.25515366e-02]
 [-3.35482657e-02  1.54854059e-01  8.80405307e-04]
 [-3.91432792e-02  1.68269351e-01  1.10901892e-03]
 [-7.26021528e-02  1.59154892e-01 -8.32748413e-03]
 [-7.50203133e-02  1.73225403e-01 -3.91578674e-02]
 [-7.50203133e-02  1.73225403e-01 -3.91578674e-02]]
maximal responce: 0.01632295921444893 min responce:  0.0
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-2-b19293a305f9> in <module>()
    100 flag = True
    101 while flag:
--> 102     flag != viewer.WasStopped()
    103     viewer.SpinOnce()
    104     # pcl_sleep (0.01)

KeyboardInterrupt: