本文整理汇总了Python中menpo.transform.Translation类的典型用法代码示例。如果您正苦于以下问题:Python Translation类的具体用法?Python Translation怎么用?Python Translation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Translation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _recursive_procrustes
def _recursive_procrustes(self):
r"""
Recursively calculates a procrustes alignment.
"""
from menpo.shape import mean_pointcloud
from menpo.transform import Similarity
if self.n_iterations > self.max_iterations:
return False
new_tgt = mean_pointcloud([t.aligned_source.points
for t in self.transforms])
# rescale the new_target to be the same size as the original about
# it's centre
rescale = Similarity.identity(new_tgt.n_dims)
s = UniformScale(self.initial_target_scale / new_tgt.norm(),
self.n_dims, skip_checks=True)
t = Translation(-new_tgt.centre, skip_checks=True)
rescale.compose_before_inplace(t)
rescale.compose_before_inplace(s)
rescale.compose_before_inplace(t.pseudoinverse)
rescale.apply_inplace(new_tgt)
# check to see if we have converged yet
delta_target = np.linalg.norm(self.target.points - new_tgt.points)
if delta_target < 1e-6:
return True
else:
self.n_iterations += 1
for t in self.transforms:
t.set_target(new_tgt)
self.target = new_tgt
return self._recursive_procrustes()
示例2: optimal_cylindrical_unwrap
def optimal_cylindrical_unwrap(points):
r"""
Returns a :map:`TransformChain` of
[:map:`Translation`, :map:`CylindricalUnwrap`]
which optimally cylindrically unwraps the points provided. This is done by:
#. Find an optimal :map:`Translation` to centre the points in ``x-z`` plane
#. Use :map:`circle_fit` to find the optimal radius for fitting the points
#. Calculate a :map:`CylindricalUnwrap` using the optimal radius
#. Return a composition of the two.
Parameters
----------
points : :map:`PointCloud`
The 3D points that will be used to find the optimum unwrapping position
Returns
-------
transform: :map:`TransformChain`
A :map:`TransformChain` which performs the optimal translation and
unwrapping.
"""
# find the optimum centre to unwrap
xy = points.points[:, [0, 2]] # just in the x-z plane
centre, radius = radial_fit(xy)
# convert the 2D circle data into the 3D space
translation = np.array([centre[0], 0, centre[1]])
centring_transform = Translation(-translation)
unwrap = CylindricalUnwrap(radius)
return centring_transform.compose_before(unwrap)
示例3: noisy_alignment_similarity_transform
def noisy_alignment_similarity_transform(source, target, noise_type='uniform',
noise_percentage=0.1,
allow_alignment_rotation=False):
r"""
Constructs and perturbs the optimal similarity transform between the source
and target shapes by adding noise to its parameters.
Parameters
----------
source : `menpo.shape.PointCloud`
The source pointcloud instance used in the alignment
target : `menpo.shape.PointCloud`
The target pointcloud instance used in the alignment
noise_type : ``{'uniform', 'gaussian'}``, optional
The type of noise to be added.
noise_percentage : `float` in ``(0, 1)`` or `list` of `len` `3`, optional
The standard percentage of noise to be added. If `float`, then the same
amount of noise is applied to the scale, rotation and translation
parameters of the optimal similarity transform. If `list` of
`float` it must have length 3, where the first, second and third elements
denote the amount of noise to be applied to the scale, rotation and
translation parameters, respectively.
allow_alignment_rotation : `bool`, optional
If ``False``, then the rotation is not considered when computing the
optimal similarity transform between source and target.
Returns
-------
noisy_alignment_similarity_transform : `menpo.transform.Similarity`
The noisy Similarity Transform between source and target.
"""
if isinstance(noise_percentage, float):
noise_percentage = [noise_percentage] * 3
elif len(noise_percentage) == 1:
noise_percentage *= 3
similarity = AlignmentSimilarity(source, target,
rotation=allow_alignment_rotation)
if noise_type is 'gaussian':
s = noise_percentage[0] * (0.5 / 3) * np.asscalar(np.random.randn(1))
r = noise_percentage[1] * (180 / 3) * np.asscalar(np.random.randn(1))
t = noise_percentage[2] * (target.range() / 3) * np.random.randn(2)
s = scale_about_centre(target, 1 + s)
r = rotate_ccw_about_centre(target, r)
t = Translation(t, source.n_dims)
elif noise_type is 'uniform':
s = noise_percentage[0] * 0.5 * (2 * np.asscalar(np.random.randn(1)) - 1)
r = noise_percentage[1] * 180 * (2 * np.asscalar(np.random.rand(1)) - 1)
t = noise_percentage[2] * target.range() * (2 * np.random.rand(2) - 1)
s = scale_about_centre(target, 1. + s)
r = rotate_ccw_about_centre(target, r)
t = Translation(t, source.n_dims)
else:
raise ValueError('Unexpected noise type. '
'Supported values are {gaussian, uniform}')
return similarity.compose_after(t.compose_after(s.compose_after(r)))
示例4: _recursive_procrustes
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()
示例5: lm_centres_correction
def lm_centres_correction(centres):
r"""
Construct a transform that will correct landmarks for a window
iterating feature calculation
Parameters
----------
centres : `ndarray` (H, W, 2)
The location of the window centres in the features
Returns
-------
:map:`Affine`
An affine transform that performs the correction.
Should be applied to the landmarks on the target image.
"""
t = Translation(-centres.min(axis=0).min(axis=0), skip_checks=True)
step_v = centres[0, 0, 0]
if centres.shape[0] > 1:
step_v = centres[1, 0, 0] - centres[0, 0, 0]
step_h = centres[0, 0, 1]
if centres.shape[1] > 1:
step_h = centres[0, 1, 1] - centres[0, 0, 1]
s = NonUniformScale((1./step_v, 1./step_h), skip_checks=True)
return t.compose_before(s)
示例6: test_translation_compose_after_homog
def test_translation_compose_after_homog():
# can't do this inplace - so should just give transform chain
homog = Homogeneous(np.array([[0, 1, 0],
[1, 0, 0],
[0, 0, 1]]))
t = Translation([3, 4])
res = t.compose_after(homog)
assert(type(res) == Homogeneous)
示例7: test_align_2d_translation
def test_align_2d_translation():
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 and target
estimate = AlignmentTranslation(source, target)
# check the estimates is correct
assert_allclose(translation.h_matrix, estimate.h_matrix)
示例8: test_align_2d_translation_set_h_matrix_raises_notimplemented_error
def test_align_2d_translation_set_h_matrix_raises_notimplemented_error():
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_h_matrix(translation.h_matrix)
示例9: crop
def crop(self, min_indices, max_indices, constrain_to_boundary=True):
r"""
Crops this image using the given minimum and maximum indices.
Landmarks are correctly adjusted so they maintain their position
relative to the newly cropped image.
Parameters
-----------
min_indices: (n_dims, ) ndarray
The minimum index over each dimension
max_indices: (n_dims, ) ndarray
The maximum index over each dimension
constrain_to_boundary: boolean, optional
If True the crop will be snapped to not go beyond this images
boundary. If False, an ImageBoundaryError will be raised if an
attempt is made to go beyond the edge of the image.
Default: True
Returns
-------
cropped_image : :class:`type(self)`
This image, but cropped.
Raises
------
ValueError
min_indices and max_indices both have to be of length n_dims.
All max_indices must be greater than min_indices.
ImageBoundaryError
Raised if constrain_to_boundary is False, and an attempt is made
to crop the image in a way that violates the image bounds.
"""
min_indices = np.floor(min_indices)
max_indices = np.ceil(max_indices)
if not (min_indices.size == max_indices.size == self.n_dims):
raise ValueError(
"Both min and max indices should be 1D numpy arrays of" " length n_dims ({})".format(self.n_dims)
)
elif not np.all(max_indices > min_indices):
raise ValueError("All max indices must be greater that the min " "indices")
min_bounded = self.constrain_points_to_bounds(min_indices)
max_bounded = self.constrain_points_to_bounds(max_indices)
if not constrain_to_boundary and not (np.all(min_bounded == min_indices) or np.all(max_bounded == max_indices)):
# points have been constrained and the user didn't want this -
raise ImageBoundaryError(min_indices, max_indices, min_bounded, max_bounded)
slices = [slice(int(min_i), int(max_i)) for min_i, max_i in zip(list(min_bounded), list(max_bounded))]
self.pixels = self.pixels[slices].copy()
# update all our landmarks
lm_translation = Translation(-min_bounded)
lm_translation.apply_inplace(self.landmarks)
return self
示例10: _build_reference_frame
def _build_reference_frame(landmarks, boundary=3, group='source'):
# translate landmarks to the origin
minimum = landmarks.bounds(boundary=boundary)[0]
landmarks = Translation(-minimum).apply(landmarks)
resolution = landmarks.range(boundary=boundary)
reference_frame = MaskedImage.blank(resolution)
reference_frame.landmarks[group] = landmarks
return reference_frame
示例11: test_align_2d_translation_from_vector_inplace
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)
示例12: chain_compose_after_inplace_chain_test
def chain_compose_after_inplace_chain_test():
a = PointCloud(np.random.random([10, 2]))
b = PointCloud(np.random.random([10, 2]))
t = Translation([3, 4])
s = Scale([4, 2])
chain_1 = TransformChain([t, s])
chain_2 = TransformChain([s.pseudoinverse(), t.pseudoinverse()])
chain_1.compose_before_inplace(chain_2)
points = PointCloud(np.random.random([10, 2]))
chain_res = chain_1.apply(points)
assert(np.allclose(points.points, chain_res.points))
示例13: init_from_pointcloud
def init_from_pointcloud(cls, pointcloud, group=None, boundary=0,
constrain=True, fill=True):
r"""
Create an Image that is big enough to contain the given pointcloud.
The pointcloud will be translated to the origin and then translated
according to its bounds in order to fit inside the new image.
An optional boundary can be provided in order to increase the space
around the boundary of the pointcloud. The boundary will be added
to *all sides of the image* and so a boundary of 5 provides 10 pixels
of boundary total for each dimension.
By default, the mask will be constrained to the convex hull of the
provided pointcloud.
Parameters
----------
pointcloud : :map:`PointCloud`
Pointcloud to place inside the newly created image.
group : `str`, optional
If ``None``, the pointcloud will only be used to create the image.
If a `str` then the pointcloud will be attached as a landmark
group to the image, with the given string as key.
boundary : `float`
A optional padding distance that is added to the pointcloud bounds.
Default is ``0``, meaning the max/min of tightest possible
containing image is returned.
fill : `int`, optional
The value to fill all pixels with.
constrain : `bool`, optional
If ``True``, the ``True`` values will be image will be constrained
to the convex hull of the provided pointcloud. If ``False``,
the mask will be the value of ``fill``.
Returns
-------
image : :map:`MaskedImage`
A new image with the same size as the given pointcloud, optionally
with the pointcloud attached as landmarks and the mask constrained
to the convex hull of the pointcloud.
"""
# Translate pointcloud to the origin
minimum = pointcloud.bounds(boundary=boundary)[0]
origin_pc = Translation(-minimum).apply(pointcloud)
image_shape = origin_pc.range(boundary=boundary)
new_image = cls.init_blank(image_shape, fill=fill)
if constrain:
new_image = new_image.constrain_to_pointcloud(origin_pc)
if group is not None:
new_image.landmarks[group] = origin_pc
return new_image
示例14: chain_compose_before_tps_test
def chain_compose_before_tps_test():
a = PointCloud(np.random.random([10, 2]))
b = PointCloud(np.random.random([10, 2]))
tps = ThinPlateSplines(a, b)
t = Translation([3, 4])
s = Scale([4, 2])
chain = TransformChain([t, s])
chain_mod = chain.compose_before(tps)
points = PointCloud(np.random.random([10, 2]))
manual_res = tps.apply(s.apply(t.apply(points)))
chain_res = chain_mod.apply(points)
assert(np.all(manual_res.points == chain_res.points))
示例15: test_align_2d_translation_from_vector
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)