Python numpy 模块,deg2rad() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.deg2rad()。
def augment(
rotation_fn=lambda: np.random.random_integers(0, 360),
translation_fn=lambda: (np.random.random_integers(-20, 20), np.random.random_integers(-20, 20)),
scale_factor_fn=random_zoom_range(),
shear_fn=lambda: np.random.random_integers(-10, 10)
):
def call(x):
rotation = rotation_fn()
translation = translation_fn()
scale = scale_factor_fn()
shear = shear_fn()
tf_augment = AffineTransform(scale=scale, rotation=np.deg2rad(rotation), translation=translation, shear=np.deg2rad(shear))
tf = tf_center + tf_augment + tf_uncenter
x = warp(x, tf, order=1, preserve_range=True, mode='symmetric')
return x
return call
def affine_skew(self, tilt, phi, img, mask=None):
h, w = img.shape[:2]
if mask is None:
mask = np.zeros((h, w), np.uint8)
mask[:] = 255
A = np.float32([[1, 0, 0], [0, 1, 0]])
if phi != 0.0:
phi = np.deg2rad(phi)
s, c = np.sin(phi), np.cos(phi)
A = np.float32([[c, -s], [s, c]])
corners = [[0, 0], [w, 0], [w, h], [0, h]]
tcorners = np.int32(np.dot(corners, A.T))
x, y, w, h = cv2.boundingRect(tcorners.reshape(1, -1, 2))
A = np.hstack([A, [[-x], [-y]]])
img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
if tilt != 1.0:
s = 0.8*np.sqrt(tilt * tilt - 1)
img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
img = cv2.resize(img, (0, 0), fx=1.0 / tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
A[0] /= tilt
if phi != 0.0 or tilt != 1.0:
h, w = img.shape[:2]
mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST)
Ai = cv2.invertAffineTransform(A)
return img, mask, Ai
def mass_streamfun(self):
from scipy import integrate
data = self._obj
# lonlen = len(data.lon)
if 'lon' in data.dims:
data = data.fillna(0).mean('lon')
levax = data.get_axis_num('lev')
stream = integrate.cumtrapz(data * np.cos(np.deg2rad(data.lat)), x=data.lev * 1e2, initial=0., axis=levax)
stream = stream * 2 * np.pi / cc.g * cc.rearth * 1e-9
stream = xr.DataArray(stream, coords=data.coords, dims=data.dims)
stream = stream.rename('ovt')
stream.attrs['long name'] = 'atmosphere overturning circulation'
stream.attrs['unit'] = 'Sv (1e9 kg/s)'
return stream
def draw_laser_frustum(pose, zmin=0.0, zmax=10, fov=np.deg2rad(60)):
N = 30
curve = np.vstack([(
RigidTransform.from_rpyxyz(0, 0, rad, 0, 0, 0) * np.array([[zmax, 0, 0]]))
for rad in np.linspace(-fov/2, fov/2, N)])
curve_w = pose * curve
faces, edges = [], []
for cpt1, cpt2 in zip(curve_w[:-1], curve_w[1:]):
faces.extend([pose.translation, cpt1, cpt2])
edges.extend([cpt1, cpt2])
# Connect the last pt in the curve w/ the current pose,
# then connect the the first pt in the curve w/ the curr. pose
edges.extend([edges[-1], pose.translation])
edges.extend([edges[0], pose.translation])
faces = np.vstack(faces)
edges = np.vstack(edges)
return (faces, edges)
def __init__(self, theta=np.deg2rad(20), displacement=0.25, lookup_history=10,
get_sample=lambda item: item.pose,
on_sampled_cb=lambda index, item: None, verbose=False):
PoseSampler.__init__(self, displacement=displacement, theta=theta,
lookup_history=lookup_history,
get_sample=get_sample,
on_sampled_cb=on_sampled_cb, verbose=verbose)
# class KeyframeVolumeSampler(FrustumVolumeIntersectionPoseSampler):
# def __init__(self, iou=0.5, depth=20, fov=np.deg2rad(60), lookup_history=10,
# get_sample=lambda item: item.pose,
# on_sampled_cb=lambda index, item: None, verbose=False):
# FrustumVolumeIntersectionPoseSampler.__init__(self, iou=iou, depth=depth, fov=fov,
# lookup_history=lookup_history,
# get_sample=get_sample,
# on_sampled_cb=on_sampled_cb, verbose=verbose)
def tsukuba_load_poses(fn):
"""
Retrieve poses
X Y Z R P Y - > X -Y -Z R -P -Y
np.deg2rad(p[3]),-np.deg2rad(p[4]),-np.deg2rad(p[5]),
p[0]*.01,-p[1]*.01,-p[2]*.01, axes='sxyz') for p in P ]
"""
P = np.loadtxt(os.path.expanduser(fn), dtype=np.float64, delimiter=',')
return [ RigidTransform.from_rpyxyz(np.pi, 0, 0, 0, 0, 0) * \
RigidTransform.from_rpyxyz(
np.deg2rad(p[3]),np.deg2rad(p[4]),np.deg2rad(p[5]),
p[0]*.01,p[1]*.01,p[2]*.01, axes='sxyz') * \
RigidTransform.from_rpyxyz(np.pi, 0, 0, 0, 0, 0) for p in P ]
# return [ RigidTransform.from_rpyxyz(
# np.deg2rad(p[3]),-np.deg2rad(p[4]),-np.deg2rad(p[5]),
# p[0]*.01,-p[1]*.01,-p[2]*.01, axes='sxyz') for p in P ]
def ct2lg(dX, dY, dZ, lat, lon):
n = dX.size
R = np.zeros((3, 3, n))
R[0, 0, :] = -np.multiply(np.sin(np.deg2rad(lat)), np.cos(np.deg2rad(lon)))
R[0, 1, :] = -np.multiply(np.sin(np.deg2rad(lat)), np.sin(np.deg2rad(lon)))
R[0, 2, :] = np.cos(np.deg2rad(lat))
R[1, 0, :] = -np.sin(np.deg2rad(lon))
R[1, 1, :] = np.cos(np.deg2rad(lon))
R[1, 2, :] = np.zeros((1, n))
R[2, 0, :] = np.multiply(np.cos(np.deg2rad(lat)), np.cos(np.deg2rad(lon)))
R[2, 1, :] = np.multiply(np.cos(np.deg2rad(lat)), np.sin(np.deg2rad(lon)))
R[2, 2, :] = np.sin(np.deg2rad(lat))
dxdydz = np.column_stack((np.column_stack((dX, dY)), dZ))
RR = np.reshape(R[0, :, :], (3, n))
dx = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
RR = np.reshape(R[1, :, :], (3, n))
dy = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
RR = np.reshape(R[2, :, :], (3, n))
dz = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
return dx, dy, dz
def ct2lg(self, dX, dY, dZ, lat, lon):
n = dX.size
R = numpy.zeros((3, 3, n))
R[0, 0, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
R[0, 1, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.sin(numpy.deg2rad(lon)))
R[0, 2, :] = numpy.cos(numpy.deg2rad(lat))
R[1, 0, :] = -numpy.sin(numpy.deg2rad(lon))
R[1, 1, :] = numpy.cos(numpy.deg2rad(lon))
R[1, 2, :] = numpy.zeros((1, n))
R[2, 0, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
R[2, 1, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.sin(numpy.deg2rad(lon)))
R[2, 2, :] = numpy.sin(numpy.deg2rad(lat))
dxdydz = numpy.column_stack((numpy.column_stack((dX, dY)), dZ))
RR = numpy.reshape(R[0, :, :], (3, n))
dx = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
RR = numpy.reshape(R[1, :, :], (3, n))
dy = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
RR = numpy.reshape(R[2, :, :], (3, n))
dz = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
return dx, dy, dz
def ct2lg(dX, dY, dZ, lat, lon):
n = dX.size
R = np.zeros((3, 3, n))
R[0, 0, :] = -np.multiply(np.sin(np.deg2rad(lat)), np.cos(np.deg2rad(lon)))
R[0, 1, :] = -np.multiply(np.sin(np.deg2rad(lat)), np.sin(np.deg2rad(lon)))
R[0, 2, :] = np.cos(np.deg2rad(lat))
R[1, 0, :] = -np.sin(np.deg2rad(lon))
R[1, 1, :] = np.cos(np.deg2rad(lon))
R[1, 2, :] = np.zeros((1, n))
R[2, 0, :] = np.multiply(np.cos(np.deg2rad(lat)), np.cos(np.deg2rad(lon)))
R[2, 1, :] = np.multiply(np.cos(np.deg2rad(lat)), np.sin(np.deg2rad(lon)))
R[2, 2, :] = np.sin(np.deg2rad(lat))
dxdydz = np.column_stack((np.column_stack((dX, dY)), dZ))
RR = np.reshape(R[0, :, :], (3, n))
dx = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
RR = np.reshape(R[1, :, :], (3, n))
dy = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
RR = np.reshape(R[2, :, :], (3, n))
dz = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
return dx, dy, dz
def ct2lg(self, dX, dY, dZ, lat, lon):
n = dX.size
R = numpy.zeros((3, 3, n))
R[0, 0, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
R[0, 1, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.sin(numpy.deg2rad(lon)))
R[0, 2, :] = numpy.cos(numpy.deg2rad(lat))
R[1, 0, :] = -numpy.sin(numpy.deg2rad(lon))
R[1, 1, :] = numpy.cos(numpy.deg2rad(lon))
R[1, 2, :] = numpy.zeros((1, n))
R[2, 0, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
R[2, 1, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.sin(numpy.deg2rad(lon)))
R[2, 2, :] = numpy.sin(numpy.deg2rad(lat))
dxdydz = numpy.column_stack((numpy.column_stack((dX, dY)), dZ))
RR = numpy.reshape(R[0, :, :], (3, n))
dx = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
RR = numpy.reshape(R[1, :, :], (3, n))
dy = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
RR = numpy.reshape(R[2, :, :], (3, n))
dz = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
return dx, dy, dz
def ct2lg(self, dX, dY, dZ, lat, lon):
n = dX.size
R = numpy.zeros((3, 3, n))
R[0, 0, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
R[0, 1, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.sin(numpy.deg2rad(lon)))
R[0, 2, :] = numpy.cos(numpy.deg2rad(lat))
R[1, 0, :] = -numpy.sin(numpy.deg2rad(lon))
R[1, 1, :] = numpy.cos(numpy.deg2rad(lon))
R[1, 2, :] = numpy.zeros((1, n))
R[2, 0, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
R[2, 1, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.sin(numpy.deg2rad(lon)))
R[2, 2, :] = numpy.sin(numpy.deg2rad(lat))
dxdydz = numpy.column_stack((numpy.column_stack((dX, dY)), dZ))
RR = numpy.reshape(R[0, :, :], (3, n))
dx = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
RR = numpy.reshape(R[1, :, :], (3, n))
dy = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
RR = numpy.reshape(R[2, :, :], (3, n))
dz = numpy.sum(numpy.multiply(RR, dxdydz.transpose()), axis=0)
return dx, dy, dz
def augment_deterministic(
rotation=0,
translation=0,
scale_factor=1,
shear=0
):
def call(x):
scale = scale_factor, scale_factor
rotation_tmp = rotation
tf_augment = AffineTransform(
scale=scale,
rotation=np.deg2rad(rotation_tmp),
translation=translation,
shear=np.deg2rad(shear)
)
tf = tf_center + tf_augment + tf_uncenter
x = warp(x, tf, order=1, preserve_range=True, mode='symmetric')
return x
return call
def effect(self, point):
res = []
# print(self.centers)
for center in self.centers:
center_x, center_y = center
src_x, src_y = point.pos
# Check angle
angle = np.arctan((center_x - src_x) / (center_y - src_y))
if np.abs(angle) > self.angle / 2:
continue
angle = np.deg2rad(90) + angle
u_len = np.sqrt((center_x - src_x) ** 2 + (center_y - src_y) ** 2)
reverse_v = (self.r_index - 1) / self.radius - self.r_index / u_len
v_len = 1 / reverse_v
if v_len > 0:
p_type = 'real'
else:
p_type = 'fake'
target = line_end(point.pos, angle, u_len + v_len)
p = Point(target, p_type, 1)
# point.passed.append(self)
res.append(p)
return tuple(res)
def setRotation(self, rot, smallangle=True):
'''
Rotation angle in degrees
'''
rad = np.deg2rad(rot)
if smallangle:
# bring rad close to zero.
rad = np.fmod(rad, 2.*pi)
if rad > pi:
rad -= 2.*pi
if rad < -pi:
rad += 2.*pi
self.T = [ 0., -rad, rad, 0. ]
else:
cr = np.cos(rad)
sr = np.sin(rad)
self.T = [ cr - 1, -sr, sr, cr - 1 ]
def plot(self, values, *args, **kw):
"""Plot a concept's cause-effect repertoire on the radarchart.
Examples:
>>> full_rep = np.hstack([cause_rep, effect_rep])
>>> radar.plot(full_rep, '-', lw=2, label=mechanism_label)
Args:
values (np.ndarray): A flat array of state probabilitites, given in
the same order as the `titles` argument to the ConstellationRadar
constructor.
Also takes standard matplotlib linespec arguments, such as color, style,
linewidth, etc.
"""
angle = np.deg2rad(np.r_[self.angles, self.angles[0]])
values = np.r_[values, values[0]]
self.ax.plot(angle, values, *args, **kw)
def _rotate_interp(array, alpha, center, mode='constant', cval=0):
'''
Rotation around a provided center
This is the only way to be sure where exactly is the center of rotation.
'''
dtype = array.dtype
dims = array.shape
alpha_rad = -np.deg2rad(alpha)
x, y = np.meshgrid(np.arange(dims[1], dtype=dtype), np.arange(dims[0], dtype=dtype))
xp = (x-center[0])*np.cos(alpha_rad) + (y-center[1])*np.sin(alpha_rad) + center[0]
yp = -(x-center[0])*np.sin(alpha_rad) + (y-center[1])*np.cos(alpha_rad) + center[1]
rotated = ndimage.map_coordinates(img, [yp, xp], mode=mode, cval=cval, order=3)
return rotated
def calc_coord(self, transCoord, p, d, a, e, i, w):
# cx, cy, cz ?? ??
# p, ?? d, ?? ??
# a ??, e ???
# i ?? ???
unitAng = 360/p
ang = (unitAng * d) % 360
theta = np.deg2rad(ang)
b = a * np.sqrt(1 - np.power(e, 2))
x = transCoord[0] + a * np.cos(theta)
y = transCoord[1] + b * np.sin(theta)
z = 0.0
#rotate
w = np.deg2rad(w)
x1, y1 = x, y
#x = transCoord[0] + (x1 * np.cos(w) - y1 * np.sin(w))
#y = transCoord[1] + (x1 * np.sin(w) + y1 * np.cos(w))
coord = [x, y, z]
return coord
def mt_diff( mt1, mt2):
fps = np.deg2rad([mt1.get_fps(), mt2.get_fps()])
diff = [999999999, 999999999]
for i in range(2):
for j in range(2):
test = haversine(lon1=fps[0][i][0], phi1=fps[0][i][1], lon2=fps[1][j][0], phi2=fps[1][j][1], radius=1.)
while test>np.pi/2:
test -= np.pi/2
if test < diff[i]:
diff[i] = test
return np.rad2deg(np.mean(diff))
def __init__(self, f0=997, fs=96000, duration=None, gaindb=0, nofsamples=0,
phasedeg=0, harmonics=7,):
"""Construct a square wave by adding odd harmonics with decreasing
amplitude, i.e. Fourier Series.
"""
Sinetone.__init__(self, f0=f0, phasedeg=phasedeg, fs=fs, nofsamples=nofsamples,
duration=duration, gaindb=0)
assert harmonics >= 0
self.harmonics = harmonics
self._logger.debug("fundamental f0: %.1f" %f0)
for n in range(3, 2*(self.harmonics+1), 2):
if n <= 15:
self._logger.debug("adding harmonic n: %2i with amplitude 1/%i" %(n, n))
if n == 17:
self._logger.debug("adding %i more harmonics..." %(self.harmonics-(n-3)//2))
#self.samples[:,0] += np.sin(2*np.pi*(n*f0)*self.get_time()+np.deg2rad(phasedeg*n))/n
self.samples[:,0] += (1/n)*self._sine_gen(n*f0, n*phasedeg)
self.gain(gaindb)
def construct_K(image_size, focal_len=None, fov_degrees=None, fov_radians=None):
""" create calibration matrix K using the image size and focal length or field of view angle
Assumes 0 skew and principal point at center of image
Note that image_size = (width, height)
Note that fov is assumed to be measured horizontally
"""
if not np.sum([focal_len is not None, fov_degrees is not None, fov_radians is not None]) == 1:
raise Exception('Specify exactly one of [focal_len, fov_degrees, fov_radians]')
if fov_degrees is not None:
fov_radians = np.deg2rad(fov_degrees)
if fov_radians is not None:
focal_len = image_size[0] / (2.0 * np.tan(fov_radians/2.0))
K = np.array([[focal_len, 0, image_size[0]/2.0], [0, focal_len, image_size[1]/2.0], [0, 0, 1]])
return K
def gaussian(height, center_x, center_y, width_x, width_y, rotation):
"""Returns a gaussian function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
rotation = np.deg2rad(rotation)
center_x = center_x * np.cos(rotation) - center_y * np.sin(rotation)
center_y = center_x * np.sin(rotation) + center_y * np.cos(rotation)
def rotgauss(x,y):
xp = x * np.cos(rotation) - y * np.sin(rotation)
yp = x * np.sin(rotation) + y * np.cos(rotation)
g = height*np.exp(
-(((center_x-xp)/width_x)**2+
((center_y-yp)/width_y)**2)/2.)
return g
return rotgauss
def _add_table(self, name):
p = PoseStamped()
p.header.frame_id = self._robot.get_planning_frame()
p.header.stamp = rospy.Time.now()
p.pose.position.x = 0.2
p.pose.position.y = 0.0
p.pose.position.z = 0.1
q = quaternion_from_euler(0.0, 0.0, numpy.deg2rad(90.0))
p.pose.orientation = Quaternion(*q)
# Table size from ~/.gazebo/models/table/model.sdf, using the values
# for the surface link.
self._scene.add_box(name, p, (0.005, 0.005, 0.005))
return p.pose
def traj_diff(t1, t2):
"""Compute trajectory difference.
Parameters
----------
t1, t2 : DataFrame
Trajectories.
Returns
-------
diff : DataFrame
Trajectory difference. It can be interpreted as errors in `t1` relative
to `t2`.
"""
diff = t1 - t2
diff['lat'] *= np.deg2rad(earth.R0)
diff['lon'] *= np.deg2rad(earth.R0) * np.cos(0.5 *
np.deg2rad(t1.lat + t2.lat))
diff['h'] %= 360
diff.h[diff.h < -180] += 360
diff.h[diff.h > 180] -= 360
return diff.loc[t1.index.intersection(t2.index)]
def reset(self):
"""Clear computed trajectory except the initial point."""
lat, lon, VE, VN, h, p, r, stamp = self._init_values
self.lat_arr[0] = np.deg2rad(lat)
self.lon_arr[0] = np.deg2rad(lon)
self.VE_arr[0] = VE
self.VN_arr[0] = VN
self.Cnb_arr[0] = dcm.from_hpr(h, p, r)
self.traj = pd.DataFrame(index=pd.Index([stamp], name='stamp'))
self.traj['lat'] = [lat]
self.traj['lon'] = [lon]
self.traj['VE'] = [VE]
self.traj['VN'] = [VN]
self.traj['h'] = [h]
self.traj['p'] = [p]
self.traj['r'] = [r]
def equinox(date, eop_correction=True, terms=106, kinematic=True):
"""Equinox equation in degrees
"""
epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms)
equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar))
if date.d >= 50506 and kinematic:
# Starting 1992-02-27, we apply the effect of the moon
ttt = date.change_scale('TT').julian_century
om_m = 125.04455501 - (5 * 360. + 134.1361851) * ttt\
+ 0.0020756 * ttt ** 2 + 2.139e-6 * ttt ** 3
equin += 0.00264 * np.sin(np.deg2rad(om_m)) + 6.3e-5 * np.sin(np.deg2rad(2 * om_m))
# print("esquinox = {}\n".format(equin / 3600))
return equin / 3600.
def test_read():
tle = Tle(ref)
assert tle.name == "ISS (ZARYA)"
assert tle.norad_id == 25544
assert tle.cospar_id == "1998-067A"
assert tle.epoch == Date(2008, 9, 20, 12, 25, 40, 104192)
assert tle.ndot == -2.182e-5
assert tle.ndotdot == 0.
assert tle.bstar == -0.11606e-4
assert tle.i == np.deg2rad(51.6416)
assert tle.? == np.deg2rad(247.4627)
assert tle.e == 6.703e-4
assert tle.? == np.deg2rad(130.5360)
assert tle.M == np.deg2rad(325.0288)
assert tle.n == 15.72125391 * 2 * np.pi / 86400.
tle = Tle(ref.splitlines()[1:])
assert tle.name == ""
with raises(ValueError):
ref2 = ref[:-1] + "8"
Tle(ref2)
def gaussian(height, center_x, center_y, width_x, width_y, rotation):
"""Returns a gaussian function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
rotation = np.deg2rad(rotation)
center_x = center_x * np.cos(rotation) - center_y * np.sin(rotation)
center_y = center_x * np.sin(rotation) + center_y * np.cos(rotation)
def rotgauss(x,y):
xp = x * np.cos(rotation) - y * np.sin(rotation)
yp = x * np.sin(rotation) + y * np.cos(rotation)
g = height*np.exp(
-(((center_x-xp)/width_x)**2+
((center_y-yp)/width_y)**2)/2.)
return g
return rotgauss
def gaussian_pdf(height, center_x, center_y, width_x, width_y, rotation):
"""Returns a pdf function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
rotation = np.deg2rad(rotation)
center_x = center_x * np.cos(rotation) - center_y * np.sin(rotation)
center_y = center_x * np.sin(rotation) + center_y * np.cos(rotation)
def rotgauss(x,y):
xp = x * np.cos(rotation) - y * np.sin(rotation)
yp = x * np.sin(rotation) + y * np.cos(rotation)
g = height*np.exp(
-(((center_x-xp)/width_x)**2+
((center_y-yp)/width_y)**2)/2.)
return g
return rotgauss
# doesn't allow for flattening or mean shifting, otherwise occasionally
# we get gaussians that are in the wrong place or drastically the wrong shape
def get_area_extent(self, size, offsets, factors, platform_height):
"""Get the area extent of the file."""
nlines, ncols = size
h = platform_height
# count starts at 1
cols = 1 - 0.5
lines = 1 - 0.5
ll_x, ll_y = self.get_xy_from_linecol(lines, cols, offsets, factors)
cols += ncols
lines += nlines
ur_x, ur_y = self.get_xy_from_linecol(lines, cols, offsets, factors)
return (np.deg2rad(ll_x) * h, np.deg2rad(ll_y) * h,
np.deg2rad(ur_x) * h, np.deg2rad(ur_y) * h)
def test_get_geostationary_angle_extent(self):
"""Get max geostationary angles."""
geos_area = mock.MagicMock()
geos_area.proj_dict = {'a': 6378169.00,
'b': 6356583.80,
'h': 35785831.00}
expected = (0.15185342867090912, 0.15133555510297725)
np.testing.assert_allclose(expected,
hf.get_geostationary_angle_extent(geos_area))
geos_area.proj_dict = {'a': 1000.0,
'b': 1000.0,
'h': np.sqrt(2) * 1000.0 - 1000.0}
expected = (np.deg2rad(45), np.deg2rad(45))
np.testing.assert_allclose(expected,
hf.get_geostationary_angle_extent(geos_area))
def augmentate(self):
angles = [45, 90, 135, 180, 225, 270, 315]
scale = 1.0
for img in self.images:
print "image shape : ", img.shape
w = img.shape[1]
h = img.shape[0]
img_vmirror = cv2.flip(img,1)
skimage.io.imsave("testv"+".jpg", img_vmirror )
for angle in angles:
#rangle = np.deg2rad(angle)
# nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
# nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
rot_mat = cv2.getRotationMatrix2D((w*0.5, h*0.5), angle, scale)
# rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0]))
# rot_mat[0,2] += rot_move[0]
# rot_mat[1,2] += rot_move[1]
new_img = cv2.warpAffine(img, rot_mat, (int(math.ceil(w)), int(math.ceil(h))), flags=cv2.INTER_LANCZOS4)
skimage.io.imsave("test"+str(angle)+".jpg", new_img)
new_img_vmirror = cv2.flip(new_img, 1)
skimage.io.imsave("testv"+str(angle)+".jpg", new_img_vmirror)
# img_rmirror = cv2.flip(new_img, 0)
# skimage.io.imsave("testh"+str(angle)+".jpg", img_rmirror)
def sphericalToXYZ(lat,lon,radius=1):
'''
Convert spherical coordinates to x,y,z
@param lat: Latitude, scalar or array
@param lon: Longitude, scalar or array
@param radius: Sphere's radius
@return Numpy array of x,y,z coordinates
'''
phi = np.deg2rad(90.0 - lat)
theta = np.deg2rad(lon % 360)
x = radius * np.cos(theta)*np.sin(phi)
y = radius * np.sin(theta)*np.sin(phi)
z = radius * np.cos(phi)
if np.isscalar(x) == False:
return np.vstack([x,y,z]).T
else:
return np.array([x,y,z])
def plot_chara(self, angle, step,Rstar = 1):
counter = 1000
i = np.arange(counter)
Rstar_tmp = self.Rstar_min + i / counter
Rstar_tmp = Rstar_tmp[Rstar_tmp < 1]
fai = self.chara_line(Rstar_tmp)
for j in range(0, angle, step):
x1 = self.chara_x(Rstar_tmp * Rstar, fai - self.const + np.deg2rad(j))
y1 = self.chara_y(Rstar_tmp * Rstar, fai - self.const + np.deg2rad(j))
x2 = self.chara_x(Rstar_tmp * Rstar, - (fai - self.const - np.deg2rad(j)))
y2 = self.chara_y(Rstar_tmp * Rstar, - (fai - self.const - np.deg2rad(j)))
plt.plot(x1, y1, "r")
plt.plot(x2, y2, "k")
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
# top arc angle is 0
# v1 must be smaller than v2
def make_upper_straight_line(self):
""" make upper straight line """
targetx = self.lower_concave_in_x_end
x = self.upper_convex_in_x_end
y = self.upper_convex_in_y_end
targety = np.tan(np.deg2rad(self.beta_in)) * targetx + y - np.tan(np.deg2rad(self.beta_in)) * x
self.upper_straight_in_x = [targetx, x]
self.upper_straight_in_y = [targety, y]
self.shift = - abs(self.lower_concave_in_y_end - targety)
targetx = self.lower_concave_out_x_end
x = self.upper_convex_out_x_end
y = self.upper_convex_out_y_end
targety = np.tan(np.deg2rad(self.beta_out)) * targetx + y - np.tan(np.deg2rad(self.beta_out)) * x
self.upper_straight_out_x = [targetx, x]
self.upper_straight_out_y = [targety, y]
def distort_affine_skimage(image, rotation=10.0, shear=5.0, random_state=None):
if random_state is None:
random_state = np.random.RandomState(None)
rot = np.deg2rad(np.random.uniform(-rotation, rotation))
sheer = np.deg2rad(np.random.uniform(-shear, shear))
shape = image.shape
shape_size = shape[:2]
center = np.float32(shape_size) / 2. - 0.5
pre = transform.SimilarityTransform(translation=-center)
affine = transform.AffineTransform(rotation=rot, shear=sheer, translation=center)
tform = pre + affine
distorted_image = transform.warp(image, tform.params, mode='reflect')
return distorted_image.astype(np.float32)
def __init__(self, fig, variables, ranges, n_ordinate_levels=6):
angles = np.arange(0, 360, 360./len(variables))
axes = [fig.add_axes([0,0, 1,1],polar=True,
label = "axes{}".format(i))
for i in range(len(variables))]
l, text = axes[0].set_thetagrids(angles, labels = variables)
[txt.set_rotation(angle-90) for txt, angle in zip(text, angles)]
for ax in axes[1:]:
ax.patch.set_visible(False)
ax.grid("off")
ax.xaxis.set_visible(False)
for i, ax in enumerate(axes):
grid = np.linspace(*ranges[i], num=n_ordinate_levels)
gridlabel = ["{}".format(round(x,2)) for x in grid]
if ranges[i][0] > ranges[i][1]:
grid = grid[::-1] # hack to invert grid
# gridlabels aren't reversed
gridlabel[0] = "" # clean up origin
ax.set_rgrids(grid, labels=gridlabel, angle=angles[i])
ax.set_ylim(*ranges[i])
# variables for plotting
self.angle = np.deg2rad(np.r_[angles, angles[0]])
self.ranges = ranges
self.ax = axes[0]
def generate_circle_points(radius, initial_angle, final_angle, points=199):
"""
This methods generates points in a circle shape at (0,0) with a specific radius and from a
starting angle to a final angle.
Args:
radius: radius of the circle in microns
initial_angle: initial angle of the drawing in degrees
final_angle: final angle of the drawing in degrees
points: amount of points to be generated (default 199)
Returns:
Set of points that form the circle
"""
theta = np.linspace( np.deg2rad(initial_angle),
np.deg2rad(final_angle),
points)
return radius * np.cos(theta) , radius * np.sin(theta)
def disttoedge(self, x, y, d):
rd = numpy.deg2rad(d)
dx, dy = numpy.cos(rd), numpy.sin(rd)
maxx = self.width()
maxy = self.height()
if dx == 0:
lefthit, righthit = sys.maxsize, sys.maxsize
tophit, bothit = (maxy - y) / dy, (-y) / dy
elif dy == 0:
lefthit, righthit = (-x) / dx, (maxx - x) / dx
tophit, bothit = sys.maxsize, sys.maxsize
else:
lefthit, righthit = (-x) / dx, (maxx - x) / dx
tophit, bothit = (maxy - y) / dy, (-y) / dy
# Return smallest positive
dists = list(filter(lambda s: s > 0, [lefthit, righthit, tophit, bothit]))
if len(dists) == 0:
return 0
else:
return min(dists)
def rotation_matrix_axis(C_values):
# Change coordinate system through matrix C
rx = np.deg2rad(float(C_values[0]))
ry = np.deg2rad(float(C_values[1]))
rz = np.deg2rad(float(C_values[2]))
Cx = np.matrix([[1, 0, 0],
[0, np.cos(rx), np.sin(rx)],
[0, -np.sin(rx), np.cos(rx)]])
Cy = np.matrix([[np.cos(ry), 0, -np.sin(ry)],
[0, 1, 0],
[np.sin(ry), 0, np.cos(ry)]])
Cz = np.matrix([[np.cos(rz), np.sin(rz), 0],
[-np.sin(rz), np.cos(rz), 0],
[0, 0, 1]])
C = Cx * Cy * Cz
Cinv = np.linalg.inv(C)
return C, Cinv
def rotation_matrix(bone, tx, ty, tz):
# Construct rotation matrix M
tx = np.deg2rad(tx)
ty = np.deg2rad(ty)
tz = np.deg2rad(tz)
Mx = np.matrix([[1, 0, 0],
[0, np.cos(tx), np.sin(tx)],
[0, -np.sin(tx), np.cos(tx)]])
My = np.matrix([[np.cos(ty), 0, -np.sin(ty)],
[0, 1, 0],
[np.sin(ty), 0, np.cos(ty)]])
Mz = np.matrix([[np.cos(tz), np.sin(tz), 0],
[-np.sin(tz), np.cos(tz), 0],
[0, 0, 1]])
M = Mx * My * Mz
L = bone.Cinv * M * bone.C
return L
def keyframedb(self, theta=np.deg2rad(20), displacement=0.25, lookup_history=10, verbose=True):
sampler = PoseSampler(theta=theta, displacement=displacement, lookup_history=lookup_history,
get_sample=lambda (t, channel, frame): frame.pose, verbose=verbose)
self.iterframes = partial(sampler.iteritems, self.iterframes())
return self
# def list_annotations(self, target_name=None):
# " List of lists"
# inds = self.annotated_inds
# return [ filter(lambda frame:
# target_name is None or name is in target_name,
# self.dataset.annotationdb.iterframes(inds))
# def _build_graph(self):
# # Keep a queue of finite length to ensure
# # time-sync with RGB and IMU
# self.__pose_q = deque(maxlen=10)
# self.nodes_ = []
# for (t,ch,data) in self.dataset_.itercursors(topics=[]):
# if ch == TANGO_VIO_CHANNEL:
# self.__pose_q.append(data)
# continue
# if not len(self.__pose_q):
# continue
# assert(ch == TANGO_RGB_CHANNEL)
# self.nodes_.append(dict(img=data, pose=self.__pose_q[-1]))
# Basic type for tango frame (includes pose, image, timestamp)
def draw_camera(pose, zmin=0.0, zmax=0.1, fov=np.deg2rad(60)):
frustum = Frustum(pose, zmin=zmin, zmax=zmax, fov=fov)
nul, nll, nlr, nur, ful, fll, flr, fur = frustum.vertices
# nll, nlr, nur, nul, fll, flr, fur, ful = frustum.vertices
faces = []
# Triangles: Front Face
faces.extend([ful, fur, flr])
faces.extend([flr, ful, fll])
# Triangles: Back Face
faces.extend([nul, nur, nlr])
faces.extend([nlr, nul, nll])
# Triangles: Four walls (2-triangles per face)
left, top, right, bottom = [fll, nll, ful, ful, nll, nul], \
[ful, nul, fur, fur, nul, nur], \
[fur, nur, flr, flr, nur, nlr], \
[flr, nlr, fll, fll, nlr, nll]
faces.extend([left, top, right, bottom]) # left, top, right, bottom wall
faces = np.vstack(faces)
# Lines: zmin-zmax
pts = []
pts.extend([ful, fur, flr, fll, ful])
pts.extend([ful, fll, nll, nul, ful])
pts.extend([ful, nul, nur, fur, ful])
pts.extend([fur, nur, nlr, flr, fur])
pts.extend([flr, nlr, nll, fll, flr])
pts = np.vstack(pts)
return (faces, np.hstack([pts[:-1], pts[1:]]).reshape((-1,3)))
def __init__(self, pose, zmin=0.0, zmax=0.1, fov=np.deg2rad(60)):
# FoV derived from fx,fy,cx,cy=500,500,320,240
# fovx, fovy = 65.23848614 51.28201165
rx, ry = 0.638, 0.478
self.pose = pose
arr = [np.array([-rx, -ry, 1.]) * zmin,
np.array([-rx, ry, 1.]) * zmin,
np.array([ rx, ry, 1.]) * zmin,
np.array([ rx, -ry, 1.]) * zmin,
np.array([-rx, -ry, 1.]) * zmax,
np.array([-rx, ry, 1.]) * zmax,
np.array([ rx, ry, 1.]) * zmax,
np.array([ rx, -ry, 1.]) * zmax]
# vertices: nul, nll, nlr, nur, ful, fll, flr, fur
self.vertices_ = self.pose * np.vstack(arr)
# self.near, self.far = np.array([0,0,zmin]), np.array([0,0,zmax])
# self.near_off, self.far_off = np.tan(fov / 2) * zmin, np.tan(fov / 2) * zmax
# arr = [self.near + np.array([-1, -1, 0]) * self.near_off,
# self.near + np.array([1, -1, 0]) * self.near_off,
# self.near + np.array([1, 1, 0]) * self.near_off,
# self.near + np.array([-1, 1, 0]) * self.near_off,
# self.far + np.array([-1, -1, 0]) * self.far_off,
# self.far + np.array([1, -1, 0]) * self.far_off,
# self.far + np.array([1, 1, 0]) * self.far_off,
# self.far + np.array([-1, 1, 0]) * self.far_off]
# nll, nlr, nur, nul, fll, flr, fur, ful = self.pose * np.vstack(arr)
# return nll, nlr, nur, nul, fll, flr, fur, ful
def __init__(self, theta=np.deg2rad(20), displacement=0.25, lookup_history=10,
get_sample=lambda item: item,
on_sampled_cb=lambda index, item: None, verbose=False):
Sampler.__init__(self, lookup_history=lookup_history,
get_sample=get_sample,
on_sampled_cb=on_sampled_cb, verbose=verbose)
self.displacement_ = displacement
self.theta_ = theta
def obj_set_position_target(self, handle, angle):
return self.RAPI_rc(vrep.simxSetJointTargetPosition( self.cID,handle,
-np.deg2rad(angle),
vrep.simx_opmode_blocking))
def getJitteredParams(self, num, center=(0.0, 0.0), maxRot=(-5.0, 5.0), maxTranslate=(-2.0, 2.0),
maxScale=(-0.1, 0.1), mirror=True):
if not (type(maxRot) is tuple):
maxRot = (-maxRot, maxRot)
if not (type(maxTranslate) is tuple):
maxTranslate = (-maxTranslate, maxTranslate)
if not (type(maxScale) is tuple):
maxScale = (-maxScale, maxScale)
alphas = self.rng.rand(num) * (maxRot[1] - maxRot[0]) + maxRot[0]
alphas = numpy.deg2rad(alphas)
tx = self.rng.rand(num) * (maxTranslate[1] - maxTranslate[0]) + maxTranslate[0]
ty = self.rng.rand(num) * (maxTranslate[1] - maxTranslate[0]) + maxTranslate[0]
sc = 2 ** -(self.rng.rand(num) * (maxScale[1] - maxScale[0]) + maxScale[0])
if mirror:
mi = self.rng.randint(2, size=num) # mirror true or false
else:
mi = numpy.zeros(num)
transformationMats = []
for i in range(num):
# First is not modified
if i == 0:
t = numpy.array([0, 0, 0, 1, 0])
else:
t = numpy.array([alphas[i], tx[i], ty[i], sc[i], mi[i]])
transformationMats.append(t)
return transformationMats
def rotate(self, deg, center = (0,0)):
''' rotates the image by set degree'''
#where c is the cosine of the angle, s is the sine of the angle and
#x0, y0 are used to correctly translate the rotated image.
# size of source image
src_dimsx = self.data.shape[0]
src_dimsy = self.data.shape[1]
# get the radians and calculate sin and cos
rad = np.deg2rad(deg)
c = np.cos(rad)
s = np.sin(rad)
# calculate center of image
cx = center[0] + src_dimsx/2
cy = center[1] + src_dimsy/2
# factor that moves the index to the center
x0 = cx - c*cx - s*cx
y0 = cy - c*cy + s*cy
# initialize destination image
dest = MyImage(self.data.shape)
for y in range(src_dimsy):
for x in range(src_dimsx):
# get the source indexes
src_x = int(c*x + s*y + x0)
src_y = int(-s*x + c*y + y0)
if src_y > 0 and src_y < src_dimsy and src_x > 0 and src_x < src_dimsx:
#paste the value in the destination image
dest.data[x][y] = self.data[src_x][src_y]
self.data = dest.data
def normalize_cord(latitude, longitude):
'''
Normalize GPS cord array, assuming the earth is shpherical
:param latitude: latitude array to normalize
:param longitude: longitude array to normalize
:return: normalized arrays (np.array)
'''
rad_lat = np.deg2rad(latitude)
rad_lon = np.deg2rad(longitude)
x = np.cos(rad_lat) * np.cos(rad_lon)
y = np.cos(rad_lat) * np.sin(rad_lon)
z = np.sin(rad_lat)
return x, y, z
def d_xy(self):
"""
The sampling interval along the (X, Y) spatial dimensions,
translated from the pixel size.
Unit: [Mpc]
Reference: Ref.[liu2014].Eq.(A7)
"""
pixelsize = self.pixelsize / 3600 # [arcsec] -> [deg]
d_xy = self.DMz * np.deg2rad(pixelsize)
return d_xy
def rotate_about_center(src, angle, scale=1.):
w = src.shape[1]
h = src.shape[0]
rangle = np.deg2rad(angle) # angle in radians
nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
rot_mat = cv2.getRotationMatrix2D((nw*0.5, nh*0.5), angle, scale)
rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0]))
rot_mat[0,2] += rot_move[0]
rot_mat[1,2] += rot_move[1]
return cv2.warpAffine(src, rot_mat, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_LANCZOS4)