本文整理汇总了Python中sunpy.image.transform.affine_transform函数的典型用法代码示例。如果您正苦于以下问题:Python affine_transform函数的具体用法?Python affine_transform怎么用?Python affine_transform使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了affine_transform函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_all
def test_all(angle, dx, dy, scale_factor):
"""
Tests to make sure that combinations of scaling, shifting and rotation
produce the expected output.
"""
k = int(angle / 90)
angle = np.radians(angle)
image_center = np.array(original.shape) / 2.0 - 0.5
# Check a shifted, rotated and scaled shape against expected outcome
c = np.cos(angle)
s = np.sin(angle)
rmatrix = np.array([[c, -s], [s, c]])
scale = tf.rescale(original / original.max(), scale_factor, order=4,
mode='constant', multichannel=False, anti_aliasing=False) * original.max()
new = np.zeros(original.shape)
# Old width and new center of image
w = np.array(original.shape[0])/2.0 - 0.5
new_c = (np.array(scale.shape[0])/2.0 - 0.5)
upper = int(w+new_c+1)
if scale_factor > 1:
lower = int(new_c-w)
new = scale[lower:upper, lower:upper]
else:
lower = int(w-new_c)
new[lower:upper, lower:upper] = scale
disp = np.array([dx, dy])
rcen = image_center + disp
rot = np.rot90(new, k=k)
shift = np.roll(np.roll(rot, dx, axis=1), dy, axis=0)
expected = shift
rotscaleshift = affine_transform(original, rmatrix=rmatrix, scale=scale_factor,
recenter=True, image_center=rcen)
w = np.array(expected.shape[0])/2.0 - 0.5
new_c = (np.array(rotscaleshift.shape[0])/2.0 - 0.5)
upper = int(w+new_c+1)
if scale_factor > 1:
lower = int(new_c-w)
expected = rotscaleshift[lower:upper, lower:upper]
else:
lower = int(w-new_c)
expected[lower:upper, lower:upper] = rotscaleshift
compare_results(expected, rotscaleshift)
# Check a rotated/shifted and restored image against original
transformed = affine_transform(original, rmatrix=rmatrix, scale=1.0, recenter=True,
image_center=rcen)
rcen = image_center - np.dot(rmatrix, np.array([dx, dy]))
dx, dy = np.asarray(np.dot(rmatrix, disp), dtype=int)
rmatrix = np.array([[c, s], [-s, c]])
inverse = affine_transform(transformed, rmatrix=rmatrix, scale=1.0, recenter=True,
image_center=rcen)
# Need to ignore the portion of the image cut off by the first shift
# (which isn't the portion you'd expect, because of the rotation)
ymin, ymax = max([0, -dy]), min([original.shape[1], original.shape[1]-dy])
xmin, xmax = max([0, -dx]), min([original.shape[0], original.shape[0]-dx])
compare_results(original[ymin:ymax, xmin:xmax], inverse[ymin:ymax, xmin:xmax])
示例2: test_scipy_rotation
def test_scipy_rotation(angle, k):
# Test rotation against expected outcome
angle = np.radians(angle)
c = np.cos(angle); s = np.sin(angle)
rmatrix = np.array([[c, -s], [s, c]])
expected = np.rot90(original, k=k)
rot = affine_transform(original, rmatrix=rmatrix, use_scipy=True)
assert compare_results(expected, rot, allclose=False)
# TODO: Check incremental 360 degree rotation against original image
# Check derotated image against original
derot_matrix = np.array([[c, s], [-s, c]])
derot = affine_transform(rot, rmatrix=derot_matrix, use_scipy=True)
assert compare_results(original, derot, allclose=False)
示例3: test_rotation
def test_rotation(angle, k):
# Test rotation against expected outcome
angle = np.radians(angle)
c = np.cos(angle); s = np.sin(angle)
rmatrix = np.array([[c, -s], [s, c]])
expected = np.rot90(original, k=k)
#Run the tests at order 4 as it produces more accurate 90 deg rotations
rot = affine_transform(original, order=4, rmatrix=rmatrix)
assert compare_results(expected, rot)
# TODO: Check incremental 360 degree rotation against original image
# Check derotated image against original
derot_matrix = np.array([[c, s], [-s, c]])
derot = affine_transform(rot, order=4, rmatrix=derot_matrix)
assert compare_results(original, derot)
示例4: test_shift
def test_shift(dx, dy):
# Rotation center for all translation tests.
image_center = np.array(original.shape)/2.0 - 0.5
# No rotation for all translation tests.
rmatrix = np.array([[1.0, 0.0], [0.0, 1.0]])
# Check a shifted shape against expected outcome
expected = np.roll(np.roll(original, dx, axis=1), dy, axis=0)
rcen = image_center + np.array([dx, dy])
shift = affine_transform(original, rmatrix=rmatrix, recenter=True, image_center=rcen)
ymin, ymax = max([0, dy]), min([original.shape[1], original.shape[1]+dy])
xmin, xmax = max([0, dx]), min([original.shape[0], original.shape[0]+dx])
compare_results(expected[ymin:ymax, xmin:xmax], shift[ymin:ymax, xmin:xmax])
# Check shifted and unshifted shape against original image
rcen = image_center - np.array([dx, dy])
unshift = affine_transform(shift, rmatrix=rmatrix, recenter=True, image_center=rcen)
# Need to ignore the portion of the image cut off by the first shift
ymin, ymax = max([0, -dy]), min([original.shape[1], original.shape[1]-dy])
xmin, xmax = max([0, -dx]), min([original.shape[0], original.shape[0]-dx])
compare_results(original[ymin:ymax, xmin:xmax], unshift[ymin:ymax, xmin:xmax])
示例5: test_scale
def test_scale(scale_factor):
# No rotation for all scaling tests.
rmatrix = np.array([[1.0, 0.0], [0.0, 1.0]])
# Check a scaled image against the expected outcome
newim = tf.rescale(original/original.max(), scale_factor, order=4,
mode='constant') * original.max()
# Old width and new center of image
w = original.shape[0]/2.0 - 0.5
new_c = (newim.shape[0]/2.0) - 0.5
expected = np.zeros(original.shape)
upper = w+new_c+1
if scale_factor > 1:
lower = new_c-w
expected = newim[lower:upper, lower:upper]
else:
lower = w-new_c
expected[lower:upper, lower:upper] = newim
scale = affine_transform(original, rmatrix=rmatrix, scale=scale_factor)
compare_results(expected, scale)
示例6: rotate
def rotate(self, angle=None, rmatrix=None, order=4, scale=1.0,
rotation_center=(0,0), recenter=False, missing=0.0, use_scipy=False):
"""
Returns a new rotated and rescaled map. Specify either a rotation
angle or a rotation matrix, but not both. If neither an angle or a
rotation matrix are specified, the map will be rotated by the rotation
angle in the metadata.
Also updates the rotation_matrix attribute and any appropriate header
data so that they correctly describe the new map.
Parameters
----------
angle : float
The angle (degrees) to rotate counterclockwise.
rmatrix : 2x2
Linear transformation rotation matrix.
order : int 0-5
Interpolation order to be used. When using scikit-image this parameter
is passed into :func:`skimage.transform.warp` (e.g., 4 corresponds to
bi-quartic interpolation).
When using scipy it is passed into
:func:`scipy.ndimage.interpolation.affine_transform` where it controls
the order of the spline.
Faster performance may be obtained at the cost of accuracy by using lower values.
Default: 4
scale : float
A scale factor for the image, default is no scaling
rotation_center : tuple
The axis of rotation in data coordinates
Default: the origin in the data coordinate system
recenter : bool
If True, position the axis of rotation at the center of the new map
Default: False
missing : float
The numerical value to fill any missing points after rotation.
Default: 0.0
use_scipy : bool
If True, forces the rotation to use
:func:`scipy.ndimage.interpolation.affine_transform`, otherwise it
uses the :func:`skimage.transform.warp`.
Default: False, unless scikit-image can't be imported
Returns
-------
out : Map
A new Map instance containing the rotated and rescaled data of the
original map.
See Also
--------
sunpy.image.transform.affine_transform : The routine this method calls for the rotation.
Notes
-----
This function will remove old CROTA keywords from the header.
This function will also convert a CDi_j matrix to a PCi_j matrix.
See :func:`sunpy.image.transform.affine_transform` for details on the
transformations, situations when the underlying data is modified prior to rotation,
and differences from IDL's rot().
"""
if angle is not None and rmatrix is not None:
raise ValueError("You cannot specify both an angle and a matrix")
elif angle is None and rmatrix is None:
rmatrix = self.rotation_matrix
# Interpolation parameter sanity
if order not in range(6):
raise ValueError("Order must be between 0 and 5")
# Copy Map
new_map = deepcopy(self)
if angle is not None:
# Calulate the parameters for the affine_transform
c = np.cos(np.deg2rad(angle))
s = np.sin(np.deg2rad(angle))
rmatrix = np.matrix([[c, -s], [s, c]])
# Calculate the shape in pixels to contain all of the image data
extent = np.max(np.abs(np.vstack((new_map.shape * rmatrix, new_map.shape * rmatrix.T))), axis=0)
# Calculate the needed padding or unpadding
diff = np.asarray(np.ceil((extent - new_map.shape) / 2)).ravel()
# Pad the image array
pad_x = np.max((diff[1], 0))
pad_y = np.max((diff[0], 0))
new_map.data = np.pad(new_map.data,
((pad_y, pad_y), (pad_x, pad_x)),
mode='constant',
constant_values=(missing, missing))
new_map.meta['crpix1'] += pad_x
new_map.meta['crpix2'] += pad_y
# map_center is swapped compared to the x-y convention
array_center = (np.array(new_map.data.shape)-1)/2.0
# pixel_center is swapped compared to the x-y convention
if recenter:
# Convert the axis of rotation from data coordinates to pixel coordinates
#.........这里部分代码省略.........
示例7: test_int
def test_int(identity):
# Test casting of integer array to float array
in_arr = np.array([[100]], dtype=int)
out_arr = affine_transform(in_arr, rmatrix=identity)
assert np.issubdtype(out_arr.dtype, np.float)
示例8: test_nan_scipy
def test_nan_scipy(identity):
# Test replacement of NaN values for scipy rotation
in_arr = np.array([[np.nan]])
out_arr = affine_transform(in_arr, rmatrix=identity, use_scipy=True)
assert not np.all(np.isnan(out_arr))
示例9: test_nan_skimage_high
def test_nan_skimage_high(identity):
# Test replacement of NaN values for scikit-image rotation with order >=4
in_arr = np.array([[np.nan]])
out_arr = affine_transform(in_arr, rmatrix=identity, order=4)
assert not np.all(np.isnan(out_arr))
示例10: test_flat
def test_flat(identity):
# Test that a flat array can be rotated using scikit-image
in_arr = np.array([[100]])
out_arr = affine_transform(in_arr, rmatrix=identity)
assert np.allclose(in_arr, out_arr, rtol=rtol)
示例11: rotate
def rotate(self, angle=None, rmatrix=None, order=3, scale=1.0,
image_center=(0,0), recenter=False, missing=0.0, use_scipy=False):
"""
Returns a new rotated and rescaled map. Specify either a rotation
angle or a rotation matrix, but not both. If neither an angle or a
rotation matrix are specified, the map will be rotated by the rotation
angle in the metadata.
Also updates the rotation_matrix attribute and any appropriate header
data so that they correctly describe the new map.
Parameters
----------
angle : float
The angle (degrees) to rotate counterclockwise.
rmatrix : 2x2
Linear transformation rotation matrix.
order : int 0-5
Interpolation order to be used. When using scikit-image this parameter
is passed into :func:`skimage.transform.warp`.
When using scipy it is passed into
:func:`scipy.ndimage.interpolation.affine_transform` where it controls
the order of the spline.
Higher accuracy may be obtained at the cost of performance by using
higher values.
scale : float
A scale factor for the image, default is no scaling
image_center : tuple
The axis of rotation in data coordinates
Default: the origin in the data coordinate system
recenter : bool
If True, position the axis of rotation at the center of the new map
Default: False
missing : float
The numerical value to fill any missing points after rotation.
Default: 0.0
use_scipy : bool
If True, forces the rotation to use
:func:`scipy.ndimage.interpolation.affine_transform`, otherwise it
uses the :class:`skimage.transform.AffineTransform` class and
:func:`skimage.transform.warp`.
The function will also automatically fall back to
:func:`scipy.ndimage.interpolation.affine_transform` if scikit-image
can't be imported.
Default: False
Returns
-------
out : Map
A new Map instance containing the rotated and rescaled data of the
original map.
See Also
--------
sunpy.image.transform.affine_transform : The routine this method calls for the rotation.
Notes
-----
This function will remove old CROTA keywords from the header.
This function will also convert a CDi_j matrix to a PCi_j matrix.
The scikit-image and scipy affine_transform routines do not use the same algorithm,
see :func:`sunpy.image.transform.affine_transform` for details.
This function is not numerically equalivalent to IDL's rot() see the
:func:`sunpy.image.transform.affine_transform` documentation for a
detailed description of the differences.
"""
if angle is not None and rmatrix is not None:
raise ValueError("You cannot specify both an angle and a matrix")
elif angle is None and rmatrix is None:
rmatrix = self.rotation_matrix
# Interpolation parameter sanity
if order not in range(6):
raise ValueError("Order must be between 0 and 5")
# Copy Map
new_map = deepcopy(self)
if angle is not None:
#Calulate the parameters for the affine_transform
c = np.cos(np.deg2rad(angle))
s = np.sin(np.deg2rad(angle))
rmatrix = np.matrix([[c, -s], [s, c]])
# map_center is swapped compared to the x-y convention
array_center = (np.array(self.data.shape)-1)/2.0
# rotation_center is swapped compared to the x-y convention
if recenter:
# Convert the axis of rotation from data coordinates to pixel coordinates
x = self.data_to_pixel(image_center[0], 'x')
y = self.data_to_pixel(image_center[1], 'y')
rotation_center = (y, x)
else:
rotation_center = array_center
#Return a new map
#Copy Header
#.........这里部分代码省略.........
示例12: rotate
def rotate(self, angle=None, rmatrix=None, order=4, scale=1.0,
recenter=False, missing=0.0, use_scipy=False):
"""
Returns a new rotated and rescaled map. Specify either a rotation
angle or a rotation matrix, but not both. If neither an angle or a
rotation matrix are specified, the map will be rotated by the rotation
angle in the metadata.
The map will be rotated around the reference coordinate defined in the
meta data.
Also updates the rotation_matrix attribute and any appropriate header
data so that they correctly describe the new map.
Parameters
----------
angle : `~astropy.units.Quantity`
The angle (degrees) to rotate counterclockwise.
rmatrix : 2x2
Linear transformation rotation matrix.
order : int 0-5
Interpolation order to be used. When using scikit-image this parameter
is passed into :func:`skimage.transform.warp` (e.g., 4 corresponds to
bi-quartic interpolation).
When using scipy it is passed into
:func:`scipy.ndimage.interpolation.affine_transform` where it controls
the order of the spline.
Faster performance may be obtained at the cost of accuracy by using lower values.
Default: 4
scale : float
A scale factor for the image, default is no scaling
recenter : bool
If True, position the axis of rotation at the center of the new map
Default: False
missing : float
The numerical value to fill any missing points after rotation.
Default: 0.0
use_scipy : bool
If True, forces the rotation to use
:func:`scipy.ndimage.interpolation.affine_transform`, otherwise it
uses the :func:`skimage.transform.warp`.
Default: False, unless scikit-image can't be imported
Returns
-------
out : Map
A new Map instance containing the rotated and rescaled data of the
original map.
See Also
--------
sunpy.image.transform.affine_transform : The routine this method calls for the rotation.
Notes
-----
This function will remove old CROTA keywords from the header.
This function will also convert a CDi_j matrix to a PCi_j matrix.
See :func:`sunpy.image.transform.affine_transform` for details on the
transformations, situations when the underlying data is modified prior to rotation,
and differences from IDL's rot().
"""
if angle is not None and rmatrix is not None:
raise ValueError("You cannot specify both an angle and a matrix")
elif angle is None and rmatrix is None:
rmatrix = self.rotation_matrix
# This is out of the quantity_input decorator. To allow the angle=None
# case. See https://github.com/astropy/astropy/issues/3734
if angle:
try:
equivalent = angle.unit.is_equivalent(u.deg)
if not equivalent:
raise u.UnitsError("Argument '{0}' to function '{1}'"
" must be in units convertable to"
" '{2}'.".format('angle', 'rotate',
u.deg.to_string()))
# Either there is no .unit or no .is_equivalent
except AttributeError:
if hasattr(angle, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{0}' to function '{1}' has {2}. "
"You may want to pass in an astropy Quantity instead."
.format('angle', 'rotate', error_msg))
# Interpolation parameter sanity
if order not in range(6):
raise ValueError("Order must be between 0 and 5")
# The FITS-WCS transform is by definition defined around the
# reference coordinate in the header.
rotation_center = u.Quantity([self.reference_coordinate.x,
self.reference_coordinate.y])
# Copy Map
new_map = deepcopy(self)
#.........这里部分代码省略.........
示例13: test_int
def test_int(identity):
# Test casting of integer array to float array
in_arr = np.array([[100]], dtype=int)
with pytest.warns(SunpyUserWarning, match='Input data has been cast to float64.'):
out_arr = affine_transform(in_arr, rmatrix=identity)
assert np.issubdtype(out_arr.dtype, np.floating)
示例14: test_nan_scipy
def test_nan_scipy(identity):
# Test replacement of NaN values for scipy rotation
in_arr = np.array([[np.nan]])
with pytest.warns(SunpyUserWarning, match='Setting NaNs to 0 for SciPy rotation.'):
out_arr = affine_transform(in_arr, rmatrix=identity, use_scipy=True)
assert not np.all(np.isnan(out_arr))
示例15: test_nan_skimage_high
def test_nan_skimage_high(identity):
# Test replacement of NaN values for scikit-image rotation with order >=4
in_arr = np.array([[np.nan]])
with pytest.warns(SunpyUserWarning, match='Setting NaNs to 0 for higher-order scikit-image rotation.'):
out_arr = affine_transform(in_arr, rmatrix=identity, order=4)
assert not np.all(np.isnan(out_arr))