コード例 #1
0
ファイル: procrustes.py プロジェクト: kod3r/menpo
    def _recursive_procrustes(self):
        r"""
        Recursively calculates a procrustes alignment.
        """
        from menpo.shape import PointCloud

        if self.n_iterations > self.max_iterations:
            return False
        av_aligned_source = sum(t.aligned_source.points for t in self.transforms) / self.n_sources
        new_target = PointCloud(av_aligned_source)
        # rescale the new_target to be the same size as the original about
        # it's centre
        rescale = UniformScale(self.initial_target_scale / new_target.norm(), self.n_dims)
        centre = Translation(-new_target.centre)
        rescale_about_centre = centre.compose_before(rescale).compose_before(centre.pseudoinverse)
        rescale_about_centre.apply_inplace(new_target)
        # check to see if  we have converged yet
        delta_target = np.linalg.norm(self.target.points - new_target.points)
        if delta_target < 1e-6:
            return True
        else:
            self.n_iterations += 1
            for t in self.transforms:
                t.set_target(new_target)
            self.target = new_target
            return self._recursive_procrustes()
コード例 #2
0
ファイル: pointcloud_test.py プロジェクト: nontas/menpo
def test_pointcloud_bounding_box_3d():
    points = np.array([[1.0, 2.0, 3.0], [3.0, 2.0, 1.0]])
    pc = PointCloud(points)
    bb = pc.bounding_box()
    bb_bounds = bb.bounds()
    assert_allclose(bb_bounds[0], [1.0, 2.0, 1.0])
    assert_allclose(bb_bounds[1], [3.0, 2.0, 3.0])
コード例 #3
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_centre():
    points = np.array([[0, 0],
                       [1., 1],
                       [0, 2]])
    pc = PointCloud(points)
    c = pc.centre()
    assert_allclose(c, [1. / 3., 1.])
コード例 #4
0
ファイル: modeldriven.py プロジェクト: KeeganRen/menpofit
    def sparse_target(self):
        r"""
        The current sparse `menpo.shape.PointCloud` that this object produces.

        :type: `menpo.shape.PointCloud`
        """
        sparse_target = PointCloud(self.target.points[:self.n_landmarks])
        return self._sparse_instance.from_vector(sparse_target.as_vector())
コード例 #5
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_centre_of_bounds():
    points = np.array([[0, 0],
                       [1., 1],
                       [0, 2]])
    pc = PointCloud(points)
    cb = pc.centre_of_bounds()
    assert_allclose(cb, [0.5, 1.])
    assert 1
コード例 #6
0
ファイル: pointcloud_test.py プロジェクト: nontas/menpo
def test_pointcloud_flatten_rebuild():
    points = np.array([[1, 2, 3], [1, 1, 1]])
    pc = PointCloud(points)
    flattened = pc.as_vector()
    new_pc = pc.from_vector(flattened)
    assert np.all(new_pc.n_dims == pc.n_dims)
    assert np.all(new_pc.n_points == pc.n_points)
    assert np.all(pc.points == new_pc.points)
コード例 #7
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_bounding_box():
    points = np.array([[0, 0],
                       [1., 1],
                       [0, 2]])
    pc = PointCloud(points)
    bb = pc.bounding_box()
    bb_bounds = bb.bounds()
    assert_allclose(bb_bounds[0], [0., 0.])
    assert_allclose(bb_bounds[1], [1., 2.])
コード例 #8
0
ファイル: pointcloud_test.py プロジェクト: nontas/menpo
def test_pointcloud_copy_method():
    points = np.array([[1, 2, 3], [1, 1, 1]])
    landmarks = PointCloud(np.ones([3, 3]), copy=False)

    p = PointCloud(points, copy=False)
    p.landmarks["test"] = landmarks
    p_copy = p.copy()

    assert not is_same_array(p_copy.points, p.points)
    assert not is_same_array(p_copy.landmarks["test"].lms.points, p.landmarks["test"].lms.points)
コード例 #9
0
ファイル: fitter.py プロジェクト: HaoyangWang/menpo3d
    def _align_mean_shape_with_bbox(self, bbox):
        # Convert 3D landmarks to 2D by removing the Z axis
        template_shape = PointCloud(self.mm.landmarks.points[:, [1, 0]])

        # Rotation that flips over x axis
        rot_matrix = np.eye(template_shape.n_dims)
        rot_matrix[0, 0] = -1
        template_shape = Rotation(rot_matrix,
                                  skip_checks=True).apply(template_shape)

        # Align the 2D landmarks' bbox with the provided bbox
        return AlignmentSimilarity(template_shape.bounding_box(),
                                   bbox).apply(template_shape)
コード例 #10
0
ファイル: viewmayavi.py プロジェクト: grigorisg9gr/menpo3d
def _parse_marker_size(marker_size, points):
    if marker_size is None:
        from menpo.shape import PointCloud
        from scipy.spatial.distance import squareform
        pc = PointCloud(points, copy=False)
        if 1 < pc.n_points < 1000:
            d = squareform(pc.distance_to(pc))
            d.sort()
            min_10pc = d[int(d.shape[0] / 10)]
            marker_size = min_10pc / 5
        else:
            marker_size = 0.1
    return marker_size
コード例 #11
0
def test_LandmarkManager_group_order():
    points = np.ones((10, 3))
    pcloud = PointCloud(points, copy=False)
    target = PointCloud(points)

    man = LandmarkManager()
    man['test_set'] = pcloud.copy()
    man['abc'] = pcloud.copy()
    man['def'] = pcloud.copy()
    assert_equal(list(man._landmark_groups.keys()), ['test_set', 'abc', 'def'])
    # check that after deleting and inserting the order will remain the same.
    del man['test_set']
    man['tt'] = pcloud.copy()
    assert_equal(list(man._landmark_groups.keys()), ['abc', 'def', 'tt'])
コード例 #12
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_from_depth_image():
    fake_z = np.random.uniform(size=(10, 10))
    pc = PointCloud.init_from_depth_image(Image(fake_z))
    assert pc.n_points == 100
    assert pc.n_dims == 3
    assert_allclose(pc.range()[:2], [9, 9])
    assert pc.points[:, -1].max() <= 1.0
    assert pc.points[:, -1].min() >= 0.0
コード例 #13
0
def test_constrain_landmarks_to_bounds():
    im = Image.init_blank((10, 10))
    im.landmarks['test'] = PointCloud.init_2d_grid((20, 20))
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        im.constrain_landmarks_to_bounds()
    assert not im.has_landmarks_outside_bounds()
    assert_allclose(im.landmarks['test'].lms.bounds(), im.bounds())
コード例 #14
0
ファイル: textured.py プロジェクト: Amos-zq/menpo
    def __init__(self, points, tcoords, texture, trilist=None, copy=True):
        super(TexturedTriMesh, self).__init__(points, trilist=trilist,
                                              copy=copy)
        self.tcoords = PointCloud(tcoords, copy=copy)

        if not copy:
            self.texture = texture
        else:
            self.texture = texture.copy()
コード例 #15
0
ファイル: viewmayavi.py プロジェクト: HaoyangWang/menpo3d
def _parse_marker_size(marker_size, points):
    if marker_size is None:
        from menpo.shape import PointCloud
        pc = PointCloud(points, copy=False)
        # This is the way that mayavi automatically computes the scale factor in
        # case the user passes scale_factor = 'auto'. We use it for both the
        # marker_size as well as the numbers_size.
        xyz_min, xyz_max = pc.bounds()
        x_min, y_min, z_min = xyz_min
        x_max, y_max, z_max = xyz_max
        distance = np.sqrt(((x_max - x_min) ** 2 +
                            (y_max - y_min) ** 2 +
                            (z_max - z_min) ** 2) /
                           (4 * pc.n_points ** 0.33))
        if distance == 0:
            marker_size = 1
        else:
            marker_size = 0.1 * distance
    return marker_size
コード例 #16
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_from_depth_image_masked():
    fake_z = np.random.uniform(size=(10, 10))
    mask = np.zeros(fake_z.shape, dtype=np.bool)
    mask[2:6, 2:6] = True
    im = MaskedImage(fake_z, mask=mask)
    pc = PointCloud.init_from_depth_image(im)
    assert pc.n_points == 16
    assert pc.n_dims == 3
    assert_allclose(pc.range()[:2], [3, 3])
    assert pc.points[:, -1].max() <= 1.0
    assert pc.points[:, -1].min() >= 0.0
コード例 #17
0
ファイル: base.py プロジェクト: dubzzz/menpo
    def tojson(self):
        r"""
        Convert this `TriMesh` to a dictionary JSON representation.

        Returns
        -------
        dictionary with 'points' and 'trilist' keys. Both are lists suitable
        for use in the by the `json` standard library package.
        """
        json_dict = PointCloud.tojson(self)
        json_dict['trilist'] = self.trilist.tolist()
        return json_dict
コード例 #18
0
ファイル: io_import_test.py プロジェクト: grigorisg9gr/menpo
def test_register_landmark_importer(is_file):
    from menpo.shape import PointCloud
    lmark = PointCloud.init_2d_grid((1, 1))

    def foo_importer(filepath, **kwargs):
        return lmark

    is_file.return_value = True

    with patch.dict(mio.input.extensions.image_landmark_types, {}, clear=True):
        mio.register_landmark_importer('.foo', foo_importer)
        new_lmark = mio.import_landmark_file('fake.foo')
    assert lmark is new_lmark
コード例 #19
0
def test_align_2d_rotation():
    rotation_matrix = np.array([[0, 1],
                                [-1, 0]])
    rotation = Rotation(rotation_matrix)
    source = PointCloud(np.array([[0, 1],
                                  [1, 1],
                                  [-1, -5],
                                  [3, -5]]))
    target = rotation.apply(source)
    # estimate the transform from source and target
    estimate = AlignmentRotation(source, target)
    # check the estimates is correct
    assert_allclose(rotation.h_matrix,
                    estimate.h_matrix, atol=1e-14)
コード例 #20
0
def test_sample_maskedimage_error_values():
    m = np.zeros([100, 100], dtype=np.bool)
    m[1, 0] = True
    im = MaskedImage.init_blank((100, 100), mask=m, fill=2)
    p = PointCloud(np.array([[0, 0], [1, 0]]))
    try:
        im.sample(p)
        # Expect exception!
        assert 0
    except OutOfMaskSampleError as e:
        sampled_mask = e.sampled_mask
        sampled_values = e.sampled_values
        assert_allclose(sampled_values, [[2., 2.]])
        assert_allclose(sampled_mask, [[False, True]])
コード例 #21
0
def homog_compose_before_alignment_nonuniformscale_test():
    homog = Homogeneous(np.array([[0, 1, 0],
                                  [1, 0, 0],
                                  [0, 0, 1]]))
    scale = UniformScale(2.5, 2)
    source = PointCloud(np.array([[0, 1],
                                  [1, 1],
                                  [-1, -5],
                                  [3, -5]]))
    target = scale.apply(source)
    # estimate the transform from source and target
    s = AlignmentUniformScale(source, target)
    res = homog.compose_before(s)
    assert(type(res) == Homogeneous)
コード例 #22
0
ファイル: io_import_test.py プロジェクト: justusschock/menpo
def test_register_landmark_importer(is_file):
    from menpo.shape import PointCloud
    from menpo.landmark import LandmarkGroup
    lmark = LandmarkGroup.init_with_all_label(PointCloud.init_2d_grid((1, 1)))

    def foo_importer(filepath, **kwargs):
        return lmark

    is_file.return_value = True

    with patch.dict(mio.input.extensions.image_landmark_types, {}, clear=True):
        mio.register_landmark_importer('.foo', foo_importer)
        new_lmark = mio.import_landmark_file('fake.foo')
    assert lmark is new_lmark
コード例 #23
0
def test_register_landmark_importer(is_file):
    from menpo.shape import PointCloud

    lmark = PointCloud.init_2d_grid((1, 1))

    def foo_importer(filepath, **kwargs):
        return lmark

    is_file.return_value = True

    with patch.dict(mio.input.extensions.image_landmark_types, {}, clear=True):
        mio.register_landmark_importer(".foo", foo_importer)
        new_lmark = mio.import_landmark_file("fake.foo")
    assert lmark is new_lmark
コード例 #24
0
    def pseudoinverse(self):
        r"""
        The pseudoinverse of the transform - that is, the transform that
        results from swapping `source` and `target`, or more formally, negating
        the transforms parameters. If the transform has a true inverse this
        is returned instead.

        :type: ``type(self)``
        """
        from menpo.shape import PointCloud, TriMesh  # to avoid circular import

        new_source = TriMesh(self.target.points, self.source.trilist)
        new_target = PointCloud(self.source.points)
        return type(self)(new_source, new_target)
コード例 #25
0
ファイル: aam.py プロジェクト: xiaoyeye1117/pyVSR
def _pointcloud_subset(face_cloud, subset):
    r"""
    Selects a semantic subset of points from a face pointcloud
    Parameters
    ----------
    face_cloud
    subset

    Returns
    -------
    The `lips` or `chin` pointclouds, as a subset of `face_cloud`
    """

    if subset == 'lips':
        subset_pts = PointCloud(face_cloud.points[48:68])
    elif subset == 'chin':
        subset_pts = PointCloud(
            np.vstack((face_cloud.points[2:15], face_cloud.points[48:68])))
    else:
        raise Exception(
            'unsupported landmark subset, only lips/chin are implemented')

    return subset_pts
コード例 #26
0
def test_align_2d_translation_from_vector_inplace():
    t_vec = np.array([1, 2])
    translation = Translation(t_vec)
    source = PointCloud(np.array([[0, 1],
                                  [1, 1],
                                  [-1, -5],
                                  [3, -5]]))
    target = translation.apply(source)
    # estimate the transform from source to source..
    estimate = AlignmentTranslation(source, source)
    # and update from_vector
    estimate.from_vector_inplace(t_vec)
    # check the estimates is correct
    assert_allclose(target.points,
                    estimate.target.points)
コード例 #27
0
def test_align_2d_translation_set_target():
    t_vec = np.array([1, 2])
    translation = Translation(t_vec)
    source = PointCloud(np.array([[0, 1],
                                  [1, 1],
                                  [-1, -5],
                                  [3, -5]]))
    target = translation.apply(source)
    # estimate the transform from source to source..
    estimate = AlignmentTranslation(source, source)
    # and change the target.
    estimate.set_target(target)
    # check the estimates is correct
    assert_allclose(translation.h_matrix,
                    estimate.h_matrix)
コード例 #28
0
def clm_correct(clm_model_path, image, map, lms_init):
    """ tune landmarks using clm (constrained local model)"""

    filehandler = open(os.path.join(clm_model_path), "rb")
    try:
        part_model = pickle.load(filehandler)
    except UnicodeDecodeError:
        part_model = pickle.load(filehandler,
                                 fix_imports=True,
                                 encoding="latin1")
    filehandler.close()

    # from ECT: https://github.com/HongwenZhang/ECT-FaceAlignment
    part_model.opt = dict()
    part_model.opt['numIter'] = 5
    part_model.opt['kernel_covariance'] = 10
    part_model.opt['sigOffset'] = 25
    part_model.opt['sigRate'] = 0.25
    part_model.opt['pdm_rho'] = 20
    part_model.opt['verbose'] = False
    part_model.opt['rho2'] = 20
    part_model.opt['ablation'] = (True, True)
    part_model.opt['ratio1'] = 0.12
    part_model.opt['ratio2'] = 0.08
    part_model.opt['smooth'] = True

    fitter = GradientDescentCLMFitter(part_model, n_shape=30)

    image.rspmap_data = np.swapaxes(np.swapaxes(map, 1, 3), 2, 3)

    fr = fitter.fit_from_shape(image=image,
                               initial_shape=PointCloud(lms_init),
                               gt_shape=PointCloud(lms_init))
    w_pdm_clm = fr.final_shape.points

    return w_pdm_clm
コード例 #29
0
def mean_pointcloud(pointclouds):
    r"""
    Compute the mean of a `list` of :map:`PointCloud` or subclass objects.
    The list is assumed to be homogeneous i.e all elements of the list are
    assumed to belong to the same point cloud subclass just as all elements
    are also assumed to have the same number of points and represent
    semantically equivalent point clouds.

    Parameters
    ----------
    pointclouds: `list` of :map:`PointCloud` or subclass
        List of point cloud or subclass objects from which we want to compute
        the mean.

    Returns
    -------
    mean_pointcloud : :map:`PointCloud` or subclass
        The mean point cloud or subclass.
    """
    # make a temporary PointCloud (with copy=False for low overhead)
    tmp_pc = PointCloud(sum(pc.points for pc in pointclouds) /
                        len(pointclouds), copy=False)
    # use the type of the first element in the list to rebuild from the vector
    return pointclouds[0].from_vector(tmp_pc.as_vector())
コード例 #30
0
def perturb_init_shape(init_shape, num):
    ret = [init_shape]
    if num <= 1:
        return ret
    dx = np.random.uniform(low=-0.10, high=0.10, size=(num - 1))
    dy = np.random.uniform(low=-0.10, high=0.10, size=(num - 1))
    scale = np.random.normal(1, 0.07, size=(num - 1))
    normalized_offsets = np.dstack((dy, dx))[0]

    for i in range(num - 1):
        ret.append(
            PointCloud((init_shape.points - init_shape.centre()) * scale[i] +
                       init_shape.centre() +
                       init_shape.range() * normalized_offsets[i]))
    return ret
コード例 #31
0
def test_procrustes_no_target():
    # square
    src_1 = PointCloud(
        np.array([[1.0, 1.0], [1.0, -1.0], [-1.0, -1.0], [-1.0, 1.0]]))
    # rhombus
    src_2 = PointCloud(
        np.array([[2.0, 0.0], [4.0, 2.0], [6.0, 0.0], [4.0, -2.0]]))
    # trapezoid
    src_3 = PointCloud(
        np.array([[-0.5, -1.5], [2.5, -1.5], [2.8, -2.5], [-0.2, -2.5]]))
    gpa = GeneralizedProcrustesAnalysis([src_1, src_2, src_3])
    aligned_1 = gpa.transforms[0].apply(gpa.sources[0])
    aligned_2 = gpa.transforms[1].apply(gpa.sources[1])
    aligned_3 = gpa.transforms[2].apply(gpa.sources[2])
    assert (gpa.converged is True)
    assert (gpa.n_iterations == 5)
    assert (gpa.n_sources == 3)
    assert (np.round(gpa.initial_target_scale * 100) == 195.)
    assert (np.round(gpa.mean_alignment_error() * 10) == 4.)
    assert_allclose(np.around(aligned_1.points, decimals=1),
                    np.around(aligned_2.points, decimals=1))
    res_3 = np.array([[0.7, -0.3], [2.6, -0.4], [2.7, -1.0], [0.9, -0.9]])
    assert_allclose(np.around(aligned_3.points, decimals=1), res_3)
    assert_allclose(gpa.target.points, gpa.mean_aligned_shape().points)
コード例 #32
0
def test_pca_variance_after_trim():
    samples = [PointCloud(np.random.randn(10)) for _ in range(10)]
    model = PCAModel(samples)
    # set number of active components
    model.trim_components(5)
    # kept variance must be smaller than total variance
    assert (model.variance < model.original_variance)
    # kept variance ratio must be smaller than 1.0
    assert (model.variance_ratio < 1.0)
    # noise variance must be bigger than 0.0
    assert (model.noise_variance > 0.0)
    # noise variance ratio must also be bigger than 0.0
    assert (model.noise_variance_ratio > 0.0)
    # inverse noise variance is computable
    assert (model.inverse_noise_variance == 1 / model.noise_variance)
コード例 #33
0
def test_procrustes_with_target():
    # square
    src_1 = PointCloud(
        np.array([[1.0, 1.0], [1.0, -1.0], [-1.0, -1.0], [-1.0, 1.0]]))
    # trapezoid
    src_2 = PointCloud(
        np.array([[-0.5, -1.5], [2.5, -1.5], [2.8, -2.5], [-0.2, -2.5]]))
    # rhombus as target
    src_trg = PointCloud(
        np.array([[2.0, 0.0], [4.0, 2.0], [6.0, 0.0], [4.0, -2.0]]))
    gpa = GeneralizedProcrustesAnalysis([src_1, src_2], target=src_trg)
    aligned_1 = gpa.transforms[0].apply(gpa.sources[0])
    aligned_2 = gpa.transforms[1].apply(gpa.sources[1])
    assert (gpa.converged is True)
    assert (gpa.n_iterations == 2)
    assert (gpa.n_sources == 2)
    assert (gpa.initial_target_scale == 4.)
    assert (np.round(gpa.av_alignment_error * 100) == 93.)
    assert_allclose(np.around(aligned_1.points, decimals=1),
                    np.around(src_trg.points, decimals=1))
    res_2 = np.array([[2.0, -0.9], [4.9, 1.6], [6.0, 0.9], [3.1, -1.6]])
    assert_allclose(np.around(aligned_2.points, decimals=1), res_2)
    mean = np.array([[2.0, -0.5], [4.5, 1.8], [6.0, 0.5], [3.5, -1.8]])
    assert_allclose(np.around(gpa.mean_aligned_shape.points, decimals=1), mean)
コード例 #34
0
    def _align_source(self, source, eps=1e-3, max_iter=100):

        # Initial Alignment using PCA
        # p0, r, sm, tm = self._pca_align(source)
        # transforms.append([r, sm, tm])
        p0 = source.points

        a_p, transforms, iters, point_corr = self._align(p0, eps, max_iter)
        iters = [source.points, p0] + iters

        self._test_iteration.append(iters)
        self.transformations.append(transforms)
        self.point_correspondence.append(point_corr)

        return PointCloud(a_p)
コード例 #35
0
def test_single_ndarray_patch():
    patch_shape = (8, 7)
    n_channels = 4
    im = Image.init_blank((32, 32), n_channels)
    patch = np.zeros((2, 2, n_channels) + patch_shape)
    patch[0, 0, ...] = np.full((n_channels,) + patch_shape, 1)  # Should be unused
    patch[0, 1, ...] = np.full((n_channels,) + patch_shape, 2)
    patch[1, 0, ...] = np.full((n_channels,) + patch_shape, 3)  # Should be unused
    patch[1, 1, ...] = np.full((n_channels,) + patch_shape, 4)
    patch_center = PointCloud(np.array([[4.0, 4.0], [16.0, 16.0]]))
    new_im = im.set_patches(patch, patch_center, offset_index=1)
    res = np.zeros((32, 32))
    res[:8, 1:8] = 2
    res[12:20, 13:20] = 4
    assert_array_equal(new_im.pixels[2], res)
コード例 #36
0
def test_align_2d_similarity_set_target():
    linear_component = np.array([[2, -6], [6, 2]])
    translation_component = np.array([7, -8])
    h_matrix = np.eye(3, 3)
    h_matrix[:-1, :-1] = linear_component
    h_matrix[:-1, -1] = translation_component
    similarity = Similarity(h_matrix)
    source = PointCloud(np.array([[0, 1], [1, 1], [-1, -5], [3, -5]]))
    target = similarity.apply(source)
    # estimate the transform from source to source
    estimate = AlignmentSimilarity(source, source, allow_mirror=True)
    # and set the target
    estimate.set_target(target)
    # check the estimates is correct
    assert_allclose(similarity.h_matrix, estimate.h_matrix)
コード例 #37
0
def test_landmarkgroup_copy_method():
    points = np.ones((10, 3))
    mask_dict = OrderedDict([('all', np.ones(10, dtype=np.bool))])
    pcloud = PointCloud(points, copy=False)

    lgroup = LandmarkGroup(pcloud, mask_dict, copy=False)
    lgroup_copy = lgroup.copy()

    assert (not is_same_array(lgroup_copy.lms.points, lgroup.lms.points))
    # Check the mask dictionary is deepcopied properly
    assert (lgroup._labels_to_masks is not lgroup_copy._labels_to_masks)
    masks = zip(lgroup_copy._labels_to_masks.values(),
                lgroup._labels_to_masks.values())
    for ms in masks:
        assert (ms[0] is not ms[1])
コード例 #38
0
def test_align_2d_affine_set_target():
    linear_component = np.array([[1, -6], [-3, 2]])
    translation_component = np.array([7, -8])
    h_matrix = np.eye(3, 3)
    h_matrix[:-1, :-1] = linear_component
    h_matrix[:-1, -1] = translation_component
    affine = Affine(h_matrix)
    source = PointCloud(np.array([[0, 1], [1, 1], [-1, -5], [3, -5]]))
    target = affine.apply(source)
    # estimate the transform from source and source
    estimate = AlignmentAffine(source, source)
    # and set the target
    estimate.set_target(target)
    # check the estimates is correct
    assert_allclose(affine.h_matrix, estimate.h_matrix)
コード例 #39
0
def test_align_2d_translation_from_vector():
    t_vec = np.array([1, 2])
    translation = Translation(t_vec)
    source = PointCloud(np.array([[0, 1], [1, 1], [-1, -5], [3, -5]]))
    target = translation.apply(source)
    # estimate the transform from source to source..
    estimate = AlignmentTranslation(source, source)
    # and update from_vector
    new_est = estimate.from_vector(t_vec)
    # check the original is unchanged
    assert_allclose(estimate.source.points, source.points)
    assert_allclose(estimate.target.points, source.points)
    # check the new estimate has the source and target correct
    assert_allclose(new_est.source.points, source.points)
    assert_allclose(new_est.target.points, target.points)
コード例 #40
0
    def __init__(self, sources, target=None):
        from menpo.shape import PointCloud

        if len(sources) < 2 and target is None:
            raise ValueError("Need at least two sources to align")
        self.n_sources = len(sources)
        self.n_points, self.n_dims = sources[0].n_points, sources[0].n_dims
        self.sources = sources
        if target is None:
            # set the target to the mean source position
            self.target = PointCloud(
                sum([s.points for s in self.sources]) / self.n_sources)
        else:
            assert self.n_dims, self.n_points == target.shape
            self.target = target
コード例 #41
0
def mean_pointcloud(pointclouds):
    r"""
    Compute the mean of a list of point cloud objects

    Parameters
    ----------
    pointclouds: list of :class:`menpo.shape.PointCloud`
        List of point cloud objects from which we want to
        compute the mean.

    Returns
    -------
    mean_pointcloud: class:`menpo.shape.PointCloud`
        The mean point cloud.
    """
    return PointCloud(np.mean([pc.points for pc in pointclouds], axis=0))
コード例 #42
0
def FastNICP(sources, target):
    aligned = []
    corrs = []
    for source in sources:
        pts, _ = icp(source.points, target.points)
        mesh = TriMesh(pts)
        try:
            a_s, corr = nicp(mesh, target, us=2001, ls=1, step=100)
        except:
            print('Failed Fast NICP')
            nicp_result = SNICP([PointCloud(pts)], target)
            corr = nicp_result.point_correspondence[0]
            a_s = nicp_result.aligned_shapes[0]
        aligned.append(a_s)
        corrs.append(corr)
    return aligned, corrs
コード例 #43
0
ファイル: test_image_warp.py プロジェクト: eosulliv/menpo
def test_mirror_vertical_image():
    image = Image(
        np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0],
                  [9.0, 10.0, 11.0, 12.0]]))
    image.landmarks["temp"] = PointCloud(
        np.array([[1.0, 0.0], [1.0, 1.0], [2.0, 1.0], [2.0, 2.0]]))
    mirrored_img = image.mirror()
    assert_allclose(
        mirrored_img.pixels,
        np.array([[[4.0, 3.0, 2.0, 1.0], [8.0, 7.0, 6.0, 5.0],
                   [12.0, 11.0, 10.0, 9.0]]]),
    )
    assert_allclose(
        mirrored_img.landmarks["temp"].points,
        np.array([[1.0, 3.0], [1.0, 2.0], [2.0, 2.0], [2.0, 1.0]]),
    )
コード例 #44
0
def fit_shape_to_box(normal_shape, box):
    x, y = box.points[0]
    w, h = box.range()

    # center_x = x + w*2.0/3.0
    # center_y = y + h/2.0

    center_x = x + w/2.0
    center_y = y + h/2.0

    shape = normal_shape.points - normal_shape.centre()
    shape *= [0.9*h/2.0, 0.9*w/2.0]
#     shape *= [h/2.0, w/2.0]
    shape += [center_x, center_y]

    return PointCloud(shape)
コード例 #45
0
def test_rotate_image_45():
    image = Image(
        np.array([[1., 2., 3., 4.], [5., 6., 7., 8.], [9., 10., 11., 12.],
                  [13., 14., 15., 16.]]))
    image.landmarks['temp'] = PointCloud(
        np.array([[1., 1.], [1., 2.], [2., 1.], [2., 2.]]))
    rotated_img = image.rotate_ccw_about_centre(theta=45, order=0)
    assert_allclose(
        rotated_img.pixels,
        np.array([[[0., 0., 4., 0., 0.], [0., 3., 7., 8., 0.],
                   [1., 6., 7., 11., 16.], [0., 5., 10., 15., 15.],
                   [0., 0., 13., 14., 0.]]]))
    assert_almost_equal(rotated_img.landmarks['temp'].lms.points,
                        np.array([[2.121, 1.414], [1.414, 2.121],
                                  [2.828, 2.121], [2.121, 2.828]]),
                        decimal=3)
コード例 #46
0
def test_single_list_patch():
    patch_shape = (8, 7)
    n_channels = 4
    im = Image.init_blank((32, 32), n_channels)
    patch = [
        Image(np.full((n_channels,) + patch_shape, 1)),
        Image(np.full((n_channels,) + patch_shape, 2)),  # Should be unused
        Image(np.full((n_channels,) + patch_shape, 3)),
        Image(np.full((n_channels,) + patch_shape, 4)),
    ]  # Should be unused
    patch_center = PointCloud(np.array([[4.0, 4.0], [16.0, 16.0]]))
    new_im = im.set_patches(patch, patch_center, offset_index=0)
    res = np.zeros((32, 32))
    res[:8, 1:8] = 1
    res[12:20, 13:20] = 3
    assert_array_equal(new_im.pixels[0], res)
コード例 #47
0
def test_colouredtrimesh_copy():
    points = np.ones([10, 3])
    colours = np.ones([10, 3])
    trilist = np.ones([10, 3])
    landmarks = PointCloud(np.ones([3, 3]), copy=False)

    ctmesh = ColouredTriMesh(points, trilist=trilist, colours=colours,
                             copy=False)
    ctmesh.landmarks['test'] = landmarks
    ctmesh_copy = ctmesh.copy()

    assert (not is_same_array(ctmesh_copy.points, ctmesh.points))
    assert (not is_same_array(ctmesh_copy.trilist, ctmesh.trilist))
    assert (not is_same_array(ctmesh_copy.colours, ctmesh.colours))
    assert (not is_same_array(ctmesh_copy.landmarks['test'].lms.points,
                              ctmesh.landmarks['test'].lms.points))
コード例 #48
0
    def as_menpo_img(self):
        """
        Converts image to menpo image

        Returns
        -------
        menpo.image.Image: current image as menpo image
        """
        menpo_img = Image(self.img)
        lmk = self.lmk
        menpo_lmk = PointCloud(self.lmk)
        lmk_manager = LandmarkManager()
        lmk_manager["LMK"] = menpo_lmk
        menpo_img.landmarks = lmk_manager

        return menpo_img
コード例 #49
0
def test_align_2d_affine_compose_target():
    source = PointCloud(np.array([[0, 1],
                                  [1, 1],
                                  [-1, -5],
                                  [3, -5]]))
    target = UniformScale(2.0, n_dims=2).apply(source)
    original_estimate = AlignmentAffine(source, target)
    new_estimate = original_estimate.copy()
    new_estimate.compose_after_from_vector_inplace(
        np.array([0, 0, 0, 0, 1, 1.]))
    estimate_target = new_estimate.target

    correct_target = original_estimate.compose_after(
        Translation([1, 1.])).apply(source)

    assert_allclose(estimate_target.points, correct_target.points)
コード例 #50
0
def test_init_from_pointcloud_return_transform():
    correct_tr = Translation([5, 5])
    pc = correct_tr.apply(PointCloud.init_2d_grid((10, 10)))
    im, tr = Image.init_from_pointcloud(pc, return_transform=True)
    assert im.shape == (9, 9)
    assert_allclose(tr.as_vector(), -correct_tr.as_vector())
コード例 #51
0
ファイル: modeldriven.py プロジェクト: HaoyangWang/menpofit
 def sparse_target(self):
     sparse_target = PointCloud(self.target.points[:self.n_landmarks])
     return self._sparse_instance.from_vector(sparse_target.as_vector())
コード例 #52
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_no_nan_values():
    pcloud = PointCloud(np.random.rand(3, 2), copy=False)
    assert not pcloud.has_nan_values()
コード例 #53
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_has_nan_values():
    pcloud = PointCloud(np.random.rand(3, 2), copy=False)
    pcloud.points[0, 0] = np.nan
    assert pcloud.has_nan_values()
コード例 #54
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_2d_grid_incorrect_type_spacing_raises():
    PointCloud.init_2d_grid([10, 10], spacing={})
コード例 #55
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_2d_grid_3d_spacing_raises():
    PointCloud.init_2d_grid([10, 10], spacing=[1, 1, 1])
コード例 #56
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_2d_grid_3d_raises():
    PointCloud.init_2d_grid([10, 10, 10])
コード例 #57
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_2d_grid_unequal_spacing():
    pc = PointCloud.init_2d_grid([10, 10], spacing=(2., 3))
    assert pc.n_points == 100
    assert pc.n_dims == 2
    assert_allclose(pc.range(), [18, 27])
コード例 #58
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_2d_grid_single_spacing():
    pc = PointCloud.init_2d_grid([10, 10], spacing=2)
    assert pc.n_points == 100
    assert pc.n_dims == 2
    assert_allclose(pc.range(), [18, 18])
コード例 #59
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_bounding_box_3d_fail():
    points = np.array([[0, 0, 0],
                       [1, 1, 1]])
    pc = PointCloud(points)
    pc.bounding_box()
コード例 #60
0
ファイル: pointcloud_test.py プロジェクト: JeanKossaifi/menpo
def test_pointcloud_init_2d_grid():
    pc = PointCloud.init_2d_grid([10, 10])
    assert pc.n_points == 100
    assert pc.n_dims == 2
    assert_allclose(pc.range(), [9, 9])