def get_pixelist_interp_iq( qp, iq, ring_mask, center):
qind, pixelist = roi.extract_label_indices( ring_mask )
#pixely = pixelist%FD.md['nrows'] -center[1]
#pixelx = pixelist//FD.md['nrows'] - center[0]
pixely = pixelist%ring_mask.shape[1] -center[1]
pixelx = pixelist//ring_mask.shape[1] - center[0]
r= np.hypot(pixelx, pixely) #leave as float.
#r= np.int_( np.hypot(pixelx, pixely) +0.5 ) + 0.5
return np.interp( r, qp, iq )
python类hypot()的实例源码
def transform(cls, value):
value = np.asarray(value, dtype=np.float64)
assert value.shape[-1] == 2
result = np.empty_like(value)
result[...,0] = np.hypot(value[...,1], value[...,0])
result[...,1] = np.arctan2(value[...,1], value[...,0]) % (2 * np.pi)
return result
def transform(cls, value):
value = np.asarray(value, dtype=np.float64)
result = np.empty_like(value)
x, y, z = value.T
xy = np.hypot(x, y)
result[..., 0] = np.hypot(xy, z)
result[..., 1] = np.arctan2(xy, z) % (2 * np.pi)
result[..., 2] = np.arctan2(y, x) % (2 * np.pi)
return result
def transform(cls, value):
value = np.asarray(value, dtype=np.float64)
result = np.empty_like(value)
x, y, z = value.T
result[..., 0] = np.hypot(x, y) # tho
result[..., 1] = np.arctan2(y, x) % (2 * np.pi) # phi
result[..., 2] = z
return result
def ecef2geodetic(x, y, z):
"""http://www.astro.uni.torun.pl/~kb/Papers/geod/Geod-BG.htm
This algorithm provides a converging solution to the latitude equation in
terms of the parametric or reduced latitude form (v).
This algorithm provides a uniform solution over all latitudes as it does
not involve division by cos(phi) or sin(phi).
"""
ell = {}
ell['a'] = 6378137.
ell['f'] = 1. / 298.2572235630
ell['b'] = ell['a'] * (1 - ell['f'])
ea = ell['a']
eb = ell['b']
rad = np.hypot(x, y)
# Constant required for Latitude equation
rho = np.arctan2(eb * z, ea * rad)
#Constant required for latitude equation
c = (ea**2 - eb**2) / np.hypot(ea * rad, eb * z)
# Starter for the Newtons Iteration Method
vnew = np.arctan2(ea * z, eb * rad)
# Initializing the parametric latitude
v = 0
count = 0
while (v != vnew).any() and count < 5:
v = vnew.copy()
# Newtons Method for computing iterations
vnew = v - ((2 * np.sin(v - rho) - c * np.sin(2 * v)) /
(2 * (np.cos(v - rho) - c * np.cos(2 * v))))
count += 1
# Computing latitude from the root of the latitude equation
lat = np.arctan2(ea * np.tan(vnew), eb)
lon = np.arctan2(y, x)
alt = ((rad - ea * np.cos(vnew)) * np.cos(lat) +
(z - eb * np.sin(vnew)) * np.sin(lat))
return lat, lon, alt
def _cart2polar(x, y, center):
xx = x - center[0]
yy = y - center[1]
phi = np.arctan2(yy, xx)
r = np.hypot(xx, yy)
return r, phi
def _grid(self):
tsne_norm = self.tsne_vectors[:, ] / float(self.ratio)
used_imgs = np.equal(self.tsne_vectors[:, 0], None)
image = np.ones((self.output_img_size, self.output_img_size, 3)) * self.background_color
for x in tqdm(range(self.ratio)):
x0 = x * self.each_img_size
x05 = (x + 0.5) * self.each_img_size
for y in range(self.ratio):
y0 = y * self.each_img_size
y05 = (y + 0.5) * self.each_img_size
tmp_tsne = tsne_norm - [x05, y05]
tmp_tsne[used_imgs] = 99999 # don't use the same img twice
tsne_dist = np.hypot(tmp_tsne[:, 0], tmp_tsne[:, 1])
min_index = np.argmin(tsne_dist)
used_imgs[min_index] = True
img_path = self.image_list[min_index]
small_img, x1, y1, dx, dy = get_image(img_path, self.each_img_size)
if small_img is None:
y -= 1
continue
if x < 1 and all(side < self.each_img_size for side in [x1, y1]):
self.each_img_size = min(x1, y1)
dx = int(ceil(x1 / 2))
dy = int(ceil(y1 / 2))
image[x0 + dx:x0 + dx + x1, y0 + dy:y0 + dy + y1] = small_img
return image
def on_button(self, event):
# only consider events from the lines Axes
if event.inaxes is not self.ln.axes:
return
# if not the left mouse button or a modifier key
# is held down, bail
if event.button != 1 or event.key not in (None, 'shift'):
print('key+button: {!r}+{!r}'.format(event.key, event.button))
return
if event.key == 'shift':
# compute the distance to each point *in data space*
d = np.hypot(np.asarray(self.xdata) - event.xdata,
np.asarray(self.ydata) - event.ydata)
# find the closest point
ix = np.argmin(d)
# remove that data point
del self.xdata[ix]
del self.ydata[ix]
else:
# get the event location in data-space
# and add to internal data list
self.xdata.append(event.xdata)
self.ydata.append(event.ydata)
# update the line
self._update_line()
def point_distance(p1, p2):
dist_diff = p1 - p2
return np.hypot(*dist_diff)
def collide_line_ball(line, ball):
displacement_to_second_point = line.line[1] - line.line[0]
normalised_point_diff_vector = displacement_to_second_point / \
np.hypot(*(displacement_to_second_point))
perpendicular_vector = np.array(
[-normalised_point_diff_vector[1], normalised_point_diff_vector[0]])
ball.velocity -= 2 * np.dot(perpendicular_vector,
ball.velocity) * perpendicular_vector
def __init__(self, line):
self.line = np.array(line)
self.middle = (self.line[0] + self.line[1]) / 2
self.size = np.round(np.abs(self.line[0] - self.line[1]))
self.length = np.hypot(*self.size)
if np.count_nonzero(self.size) != 2:
# line is perpendicular to y or x axis
if self.size[0] == 0:
self.size[0] += 1
else:
self.size[1] += 1
# draws the yellow part of the table
def ball_hit(self):
new_velocity = -(self.displacement - config.ball_radius - config.cue_safe_displacement) * \
config.cue_hit_power * np.array([math.sin(self.angle), math.cos(self.angle)])
change_in_disp = np.hypot(*new_velocity) * 0.1
while self.displacement - change_in_disp > config.ball_radius:
self.displacement -= change_in_disp
self.update()
pygame.display.flip()
self.target_ball.ball.apply_force(new_velocity)
self.displacement = config.ball_radius
self.visible = False
def update(self, *args):
if np.hypot(*self.ball.velocity) != 0:
# updates label circle and number offset
perpendicular_velocity = -np.cross(self.ball.velocity, [0, 0, 1])
# angle formula is angle=((ballspeed*2)/(pi*r*2))*2
rotation_angle = -np.hypot(
*(self.ball.velocity)) * 2 / (config.ball_radius * np.pi)
transformation_matrix = physics.rotation_matrix(
perpendicular_velocity, rotation_angle)
self.label_offset = np.matmul(
self.label_offset, transformation_matrix)
if self.ball_type == BallType.Striped:
self.ball_stripe.update_stripe(transformation_matrix)
self.update_sprite()
self.ball.update()
def check_reg(fixed_img, moved_img, scale=15, norm=True, sigma=0.8, **kwargs):
dim = list(moved_img.shape)
resol = list(moved_img.header['pixdim'][1:4])
# Convert 4D image to 3D or raise error
data = convert_to_3d(moved_img)
# Check normalization
if norm:
data = apply_p2_98(data)
# Set slice axis for mosaic grid
slice_axis, cmap = check_sliceaxis_cmap(data, kwargs)
cmap = 'YlOrRd'
# Set grid shape
data, slice_grid, size = set_mosaic_fig(data, dim, resol, slice_axis, scale)
fig, axes = BrainPlot.mosaic(fixed_img, scale=scale, norm=norm, cmap='bone', **kwargs)
# Applying inversion
invert = check_invert(kwargs)
data = apply_invert(data, *invert)
# Plot image
for i in range(slice_grid[1] * slice_grid[2]):
ax = axes.flat[i]
edge = data[:, :, i]
edge = feature.canny(edge, sigma=sigma) # edge detection for second image
# edge = ndimage.gaussian_filter(edge, 3)
mask = np.ones(edge.shape)
sx = ndimage.sobel(edge, axis=0, mode='constant')
sy = ndimage.sobel(edge, axis=1, mode='constant')
sob = np.hypot(sx, sy)
mask[sob == False] = np.nan
m_norm = colors.Normalize(vmin=0, vmax=1.5)
if i < slice_grid[0] and False in np.isnan(mask.flatten()):
ax.imshow(mask.T, origin='lower', interpolation='nearest', cmap=cmap, norm=m_norm, alpha=0.8)
else:
ax.imshow(np.zeros((dim[0], dim[1])).T, origin='lower', interpolation='nearest', cmap='bone')
ax.set_axis_off()
fig.set_facecolor('black')
if notebook_env:
display(fig)
return fig, axes
def distance(vertex1, vertex2):
x, y = vertex1 - vertex2
return np.hypot(x, y)
def angsep(lon1,lat1,lon2,lat2):
"""
Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alternatives, but is stable at at all distances, including the
poles and antipodes.
[1] http://en.wikipedia.org/wiki/Great-circle_distance
"""
lon1,lat1 = numpy.radians([lon1,lat1])
lon2,lat2 = numpy.radians([lon2,lat2])
sdlon = numpy.sin(lon2 - lon1)
cdlon = numpy.cos(lon2 - lon1)
slat1 = numpy.sin(lat1)
slat2 = numpy.sin(lat2)
clat1 = numpy.cos(lat1)
clat2 = numpy.cos(lat2)
num1 = clat2 * sdlon
num2 = clat1 * slat2 - slat1 * clat2 * cdlon
denominator = slat1 * slat2 + clat1 * clat2 * cdlon
return numpy.degrees(numpy.arctan2(numpy.hypot(num1,num2), denominator))
############################################################
# ADW: Reduce numpy array operations for speed
def generate_pattern(self, reference, size):
"""Extracts a pattern from the reference image.
Firstly, the image is transformed to grayscale. A random square from image
is picked. A pattern is extracted using the edge detection (Sobel's filter).
:param reference: Reference image.
:param int size: Size of a pattern (length of its edge).
:returns:
A pattern extracted from the image.
"""
# Import image from reference and convert it to grayscale.
img = mpimg.imread(reference)
gray = np.mean(img, -1)
# Normalization of data to decimal (0.0 - 1.0) representation
if gray.max() > 1.0:
gray /= 255.0
# Extract a random slice with the pixel size given as parameter
slice_center_x = random.randint(0, len(img[0]) - size - 1)
slice_center_y = random.randint(0, len(img) - size - 1)
slice = gray[slice_center_y: slice_center_y + size, slice_center_x: slice_center_x + size]
# # Detects border to generate the pattern of the brush
dx = ndimage.sobel(slice, 0) # horizontal derivative
dy = ndimage.sobel(slice, 1) # vertical derivative
pattern = np.hypot(dx, dy) # grayscale slice with border detection
# Normalize pattern
if pattern.max() > 1.0:
return pattern / pattern.max()
return pattern
# Test
def _deproj(x, y, inc, pa, polar_out=True, polar_in=True, fourier_plan=False):
if polar_in:
y, x = x*np.cos(y), x*np.sin(y)
else:
y, x = x, y
if fourier_plan:
X = (x*np.cos(pa) + y*np.sin(pa))*np.cos(inc)
Y = y*np.cos(pa) - x*np.sin(pa)
else:
X = x*np.cos(pa) + y*np.sin(pa)
Y = (y*np.cos(pa) - x*np.sin(pa))/np.cos(inc)
x, y = np.hypot(Y, X), (np.arctan2(X, Y)-pa) % (2*np.pi)
if not polar_out:
return x*np.cos(y), x*np.sin(y)
return x, y
def psf(lOverd, masperpx):
"""
lOverd in radian
masperpx in mas per px
"""
nbpts = (lOverd*4/(masperpx*MAS2RAD))//2*2+1
y, x = np.meshgrid(np.linspace(-1, 1, nbpts), np.linspace(-1, 1, nbpts))
psf = airy(np.hypot(y, x)*2*lOverd+1e-10, 1/lOverd)**2
psf /= psf.sum()
return psf
def distance_matrix(x0, y0, x1, y1):
'''Distance matrix for IDW calculation'''
obs = np.vstack((x0, y0)).T
interp = np.vstack((x1, y1)).T
# Make a distance matrix between pairwise observations
# Note: from <http://stackoverflow.com/questions/1871536>
d0 = np.subtract.outer(obs[:,0], interp[:,0])
d1 = np.subtract.outer(obs[:,1], interp[:,1])
return np.hypot(d0, d1)