GVKun编程网logo

Python numpy 模块-deg2rad() 实例源码(python中numpy模块)

1

如果您对Pythonnumpy模块-deg2rad()实例源码和python中numpy模块感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Pythonnumpy模块-deg2rad()实例源码

如果您对Python numpy 模块-deg2rad() 实例源码python中numpy模块感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Python numpy 模块-deg2rad() 实例源码的各种细节,并对python中numpy模块进行深入的分析,此外还有关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的实用技巧。

本文目录一览:

Python numpy 模块-deg2rad() 实例源码(python中numpy模块)

Python numpy 模块-deg2rad() 实例源码(python中numpy模块)

Python numpy 模块,deg2rad() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.deg2rad()

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

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel(a, order=''C'')

  Return a flattened array

numpy.chararray.flatten(order=''C'')

  Return a copy of the array collapsed into one dimension

numpy.squeeze(a, axis=None)

  Remove single-dimensional entries from the shape of an array.

 

相同点: 将多维数组 降为 一维数组

不同点:

  ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;

  flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;

  squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;

 

ravel()示例:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 
20 print(a)
21 log_type(''a'',a)

 

flatten()示例

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

squeeze()示例:

1. 没有single-dimensional entries的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。

 

2. 有single-dimentional entries 的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10 
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

一、Numpy数组创建

 part 1:np.linspace(起始值,终止值,元素总个数

 

import numpy as np
''''''
numpy中的ndarray数组
''''''

ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)

''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)

# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)

print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)

# 创建二维数组:
print(np.zeros ((3,4)))

print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)

# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim)  # 返回:3(维)

 

结果图:

 

part 2 :np.linspace ( 起始值,终止值,元素总个数)

 

import numpy as np
a = np.arange( 10, 30, 5 )

b = np.arange( 0, 2, 0.3 )

c = np.arange(12).reshape(4,3)

d = np.random.random((2,3))  # 取-1到1之间的随机数,要求设置为诶2行3列的结构

print(a)
print(b)
print(c)
print(d)

print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))

print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))

 

结果图:

 

 

 

 

二、Numpy的ndarray对象属性:

数组的结构:array.shape

数组的维度:array.ndim

元素的类型:array.dtype

数组元素的个数:array.size

数组的索引(下标):array[0]

 

''''''
数组的基本属性
''''''
import numpy as np

print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)     # 打印数组结构
print(len(a))      # 打印有多少行
print(a.ndim)     # 打印维度
print(a.dtype)    # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size)    # 打印数组的总元素个数


print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)

# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, )  # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)

# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3)   # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )

print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])

print("-----------------")


# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
    for j in range(ary.shape[1]):
        for k in range(ary.shape[2]):
            print(ary[i, j, k], end='' '')
            

 

结果图:

 

关于Python numpy 模块-deg2rad() 实例源码python中numpy模块的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性等相关知识的信息别忘了在本站进行查找喔。

本文标签: