def transformImg(self, img, t):
imgT = img.transform((int(img.size[0]*t[3]),int(img.size[1]*t[3])), Image.EXTENT, (0,0,img.size[0],img.size[1]), Image.BILINEAR)
imgT = imgT.rotate(numpy.rad2deg(t[0]), Image.BILINEAR, expand=1)
if t[4] == 1.:
imgT = imgT.transpose(Image.FLIP_LEFT_RIGHT)
# crop only valid part
if self.crop:
imgT = imgT.crop(self.getInscribedRectangle(t[0], (img.size[0]*t[3], img.size[1]*t[3])))
# crop from translation
imgT = imgT.resize((int(self.imgSize[0]*1.1), int(self.imgSize[1]*1.1)), Image.BILINEAR)
xstart = int((imgT.size[0] // 2 - t[1]) - self.imgSize[0] // 2)
ystart = int((imgT.size[1] // 2 - t[2]) - self.imgSize[1] // 2)
assert xstart >= 0 and ystart >= 0
return imgT.crop((xstart, ystart, xstart+self.imgSize[0], ystart+self.imgSize[1]))
python类rad2deg()的实例源码
def getApproxRotation(self):
# do an SVD to express T as a rotation matrix.
M = np.array([[self.T[0]+1., self.T[1]], [self.T[2], self.T[3]+1.]])
U,S,V = np.linalg.svd(M)
print 'approx rotation:'
print 'M='
print M
print 'U='
print U
print 'V='
print V
print 'S='
print S
r1 = np.rad2deg(np.arctan2(U[0,1], U[0,0]))
r2 = np.rad2deg(np.arctan2(V[0,1], V[0,0]))
print 'r1', r1
print 'r2', r2
print 'rotation', r1-r2
return r1-r2
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def insertion_pitch(self):
_circ_dv = self.circ_dv()
_t_ap_dv = self.target_apoapsis_speed_dv()
_m = np.rad2deg(self.mean_anomaly())
_burn_time = self.maneuver_burn_time(self.circ_dv())
@jit(nopython=True)
def pitch_calcs_low():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))
@jit(nopython=True)
def pitch_calcs_high():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)
if self.parking_orbit_alt <= 300000: return pitch_calcs_low()
else: return pitch_calcs_high()
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def insertion_pitch(self):
_circ_dv = self.circ_dv()
_t_ap_dv = self.target_apoapsis_speed_dv()
_m = np.rad2deg(self.mean_anomaly())
_burn_time = self.maneuver_burn_time(self.circ_dv())
@jit(nopython=True)
def pitch_calcs_low():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))
@jit(nopython=True)
def pitch_calcs_high():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)
if self.target_orbit_alt <= 250000: return pitch_calcs_low()
else: return pitch_calcs_high()
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + 360, 360))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def SortByAngle(kNearestPoints, currentPoint, prevPoint):
''' Sorts the k nearest points given by angle '''
angles = np.zeros(kNearestPoints.shape[0])
i = 0
for NearestPoint in kNearestPoints:
# calculate the angle
angle = np.arctan2(NearestPoint[1]-currentPoint[1],
NearestPoint[0]-currentPoint[0]) - \
np.arctan2(prevPoint[1]-currentPoint[1],
prevPoint[0]-currentPoint[0])
angle = np.rad2deg(angle)
# only positive angles
angle = np.mod(angle+360,360)
#print NearestPoint[0], NearestPoint[1], angle
angles[i] = angle
i=i+1
return kNearestPoints[np.argsort(angles)]
def get_motion_level(directory,translation_threshold=2.5,rotation_threshold=2.5):
'''Roughly classify the amount of motion per slice for calculating likelihood of signal dropouts - 1 = severe motion, 2 = moderate motion'''
motion_path = os.path.join(directory,'motion')
motion = np.loadtxt(motion_path)
max_motion = np.max(motion[:,1:],axis=0)
min_motion = np.min(motion[:,1:],axis=0)
diff_motion = np.abs(max_motion-min_motion)
diff_motion[:3] = diff_motion[:3]*1000
diff_motion[3:] = np.rad2deg(diff_motion[3:])
if np.any( diff_motion[:3] > translation_threshold):
return 1
elif np.any(diff_motion[3:] > rotation_threshold):
return 1
elif np.any( diff_motion[:3] > 1):
return 2
elif np.any(diff_motion[3:] > 1):
return 2
else:
return 0
def calc_Tb(self, freq):
"""
Calculate the surface brightness temperature of the point sources.
Parameters
------------
freq: `~astropy.units.Quantity`
Frequency, e.g., `1.0*au.MHz`
Return
------
Tb_list: list
Point sources brightness temperature
"""
# Tb_list
num_ps = self.ps_catalog.shape[0]
Tb_list = np.zeros((num_ps,))
sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2 # [sr] -> [arcsec^2]
# Iteratively calculate Tb
for i in range(num_ps):
ps_area = self.ps_catalog['Area (sr)'][i] # [sr]
area = ps_area * sr_to_arcsec2
Tb_list[i] = self.calc_single_Tb(area, freq)
return Tb_list
def calc_Tb(self, freq):
"""
Calculate the surface brightness temperature of the point sources.
Parameters
------------
freq: `~astropy.units.Quantity`
Frequency, e.g., `1.0*au.MHz`
Return
------
Tb_list: list
Point sources brightness temperature
"""
# Tb_list
num_ps = self.ps_catalog.shape[0]
Tb_list = np.zeros((num_ps, 3))
sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2 # [sr] -> [arcsec^2]
# Iteratively calculate Tb
for i in range(num_ps):
ps_area = self.ps_catalog['Area (sr)'][i] # [sr]
area = ps_area * sr_to_arcsec2
Tb_list[i, :] = self.calc_single_Tb(area, freq)
return Tb_list
def calc_Tb(self, freq):
"""
Calculate the surface brightness temperature of the point sources.
Parameters
------------
freq: `~astropy.units.Quantity`
Frequency, e.g., `1.0*au.MHz`
Return
------
Tb_list: list
Point sources brightness temperature
"""
# Tb_list
num_ps = self.ps_catalog.shape[0]
Tb_list = np.zeros((num_ps,))
sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2 # [sr] -> [arcsec^2]
# Iteratively calculate Tb
for i in range(num_ps):
ps_area = self.ps_catalog['Area (sr)'][i] # [sr]
area = ps_area * sr_to_arcsec2
Tb_list[i] = self.calc_single_Tb(area, freq)
return Tb_list
def calc_Tb(self, freq):
"""
Calculate the surface brightness temperature of the point sources.
Parameters
------------
freq: `~astropy.units.Quantity`
Frequency, e.g., `1.0*au.MHz`
Return
------
Tb_list: list
Point sources brightness temperature
"""
# Tb_list
num_ps = self.ps_catalog.shape[0]
Tb_list = np.zeros((num_ps,))
sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2 # [sr] -> [arcsec^2]
# Iteratively calculate Tb
for i in range(num_ps):
ps_area = self.ps_catalog['Area (sr)'][i] # [sr]
area = ps_area * sr_to_arcsec2
Tb_list[i] = self.calc_single_Tb(area, freq)
return Tb_list
def insertion_pitch(self):
_circ_dv = self.circ_dv()
_t_ap_dv = self.target_apoapsis_speed_dv()
_m = np.rad2deg(self.mean_anomaly())
_burn_time = self.maneuver_burn_time(self.circ_dv())
@jit(nopython=True)
def pitch_calcs_low():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))
@jit(nopython=True)
def pitch_calcs_high():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)
if self.parking_orbit_alt <= 300000: return pitch_calcs_low()
else: return pitch_calcs_high()
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def insertion_pitch(self):
_circ_dv = self.circ_dv()
_t_ap_dv = self.target_apoapsis_speed_dv()
_m = np.rad2deg(self.mean_anomaly())
_burn_time = self.maneuver_burn_time(self.circ_dv())
def pitch_calcs_low():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))
def pitch_calcs_high():
return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)
if self.target_orbit_alt <= 250000:
self.pitchMode = "INS LOW"
return pitch_calcs_low()
else:
self.pitchMode = "INS HIGH"
return pitch_calcs_high()
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + 360, 360))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def magic3(self):
time_end = 5123
real_hofong_fix_pts = pd.read_csv('20161012_HoFong/control_points_coodination.csv').sort(ascending=False)
real_hofong_fix_pts['N'] = real_hofong_fix_pts['N'] - real_hofong_fix_pts['N'][129]
real_hofong_fix_pts['E'] = real_hofong_fix_pts['E'] - real_hofong_fix_pts['E'][129] # last data name=2717, index=129
N_diff = np.diff(real_hofong_fix_pts['N'])
E_diff = np.diff(real_hofong_fix_pts['E'])
hofong_deg = np.rad2deg(np.arctan2(N_diff, E_diff))
hofong_deg = hofong_deg - hofong_deg[0]
hofong_deg_diff = np.cumsum(np.diff(hofong_deg))
interp_hofong = np.interp(np.arange(100), np.arange(hofong_deg_diff.size), hofong_deg_diff)
#plt.plot(hofong_deg, label='hahaxd')
#plt.plot(hofong_deg_diff, label='hehexd')
plt.plot(interp_hofong)
plt.legend()
plt.show()
def segment_angle(line1, line2):
""" Angle between two segments """
vector_a = np.array([line1[0][0]-line1[1][0],
line1[0][1]-line1[1][1]])
vector_b = np.array([line2[0][0]-line2[1][0],
line2[0][1]-line2[1][1]])
# Get dot prod
dot_prod = np.dot(vector_a, vector_b)
# Get magnitudes
magnitude_a = np.dot(vector_a, vector_a)**0.5
magnitude_b = np.dot(vector_b, vector_b)**0.5
# Get angle in radians and then convert to degrees
angle = np.arccos(dot_prod/magnitude_b/magnitude_a)
# Basically doing angle <- angle mod 360
ang_deg = np.rad2deg(angle)%360
if ang_deg-180 >= 0:
# As in if statement
return 360 - ang_deg
else:
return ang_deg
def sphere2basemap(map, azimuthangle_polarangle_radialdistance):
## PT axis should not be givien to this, not same convention!
azimuth = -1* (360 - (450. - np.rad2deg(azimuthangle_polarangle_radialdistance[0]))) # 450-
takeoff = 90. - np.rad2deg(azimuthangle_polarangle_radialdistance[1]) #90. -
#radius = azimuthangle_polarangle_radialdistance[2]
while len(takeoff[takeoff>90.])>0 or len(takeoff[takeoff<-90.])>0 :
azimuth[takeoff <-90.] += 180.
takeoff[takeoff <-90.] = -180 - takeoff[takeoff <-90.]
azimuth[takeoff >90.] += 180.
takeoff[takeoff >90.] = 180 - takeoff[takeoff >90.]
while len(azimuth[azimuth>360.])>0 or len(azimuth[azimuth<0.])>0 :
azimuth[azimuth <0.] += 360.
azimuth[azimuth >360.] -= 360.
return map( azimuth, takeoff )
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 _correct(self, x):
i = self.traj.shape[0] - 1
d_lat = x[1] / earth.R0
d_lon = x[0] / (earth.R0 * np.cos(self.lat_arr[i]))
self.lat_arr[i] -= d_lat
self.lon_arr[i] -= d_lon
phi = x[4:7]
phi[2] += d_lon * np.sin(self.lat_arr[i])
VE_new = self.VE_arr[i] - x[2]
VN_new = self.VN_arr[i] - x[3]
self.VE_arr[i] = VE_new - phi[2] * VN_new
self.VN_arr[i] = VN_new + phi[2] * VE_new
self.Cnb_arr[i] = dcm.from_rv(phi).dot(self.Cnb_arr[i])
h, p, r = dcm.to_hpr(self.Cnb_arr[i])
self.traj.iloc[-1] = [np.rad2deg(self.lat_arr[i]),
np.rad2deg(self.lon_arr[i]),
self.VE_arr[i], self.VN_arr[i], h, p, r]
def __init__(self, filename, filename_info, filetype_info,
prologue, epilogue):
"""Initialize the reader."""
super(HRITGOMSFileHandler, self).__init__(filename, filename_info,
filetype_info,
(goms_hdr_map,
goms_variable_length_headers,
goms_text_headers))
self.prologue = prologue.prologue
self.epilogue = epilogue.epilogue
self.chid = self.mda['spectral_channel_id']
sublon = self.epilogue['GeometricProcessing']['TGeomNormInfo']['SubLon']
sublon = sublon[self.chid]
self.mda['projection_parameters']['SSP_longitude'] = np.rad2deg(sublon)
satellite_id = self.prologue['SatelliteStatus']['SatelliteID']
self.platform_name = SPACECRAFTS[satellite_id]
def _lonlat_from_geos_angle(x, y, geos_area):
"""Get lons and lats from x, y in projection coordinates."""
h = (geos_area.proj_dict['h'] + geos_area.proj_dict['a']) / 1000
b__ = (geos_area.proj_dict['a'] / geos_area.proj_dict['b']) ** 2
sd = np.sqrt((h * np.cos(x) * np.cos(y)) ** 2 -
(np.cos(y)**2 + b__ * np.sin(y)**2) *
(h**2 - (geos_area.proj_dict['a'] / 1000)**2))
#sd = 0
sn = (h * np.cos(x) * np.cos(y) - sd) / (np.cos(y)**2 + b__ * np.sin(y)**2)
s1 = h - sn * np.cos(x) * np.cos(y)
s2 = sn * np.sin(x) * np.cos(y)
s3 = -sn * np.sin(y)
sxy = np.sqrt(s1**2 + s2**2)
lons = np.rad2deg(np.arctan2(s2, s1)) + geos_area.proj_dict.get('lon_0', 0)
lats = np.rad2deg(-np.arctan2(b__ * s3, sxy))
return lons, lats
def xyzToSpherical(x,y,z):
'''
Convert x,y,z to spherical coordinates
@param x: Cartesian coordinate x
@param y: Cartesian coordinate y
@param z: Cartesian coordinate z
@return numpy array of latitude,longitude, and radius
'''
radius = np.sqrt(x**2 + y**2 + z**2)
theta = np.rad2deg(np.arctan2(y,x))
phi = np.rad2deg(np.arccos(z/radius))
# lon = (theta + 180) % 360 - 180
# lon = (theta + 360) % 360
lon = theta
lat = 90 - phi
return np.array([lat,lon,radius]).T
def _calculate_zmat_values(self, construction_table):
c_table = construction_table
if not isinstance(c_table, pd.DataFrame):
if isinstance(c_table, pd.Series):
c_table = pd.DataFrame(c_table).T
else:
c_table = np.array(c_table)
if len(c_table.shape) == 1:
c_table = c_table[None, :]
c_table = pd.DataFrame(
data=c_table[:, 1:], index=c_table[:, 0],
columns=['b', 'a', 'd'])
c_table = c_table.replace(constants.int_label).astype('i8')
c_table.index = c_table.index.astype('i8')
new_index = c_table.index.append(self.index.difference(c_table.index))
X = self.loc[new_index, ['x', 'y', 'z']].values.astype('f8').T
c_table = c_table.replace(dict(zip(new_index, range(len(self)))))
c_table = c_table.values.T
err, C = transformation.get_C(X, c_table)
if err == ERR_CODE_OK:
C[[1, 2], :] = np.rad2deg(C[[1, 2], :])
return C.T
def orientArrow(self):
phi = num.median(self.model.scene.phi)
theta = num.median(self.model.scene.theta)
angle = -num.rad2deg(phi)
theta_f = theta / (num.pi/2)
tipAngle = 30. + theta_f * 20.
tailLen = 15 + theta_f * 15.
self.arrow.setStyle(
angle=angle,
tipAngle=tipAngle,
tailLen=tailLen,
tailWidth=6,
headLen=25)
self.arrow.setRotation(self.arrow.opts['angle'])
def getCornerFeatures(img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
corners = skimage.feature.corner_peaks(skimage.feature.corner_fast(gray, 14), min_distance=1)
orientations = skimage.feature.corner_orientations(gray, corners, octagon(3, 2))
corners = np.rad2deg(orientations)
corners = np.array(corners)
AngleBins = np.arange(0,360,45);
AngleBinsOrientation = np.array([0, 1, 2, 1, 0, 1, 2, 1])
OrientationHist = np.zeros((3,1))
for a in corners:
OrientationHist[AngleBinsOrientation[np.argmin(np.abs(a-AngleBins))]] += 1
if OrientationHist.sum()>0:
OrientationHist = OrientationHist / OrientationHist.sum()
else:
OrientationHist = - 0.01*np.ones((3,1))
F = []
F.extend(OrientationHist[:,0].tolist())
F.append(100.0*float(len(corners)) / ( gray.shape[0] * gray.shape[1] ) )
Fnames = ["Corners-Hor", "Corners-Diag", "Corners-Ver", "Corners-Percent"]
return (F, Fnames)
def __new__(cls, realpart, imagpart=None):
"""Create a new EMArray."""
# Create complex obj
if np.any(imagpart):
obj = np.real(realpart) + 1j*np.real(imagpart)
else:
obj = np.asarray(realpart, dtype=complex)
# Ensure its at least a 1D-Array, view cls
obj = np.atleast_1d(obj).view(cls)
# Store amplitude
obj.amp = np.abs(obj)
# Calculate phase, unwrap it, transform to degrees
obj.pha = np.rad2deg(np.unwrap(np.angle(obj.real + 1j*obj.imag)))
return obj
# 2. Input parameter checks for modelling
# 2.a <Check>s (alphabetically)