GVKun编程网logo

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

1

想了解Pythonnumpy模块-rot90()实例源码的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于python中numpy模块的相关问题,此外,我们还将为您介绍关于Jupyter中的N

想了解Python numpy 模块-rot90() 实例源码的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于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 模块-rot90() 实例源码(python中numpy模块)

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

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

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

项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def inner_extract(self,B,signature):
  2. w,h =B.shape[:2]
  3.  
  4. LL,(HL,LH,HH) = pywt.dwt2(B[:32*(w//32),:32*(h//32)],''haar'')
  5. LL_1,(HL_1,LH_1,HH_1) = pywt.dwt2(LL,''haar'')
  6. LL_2,(HL_2,LH_2,HH_2) = pywt.dwt2(LL_1,''haar'')
  7. LL_3,(HL_3,LH_3,HH_3) = pywt.dwt2(LL_2,''haar'')
  8. LL_4,(HL_4,LH_4,HH_4) = pywt.dwt2(LL_3,''haar'')
  9.  
  10. _,_,ori_sig = self._gene_embed_space(HH_3)
  11.  
  12. ext_sigs=[]
  13. ext_sigs.extend(self._extract_sig(ori_sig,len(signature)))
  14. ext_sigs.extend(self._extract_sig(np.rot90(ori_sig,1),2),3),len(signature)))
  15.  
  16. return ext_sigs
项目:semantic-segmentation    作者:albertbuchard    | 项目源码 | 文件源码
  1. def mk_rotations(img):
  2. #
  3. # DESCRIPTION
  4. # This function create 8 roatation image fro an input image 4 rotation from the raw image and 4 rotation form the transposed
  5. #
  6. # INPUTS
  7. # img np.array
  8. #
  9. # OUTPUTS
  10. # rotated_image_img,img90,img180,img270,imgT,imgT90,imgT180,imgT270
  11. #
  12. #
  13. img90 = np.rot90(img)
  14. img180 = np.rot90(img,k=2)
  15. img270 = np.rot90(img,k=3)
  16. imgT = np.zeros(img.shape)
  17. if np.size(img.shape)>2:
  18. for i in range(3):
  19. imgT[:,:,i] =img[:,i].T
  20. else:
  21. imgT = img.T
  22. imgT90 = np.rot90(imgT)
  23. imgT180 = np.rot90(imgT, k=2)
  24. imgT270 = np.rot90(imgT, k=3)
  25. return img, img90, img180, img270, imgT, imgT90, imgT180,imgT270
项目:semantic-segmentation    作者:albertbuchard    | 项目源码 | 文件源码
  1. def unrotate(rot0, rot1, rot2, rot3, rot4, rot5, rot6, rot7):
  2. #
  3. # DESCRIPTION
  4. # Functions that merges the 8 mapped images as described in the beginning of the file back to the original format
  5. # Uses element wise product
  6. #
  7. #
  8. unrot = np.copy(rot0)
  9. unrot*=np.rot90((rot1),k=3)
  10. unrot*=np.rot90((rot2),k=2)
  11. unrot*=np.rot90((rot3),k=1)
  12.  
  13. unrot*=(rot4.T)
  14. unrot*=np.rot90((rot5),k=3).T
  15. unrot*=np.rot90((rot6),k=2).T
  16. unrot*=np.rot90((rot7),k=1).T
  17.  
  18. return unrot
  19.  
  20. ## ##
  21. ## ##
  22. ## EXECUTION ##
  23. ## ##
  24. ## ##
项目:semantic-segmentation    作者:albertbuchard    | 项目源码 | 文件源码
  1. def mk_rotations(img):
  2. ##INPUT:
  3. ## img: a 3D RGB array
  4. ##OUTPUT
  5. ## 8 rotated and transposed versions of img
  6.  
  7. img90 = np.rot90(img)
  8. img180 = np.rot90(img,imgT270
  9.  
  10. ## Formats an image to save format
项目:BirdCLEF2017    作者:kahst    | 项目源码 | 文件源码
  1. def getMagSpec(sig, rate, winlen, winstep, nfft):
  2.  
  3. #get frames
  4. winfunc = lambda x:np.ones((x,))
  5. frames = psf.sigproc.framesig(sig, winlen*rate, winstep*rate, winfunc)
  6.  
  7. #Magnitude Spectrogram
  8. magspec = np.rot90(psf.sigproc.magspec(frames, nfft))
  9.  
  10. return magspec
  11.  
  12. #Split signal into five-second chunks with overlap of 4 and minimum length of 3 seconds
  13. #Use these settings for other chunk lengths:
  14. #winlen,winstep,seconds
  15. #0.05,0.0097,5s
  16. #0.05,0.0195,10s
  17. #0.05,0.0585,30s
项目:BirdCLEF2017    作者:kahst    | 项目源码 | 文件源码
  1. def getMagSpec(sig, nfft))
  2.  
  3. return magspec
  4.  
  5. #Split signal into five-second chunks with overlap of 4 and minimum length of 1 second
  6. #Use these settings for other chunk lengths:
  7. #winlen,30s
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
  1. def test_discrete_phantom_uniform():
  2. """The uniform discrete phantom is the same after rotating 90 degrees."""
  3.  
  4. d0 = discrete_phantom(p, 100, ratio=10, prop=''mass_atten'')
  5.  
  6. p.rotate(theta=np.pi/2, point=Point([0.5, 0.5]))
  7. d1 = np.rot90(discrete_phantom(p, prop=''mass_atten''))
  8.  
  9. # plot rotated phantom
  10. plot_phantom(p)
  11.  
  12. # plot the error
  13. plt.figure()
  14. plt.imshow(d1-d0, interpolation=None)
  15. plt.colorbar()
  16.  
  17. # plt.show(block=True)
  18. # assert_allclose(d0,d1)
项目:sealionengine    作者:gecrooks    | 项目源码 | 文件源码
  1. def load_dotted_image(self, train_id, scale=1, border=0, circled=False):
  2. img = self._load_image(''dotted'', scale, border)
  3.  
  4. if train_id in self.extra_masks:
  5. for row, col, radius in self.extra_masks[train_id]:
  6. rr, cc = skimage.draw.circle(row, radius, shape = img.shape)
  7. img = np.copy(img)
  8. img[rr, cc] = (0, 0, 0)
  9.  
  10. # When dotted image is rotated relative to train,apply hot patch. (kudos: @authman)
  11. if train_id in self.dotted_rotate:
  12. rot = self.dotted_rotate[train_id]
  13. img = np.rot90(img, rot)
  14.  
  15. if circled:
  16. assert scale == 1
  17. assert border == 0
  18. img = np.copy(img)
  19. img = self.draw_circles(np.copy(img), self.tid_coords[train_id])
  20.  
  21. return img
项目:pytrip    作者:pytrip    | 项目源码 | 文件源码
  1. def get_lateral(self, resolution=0.5):
  2. if hasattr(self, "lateral") and resolution == resolution:
  3. return self.lateral
  4. max_dist = self.get_max_dist()
  5. dim = np.ceil(np.absolute(max_dist / resolution))
  6. max_dist = dim * resolution
  7. self.resolution = resolution
  8. a = np.meshgrid(np.linspace(0, max_dist, dim), np.linspace(0, dim))
  9. r = (a[0]**2 + a[1]**2)**0.5
  10. sigma = self.sigma / ((8 * log(2))**0.5)
  11. lateral = 1 / ((2 * pi * sigma**2)**0.5) * np.exp(-(r**2) / (2 * sigma**2))
  12. tot_lat = np.zeros((2 * dim - 1, 2 * dim - 1))
  13.  
  14. tot_lat[dim - 1:2 * dim - 1, dim - 1:2 * dim - 1] = lateral
  15. tot_lat[dim - 1:2 * dim - 1, 0:dim - 1] = np.rot90(lateral, 3)[:, 0:dim - 1]
  16. tot_lat[0:dim - 1, 2)[0:dim - 1, dim - 1:2 * dim - 1] = np.rot90(lateral)[0:dim - 1, :]
  17.  
  18. self.lateral = tot_lat
  19. return self.lateral
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
  1. def _apply_transformations(plot_config, data_slice):
  2. """Rotate,flip and zoom the data slice.
  3.  
  4. Depending on the plot configuration,this will apply some transformations to the given data slice.
  5.  
  6. Args:
  7. plot_config (mdt.visualization.maps.base.MapPlotConfig): the plot configuration
  8. data_slice (ndarray): the 2d slice of data to transform
  9.  
  10. Returns:
  11. ndarray: the transformed 2d slice of data
  12. """
  13. if plot_config.rotate:
  14. data_slice = np.rot90(data_slice, plot_config.rotate // 90)
  15.  
  16. if not plot_config.flipud:
  17. # by default we flipud to correct for matplotlib lower origin. If the user
  18. # sets flipud,we do not need to to it
  19. data_slice = np.flipud(data_slice)
  20.  
  21. data_slice = plot_config.zoom.apply(data_slice)
  22. return data_slice
项目:pytorch_fnet    作者:AllenCellModeling    | 项目源码 | 文件源码
  1. def _augment_chunks(self, chunks):
  2. if self.choices_augmentation is None:
  3. return chunks
  4. chunks_new = []
  5. choice = np.random.choice(self.choices_augmentation)
  6. for chunk in chunks:
  7. chunk_new = chunk
  8. if choice in [1, 3, 5, 7]:
  9. chunk_new = np.flip(chunk_new, axis=1)
  10. if choice in [2, 3]:
  11. chunk_new = np.rot90(chunk_new, 1, axes=(1, 2))
  12. elif choice in [4, 5]:
  13. chunk_new = np.rot90(chunk_new, 2, 2))
  14. elif choice in [6, 7]:
  15. chunk_new = np.rot90(chunk_new, 2))
  16. chunks_new.append(chunk_new)
  17. return chunks_new
项目:kaggle_CERVICAL_CANCER_2017    作者:ZFTurbo    | 项目源码 | 文件源码
  1. def random_augment_image(image, row):
  2. # start0_max,end0_max,start1_max,end1_max = get_bounding_Boxes_positions(image,row)
  3. # image = cv2.rectangle(image,(int(start1_max),int(start0_max)),(int(end1_max),int(end0_max)),(0,255),thickness=5)
  4. if random.randint(0, 1) == 0:
  5. image = return_random_crop(image, row)
  6. else:
  7. image = return_random_perspective(image, row)
  8. image = random_rotate(image)
  9.  
  10. # all possible mirroring and flips (in total there are only 8 possible configurations)
  11. mirror = random.randint(0, 1)
  12. if mirror != 0:
  13. image = image[::-1, :, :]
  14. angle = random.randint(0, 3)
  15. if angle != 0:
  16. image = np.rot90(image, k=angle)
  17.  
  18. image = lightning_change(image)
  19. image = blur_image(image)
  20.  
  21. return image
项目:solving-minesweeper-by-tensorflow    作者:staytime    | 项目源码 | 文件源码
  1. def rot(self):
  2. for i in range(len(self.Q)):
  3. Q = self.Q[i]
  4. ans = self.ans[i]
  5. refarea = self.area[i]
  6. refMask = self.mask[i]
  7.  
  8. for rotate in range(3):
  9. self.Q.append(Q)
  10. self.ans.append(ans)
  11.  
  12. refarea = np.rot90(refarea)
  13. refMask = np.rot90(refMask)
  14.  
  15. self.area.append(refarea)
  16. self.mask.append(refMask)
  17.  
  18. return self
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
  1. def rot90(img):
  2. ''''''
  3. rotate one or multiple grayscale or color images 90 degrees
  4. ''''''
  5. s = img.shape
  6. if len(s) == 3:
  7. if s[2] in (3, 4): # color image
  8. out = np.empty((s[1], s[0], s[2]), dtype=img.dtype)
  9. for i in range(s[2]):
  10. out[:, i] = np.rot90(img[:, i])
  11. else: # mutliple grayscale
  12. out = np.empty((s[0], s[2], s[1]), dtype=img.dtype)
  13. for i in range(s[0]):
  14. out[i] = np.rot90(img[i])
  15. elif len(s) == 2: # one grayscale
  16. out = np.rot90(img)
  17. elif len(s) == 4 and s[3] in (3, 4): # multiple color
  18. out = np.empty((s[0], s[1], s[3]), dtype=img.dtype)
  19. for i in range(s[0]): # for each img
  20. for j in range(s[3]): # for each channel
  21. out[i, j] = np.rot90(img[i, j])
  22. else:
  23. NotImplemented
  24. return out
项目:NBAapi    作者:eyalshafran    | 项目源码 | 文件源码
  1. def shot_heatmap(df,sigma = 1,log=False,player_pic=True,ax=None,cmap=''jet''):
  2. ''''''
  3. This function plots a heatmap based on the shot chart.
  4. input - dataframe with x and y coordinates.
  5. optional - log (default false) plots heatmap in log scale.
  6. player (default true) adds player''s picture and name if true
  7. sigma - the sigma of the Gaussian kernel. In feet (default=1)
  8. ''''''
  9. n,_ = np.histogram2d( 0.1*df[''LOC_X''].values, 0.1*df[''LOC_Y''].values,bins = [500, 500],range = [[-25,25],[-5.25,44.75]])
  10. KDE = ndimage.filters.gaussian_filter(n,10.0*sigma)
  11. N = 1.0*KDE/np.sum(KDE)
  12. if ax is None:
  13. ax = plt.gca(xlim = [30,-30],ylim = [-7,43],xticks=[],yticks=[],aspect=1.0)
  14. court(ax,outer_lines=True,color=''black'',lw=2.0,direction=''down'')
  15. ax.axis(''off'')
  16. if log:
  17. ax.imshow(np.rot90(np.log10(N+1)),cmap=cmap,extent=[25.0, -25.0, -5.25, 44.75])
  18. else:
  19. ax.imshow(np.rot90(N), 44.75])
  20. if player_pic:
  21. player_id = df.PLAYER_ID.values[0]
  22. pic = players_picture(player_id)
  23. ax.imshow(pic,extent=[15,25,30,37.8261])
  24. ax.text(0,-7,''By: Doingthedishes'',color=''white'',horizontalalignment=''center'',fontsize=20,fontweight=''bold'')
项目:pershing    作者:qmn    | 项目源码 | 文件源码
  1. def rot90(self, turns=1):
  2. """
  3. Rotates the blocks in the counter-clockwise direction. (As numpy
  4. does it.)
  5. """
  6. # Rotate the individual Y-layer matrices
  7. new_blocks = np.array([np.rot90(by, turns) for by in self.blocks])
  8. new_data = np.array([np.rot90(dy, turns) for dy in self.data])
  9. new_mask = np.array([np.rot90(my, turns) for my in self.mask])
  10.  
  11. # Rotate the data (if applicable)
  12. for y in xrange(new_data.shape[0]):
  13. for z in xrange(new_data.shape[1]):
  14. for x in xrange(new_data.shape[2]):
  15. b = new_blocks[y, z, x]
  16. d = new_data[y, x]
  17. new_data[y, x] = self.data_rot90(b, d, turns)
  18.  
  19. return MaskedSubChunk(new_blocks, new_data, new_mask)
项目:pershing    作者:qmn    | 项目源码 | 文件源码
  1. def data_rot90(self, block, data, turns):
  2. """
  3. Specially rotate this block,which has an orientation that depends on
  4. the data value.
  5. """
  6. blockname = blocks.block_names[block]
  7.  
  8. # Torches (redstone and normal)
  9. torches = ["redstone_torch", "unlit_redstone_torch", "torch"]
  10. if blockname in torches:
  11. return blocks.Torch.rot90(data, turns)
  12.  
  13. # Repeaters
  14. repeaters = ["unpowered_repeater", "powered_repeater"]
  15. if blockname in repeaters:
  16. return blocks.Repeater.rot90(data, turns)
  17.  
  18. # Comparators
  19. comparators = ["unpowered_comparator", "powered_comparator"]
  20. if blockname in comparators:
  21. return blocks.Comparator.rot90(data, turns)
  22.  
  23. return data
项目:bates_galaxies_lab    作者:aleksds    | 项目源码 | 文件源码
  1. def _display_pixels(x, y, counts, pixelsize):
  2. """
  3. display pixels at coordinates (x,y) coloured with "counts".
  4. This routine is fast but not fully general as it assumes the spaxels
  5. are on a regular grid. This needs not be the case for Voronoi binning.
  6.  
  7. """
  8. xmin, xmax = np.min(x), np.max(x)
  9. ymin, ymax = np.min(y), np.max(y)
  10. nx = int(round((xmax - xmin)/pixelsize) + 1)
  11. ny = int(round((ymax - ymin)/pixelsize) + 1)
  12. img = np.full((nx, ny), np.nan) # use nan for missing data
  13. j = np.round((x - xmin)/pixelsize).astype(int)
  14. k = np.round((y - ymin)/pixelsize).astype(int)
  15. img[j, k] = counts
  16.  
  17. plt.imshow(np.rot90(img), interpolation=''nearest'', cmap=''prism'',
  18. extent=[xmin - pixelsize/2, xmax + pixelsize/2,
  19. ymin - pixelsize/2, ymax + pixelsize/2])
  20.  
  21. #----------------------------------------------------------------------
项目:sg-mcmc-survey    作者:delta2323    | 项目源码 | 文件源码
  1. def visualize2D(fig, ax, xs, ys, bins=200,
  2. xlabel=''x'', ylabel=''y'',
  3. xlim=None, ylim=None):
  4. H, xedges, yedges = numpy.histogram2d(xs, bins)
  5. H = numpy.rot90(H)
  6. H = numpy.flipud(H)
  7. Hmasked = numpy.ma.masked_where(H == 0, H)
  8.  
  9. ax.pcolormesh(xedges, yedges, Hmasked)
  10.  
  11. ax.set_xlabel(xlabel)
  12. ax.set_ylabel(ylabel)
  13.  
  14. if xlim is None:
  15. xlim = (min(xs), max(xs))
  16. if ylim is None:
  17. ylim = (min(ys), max(ys))
  18. ax.set_xlim(*xlim)
  19. ax.set_ylim(*ylim)
  20. fig.colorbar(pyplot.contourf(Hmasked))
项目:hamaa    作者:monitor1379    | 项目源码 | 文件源码
  1. def rot180(images):
  2. """
  3. ????180??
  4. ??HW/CHW/NCHW?????images?
  5. """
  6. out = np.empty(shape=images.shape, dtype=images.dtype)
  7. if images.ndim == 2:
  8. out = np.rot90(images, k=2)
  9. elif images.ndim == 3:
  10. for c in xrange(images.shape[0]):
  11. out[c] = np.rot90(images[c], k=2)
  12. elif images.ndim == 4:
  13. for n in xrange(images.shape[0]):
  14. for c in xrange(images.shape[1]):
  15. out[n][c] = np.rot90(images[n][c], k=2)
  16. else:
  17. raise Exception(''Invalid ndim: '' + str(images.ndim) +
  18. '',only support ndim between 2 and 4.'')
  19. return out
  20.  
  21.  
  22. # ????f????x???f???df???x???
项目:computer-vision-algorithms    作者:aleju    | 项目源码 | 文件源码
  1. def grad_magnitude(img):
  2. """Calculate the gradient magnitude of an image.
  3. Args:
  4. img The image
  5. Returns:
  6. gradient image"""
  7. img = img / 255.0
  8. sobel_y = np.array([
  9. [-1, -2, -1],
  10. [0, 0],
  11. [1, 1]
  12. ])
  13. sobel_x = np.rot90(sobel_y) # rotates counter-clockwise
  14.  
  15. # apply x/y sobel filter to get x/y gradients
  16. imgx = signal.correlate(img, sobel_x, mode="same")
  17. imgy = signal.correlate(img, sobel_y, mode="same")
  18. imgmag = np.sqrt(imgx**2 + imgy**2)
  19.  
  20. return imgmag
项目:computer-vision-algorithms    作者:aleju    | 项目源码 | 文件源码
  1. def main():
  2. """Load image,apply filter,plot."""
  3. img = data.camera()
  4.  
  5. # just like sobel,but no -2/+2 in the middle
  6. prewitt_y = np.array([
  7. [-1, -1, 1]
  8. ])
  9. prewitt_x = np.rot90(prewitt_y) # rotates counter-clockwise
  10.  
  11. img_sx = signal.correlate(img, prewitt_x, mode="same")
  12. img_sy = signal.correlate(img, prewitt_y, mode="same")
  13. g_magnitude = np.sqrt(img_sx**2 + img_sy**2)
  14.  
  15. ground_truth = skifilters.prewitt(data.camera())
  16.  
  17. util.plot_images_grayscale(
  18. [img, img_sx, img_sy, g_magnitude, ground_truth],
  19. ["Image", "Prewitt (x)", "Prewitt (y)", "Prewitt (both/magnitude)",
  20. "Prewitt (Ground Truth)"]
  21. )
项目:camelyon-segmentation    作者:erenhalici    | 项目源码 | 文件源码
  1. def augment_image(self, image, i):
  2. if i == 0:
  3. return np.rot90(image)
  4. elif i == 1:
  5. return np.rot90(image,2)
  6. elif i == 2:
  7. return np.rot90(image,3)
  8. elif i == 3:
  9. return image
  10. elif i == 4:
  11. return np.fliplr(image)
  12. elif i == 5:
  13. return np.flipud(image)
  14. elif i == 6:
  15. return image.transpose(1,0,2)
  16. elif i == 7:
  17. return np.fliplr(np.rot90(image))
项目:camelyon-segmentation    作者:erenhalici    | 项目源码 | 文件源码
  1. def augment_image(self,2)
  2. elif i == 7:
  3. return np.fliplr(np.rot90(image))
项目:empymod    作者:empymod    | 项目源码 | 文件源码
  1. def test_get_geo_fact():
  2. res = np.array([0.017051023225738, 0.020779123804907, -0.11077204227395,
  3. -0.081155809427821, -0.098900024313067, 0.527229048585517,
  4. -0.124497144079623, -0.151717673241039, 0.808796206796408])
  5. res2 = np.rot90(np.fliplr(res.reshape(3, -1))).ravel()
  6.  
  7. # EE,MM
  8. ab = [11, 12, 13, 21, 22, 23, 31, 32, 33]
  9. i = 0
  10. for i in range(9):
  11. out = utils.get_geo_fact(ab[i], 13.45, 23.8, 124.3, 5.3, False, False)
  12. assert_allclose(out[0], res[i])
  13. out = utils.get_geo_fact(ab[i], True, True)
  14. assert_allclose(out[0], res[i])
  15. i += 1
  16.  
  17. # ME,EM
  18. ab = [14, 15, 16, 24, 25, 26, 34, 35, 36]
  19. i = 0
  20. for i in range(9):
  21. out = utils.get_geo_fact(ab[i], res2[i])
  22. out = utils.get_geo_fact(ab[i], res[i])
  23. i += 1
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
  1. def rotate_examples(X, files, extent, k=3):
  2. m,n = np.shape(X)
  3. augmentedX = np.ones(((k+1)*m,n))
  4. augmentedy = np.squeeze(np.ones(((k+1)*m,)))
  5. augmented_files = []
  6. for i in range(m):
  7. #print y[i]
  8. print((k+1)*i)
  9. augmentedX[(k+1)*i,:] *= X[i,:]
  10. augmentedy[(k+1)*i] *= y[i]
  11. #print augmentedy[(k+1)*i]
  12. augmented_files.append(files[i])
  13. for j in range(1,k+1):
  14. print(((k+1)*i)+j)
  15. rotatedX = np.rot90(np.reshape(X[i,:], (2*extent,2*extent), order="F"), j)
  16. augmentedX[((k+1)*i)+j,:] *= np.ravel(rotatedX, order="F")
  17. augmentedy[((k+1)*i)+j] *= y[i]
  18. augmented_files.append(files[i])
  19. #print augmentedX[:16,:2]
  20. #print np.shape(augmentedX)
  21. #print len(augmented_files)
  22. return augmentedX, augmentedy, augmented_files
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
  1. def rotate_examples(X,)))
  2. augmented_files = []
  3. for i in range(m):
  4. #print y[i]
  5. print (k+1)*i
  6. augmentedX[(k+1)*i,k+1):
  7. print ((k+1)*i)+j
  8. rotatedX = np.rot90(np.reshape(X[i, augmented_files
项目:niworkflows    作者:poldracklab    | 项目源码 | 文件源码
  1. def transform_to_2d(data, max_axis):
  2. """
  3. Projects 3d data cube along one axis using maximum intensity with
  4. preservation of the signs. Adapted from nilearn.
  5. """
  6. import numpy as np
  7. # get the shape of the array we are projecting to
  8. new_shape = list(data.shape)
  9. del new_shape[max_axis]
  10.  
  11. # generate a 3D indexing array that points to max abs value in the
  12. # current projection
  13. a1, a2 = np.indices(new_shape)
  14. inds = [a1, a2]
  15. inds.insert(max_axis, np.abs(data).argmax(axis=max_axis))
  16.  
  17. # take the values where the absolute value of the projection
  18. # is the highest
  19. maximum_intensity_data = data[inds]
  20.  
  21. return np.rot90(maximum_intensity_data)
项目:Rascal-tensorflow    作者:stayRascal    | 项目源码 | 文件源码
  1. def bp_sensitivity_map(self, sensitivity_array, activator):
  2. expanded_array = self.expand_sensitivity_map(sensitivity_array)
  3. expanded_width = expanded_array.shape[2]
  4. zp = (self.input_width + self.filter_width - 1 - expanded_width) / 2
  5. padded_array = padding(expanded_array, zp)
  6. self.delta_array = self.create_delta_array()
  7. for f in range(self.filter_number):
  8. filter = self.filters[f]
  9. flipped_weights = np.array(map(lambda i: np.rot90(i, 2), filter.get_weights()))
  10. delta_array = self.create_delta_array()
  11. for d in range(delta_array.shape[0]):
  12. conv(padded_array[f], flipped_weights[d], delta_array[d], 0)
  13. self.delta_array += delta_array
  14. derivative_array = np.array(self.input_array)
  15. element_wise_op(derivative_array, activator.backward)
  16. self.delta_array *= derivative_array
项目:bnpy    作者:bnpy    | 项目源码 | 文件源码
  1. def makeImgPatchPrototype(D, compID):
  2. '''''' Create image patch prototype for specific component
  3. Returns
  4. --------
  5. Xprototype : sqrt(D) x sqrt(D) matrix
  6. ''''''
  7. # Create a "prototype" image patch of PxP pixels
  8. P = np.sqrt(D)
  9. Xprototype = np.zeros((P, P))
  10. if compID % 4 == 0:
  11. Xprototype[:P / 2] = 1.0
  12. Xprototype = np.rot90(Xprototype, compID / 4)
  13. if compID % 4 == 1:
  14. Xprototype[np.tril_indices(P)] = 1
  15. Xprototype = np.rot90(Xprototype, (compID - 1) / 4)
  16. if compID % 4 == 2:
  17. Xprototype[np.tril_indices(P, 2)] = 1
  18. Xprototype = np.rot90(Xprototype, (compID - 2) / 4)
  19. if compID % 4 == 3:
  20. Xprototype[np.tril_indices(P, -2)] = 1
  21. Xprototype = np.rot90(Xprototype, (compID - 3) / 4)
  22. return Xprototype
项目:Robo-Plot    作者:JackBuck    | 项目源码 | 文件源码
  1. def take_photo_at(self, camera_centre):
  2. with picamera.PiCamera() as camera:
  3. camera.resolution = config.CAMERA_RESOLUTION
  4. camera.framerate = 24
  5. with picamera.array.PiRGBArray(camera) as output:
  6. camera.capture(output, ''bgr'', use_video_port=True)
  7. outputarray = output.array
  8.  
  9. # Rotate image to oriented it with paper.
  10. outputarray = np.rot90(outputarray, 3)
  11.  
  12. # Save photo.
  13. filename = datetime.datetime.Now().strftime("%M%s.%f_") + \\
  14. str(camera_centre[0]) \\
  15. + ''_'' \\
  16. + str(camera_centre[1]) + ''_Photo_'' + str(self._photo_index) + ''.jpg''
  17.  
  18. cv2.imwrite(os.path.join(config.debug_output_folder, filename), outputarray)
  19. self._photo_index += 1
  20.  
  21. return outputarray
项目:DRIP-SLIP    作者:NASA-DEVELOP    | 项目源码 | 文件源码
  1. def sum48(newFile,extent):
  2. currentSum=loadtxt(os.path.join(getCurrentDirectory(),''Sum48'',''sum48.txt''),dtype=''float'',delimiter='','')
  3. historicFiles=sorted(glob.glob(os.path.join(getCurrentDirectory(),''Files'',''*txt'')))
  4. lastFile=loadtxt(os.path.join(getCurrentDirectory(),historicFiles[0]),'')
  5. currentSum=currentSum-lastFile
  6. currentSum=currentSum+newFile
  7. np.savetxt(os.path.join(getCurrentDirectory(),currentSum,'')
  8. rotatedSum = np.rot90(currentSum)
  9. tiffFiles=glob.glob(os.path.join(getCurrentDirectory(),''Tiffs'',''*.TIF''))
  10. if not tiffFiles:
  11. lastTifNum=''1''
  12. else:
  13. tiffFiles=natsorted(tiffFiles,alg=ns.IC)
  14. lastTif=tiffFiles[-1]
  15. lastTifNum=str(int(lastTif[lastTif.rfind(''_'')+1:lastTif.rfind(''.'')])+1)
  16. array2raster(os.path.join(getCurrentDirectory(),timeStr[-11:-7]) + ''_48HourSum_'' + lastTifNum + ''.TIF'',[extent[0],extent[3]],extent[4],extent[5],rotatedSum,gdalconst.GDT_Float32)
  17. while len(tiffFiles)>48:
  18. os.remove(tiffFiles[0])
  19. tiffFiles=natsorted(glob.glob(os.path.join(getCurrentDirectory(),''*.TIF'')),alg=ns.IC)
  20. os.remove(historicFiles[0])
  21.  
  22. #sums the past 72 hours of rainfall,sends an email if exceeds threshold
项目:DRIP-SLIP    作者:NASA-DEVELOP    | 项目源码 | 文件源码
  1. def sum72(newFile,''Sum72'',''sum72.txt''),timeStr[-11:-7]) + ''_72HourSum_'' + lastTifNum + ''.TIF'',alg=ns.IC)
  2. os.remove(historicFiles[0])
  3.  
  4. #sends an e-mail containing "attachment",currently to the authors
项目:RocAlphaGo    作者:Rochester-NRT    | 项目源码 | 文件源码
  1. def symmetries(self):
  2. """returns a list of 8 GameState objects:
  3. all reflections and rotations of the current board
  4.  
  5. does not check for duplicates
  6. """
  7. copies = [self.copy() for i in range(8)]
  8. # copies[0] is the original.
  9. # rotate ccw 90
  10. copies[1].board = np.rot90(self.board,1)
  11. # rotate 180
  12. copies[2].board = np.rot90(self.board,2)
  13. # rotate ccw 270
  14. copies[3].board = np.rot90(self.board,3)
  15. # mirror left-right
  16. copies[4].board = np.fliplr(self.board)
  17. # mirror up-down
  18. copies[5].board = np.flipud(self.board)
  19. # mirror \\ diagonal
  20. copies[6].board = np.transpose(self.board)
  21. # mirror / diagonal (equivalently: rotate 90 ccw then flip LR)
  22. copies[7].board = np.fliplr(copies[1].board)
  23. return copies
项目:go-NN    作者:TheDuck314    | 项目源码 | 文件源码
  1. def pick_move(self, color):
  2. if not self.opponent_passed and self.last_opponent_play:
  3. mirror_x = self.board.N - self.last_opponent_play[0] - 1
  4. mirror_y = self.board.N - self.last_opponent_play[1] - 1
  5. if self.board.play_is_legal(mirror_x, mirror_y, color):
  6. return (mirror_x, mirror_y)
  7.  
  8. enemy_stones = (self.board.vertices == flipped_color[color])
  9. our_stones = (self.board.vertices == color)
  10. rot_enemy_stones = np.rot90(enemy_stones, 2)
  11.  
  12. play_vertices = np.logical_and(rot_enemy_stones, np.logical_not(our_stones))
  13. play_vertices = np.logical_and(play_vertices, np.logical_not(enemy_stones))
  14.  
  15. for x in xrange(self.board.N):
  16. for y in xrange(self.board.N):
  17. if play_vertices[x,y] and self.board.play_is_legal(x, color):
  18. return (x,y)
  19.  
  20. center = (self.board.N/2, self.board.N/2)
  21. if self.board[center] == Color.Empty and self.board.play_is_legal(center[0], center[1], color):
  22. return center
  23.  
  24. return None
项目:pyku    作者:dubvulture    | 项目源码 | 文件源码
  1. def extract_digits(self, image):
  2. """
  3. Extract digits from a binary image representing a sudoku
  4. :param image: binary image/sudoku
  5. :return: array of digits and their probabilities
  6. """
  7. prob = np.zeros(4, dtype=np.float32)
  8. digits = np.zeros((4, 9, 9), dtype=object)
  9. for i in range(4):
  10. labeled, features = label(image, structure=CROSS)
  11. objs = find_objects(labeled)
  12. for obj in objs:
  13. roi = image[obj]
  14. # center of bounding Box
  15. cy = (obj[0].stop + obj[0].start) / 2
  16. cx = (obj[1].stop + obj[1].start) / 2
  17. dists = cdist([[cy, cx]], CENTROIDS, ''euclidean'')
  18. pos = np.argmin(dists)
  19. cy, cx = pos % 9, pos / 9
  20. # 28x28 image,center relative to sudoku
  21. prediction = self.classifier.classify(morph(roi))
  22. if digits[i, cy, cx] is 0:
  23. # Newly found digit
  24. digits[i, cx] = prediction
  25. prob[i] += prediction[0, 0]
  26. elif prediction[0, 0] > digits[i, cx][0, 0]:
  27. # Overlapping! (noise),choose the most probable prediction
  28. prob[i] -= digits[i, 0]
  29. digits[i, 0]
  30. image = np.rot90(image)
  31. logging.info(prob)
  32. return digits[np.argmax(prob)]
项目:pyku    作者:dubvulture    | 项目源码 | 文件源码
  1. def extract_digits(self, 0]
  2. image = np.rot90(image)
  3. logging.info(prob)
  4. return digits[np.argmax(prob)]
项目:NumpyDL    作者:oujago    | 项目源码 | 文件源码
  1. def saveImage(inputimage, name):
  2. # red = inputimage[:1024]
  3. # green = inputimage[1024:2048]
  4. # blue = inputimage[2048:]
  5. # formatted = np.zeros([3,32,32])
  6. # formatted[0] = np.reshape(red,[32,32])
  7. # formatted[1] = np.reshape(green,32])
  8. # formatted[2] = np.reshape(blue,32])
  9. # final = np.swapaxes(formatted,2)/255
  10. final = inputimage
  11. final = np.rot90(np.rot90(np.rot90(final)))
  12. imsave(name, final)
项目:marblecutter    作者:mojodna    | 项目源码 | 文件源码
  1. def apply_latitude_adjustments(pixels):
  2. data, (bounds, crs), _ = pixels
  3. (_, height, width) = data.shape
  4.  
  5. ys = np.interp(np.arange(height), [0, height - 1], [bounds[3], bounds[1]])
  6. xs = np.empty_like(ys)
  7. xs.fill(bounds[0])
  8.  
  9. longitudes, latitudes = warp.transform(crs, wgs84_CRS, ys)
  10.  
  11. factors = 1 / np.cos(np.radians(latitudes))
  12.  
  13. # convert to 2d array,rotate 270º,scale data
  14. return PixelCollection(data * np.rot90(np.atleast_2d(factors), 3),
  15. pixels.bounds)
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def extract(self,ori_wmimage,wm, key=None):
  2. ''''''
  3. ??LSB??
  4. ''''''
  5. #???rgb?????????
  6. if len(ori_wmimage.shape)==3:
  7. wmimage = ori_wmimage[:,0]
  8. else:
  9. wmimage = ori_wmimage
  10.  
  11. #???????
  12. signature = self._gene_signature(wm,key).reshape((16,16))
  13.  
  14. #???????
  15. ext_sigs = self.ext_sig(wmimage,size=16)
  16. #ext_sigs.extend(self.ext_sig(np.rot90(wmimage,1)))
  17. #ext_sigs.extend(self.ext_sig(np.rot90(wmimage,2)))
  18. #ext_sigs.extend(self.ext_sig(np.rot90(wmimage,3)))
  19.  
  20. #?????
  21. similarity = 0
  22. for sig in ext_sigs:
  23. print(sig)
  24. print(signature)
  25. one_similarity = list(np.array(sig.flatten()) - signature.flatten()).count(0) / len(signature.flatten())
  26. #logging.info(''????? : {}''.format(one_similarity))
  27. similarity = max(similarity,one_similarity )
  28. break
  29.  
  30. logging.debug(''???????????????%f (1???0?????????0.7)'' % (similarity))
  31.  
  32. return similarity
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
  1. def inner_extract(self,signature):
  2. sig_size=np.int(np.sqrt(len(signature)))
  3. size = self.size
  4.  
  5. ext_sigs =[]
  6. #???????????????
  7. #???????????????????????
  8. # (0,0) (0,w-32)
  9. # (h-32,0) (h-32,w-32)
  10. w ,h = B.shape
  11. embed_pos =[(0,0)]
  12. embed_pos.append((w-sig_size*size,0))
  13. embed_pos.append((0,h-sig_size*size))
  14. embed_pos.append((w-sig_size*size,h-sig_size*size))
  15.  
  16. for x,y in embed_pos:
  17. ext_sig = np.zeros(len(signature),dtype=np.int)
  18.  
  19. for i in range(x,x+sig_size*size,size):
  20. for j in range(y,y+sig_size * size,size):
  21. v = cv2.dct(np.float32(B[i:i+size,j:j+size]))
  22. if v[size-1,size-1] > self.Q/2:
  23. ext_sig[((i-x)//size)*sig_size+(j-y)//size] = 1
  24.  
  25.  
  26. ext_sigs.append(ext_sig)
  27. ext_sig_arr = np.array(ext_sig).reshape((sig_size,sig_size))
  28. ext_sigs.append(np.rot90(ext_sig_arr,1).flatten())
  29. ext_sigs.append(np.rot90(ext_sig_arr,2).flatten())
  30. ext_sigs.append(np.rot90(ext_sig_arr,3).flatten())
  31.  
  32. return ext_sigs
项目:train-DeepLab    作者:martinkersner    | 项目源码 | 文件源码
  1. def convert_segmentation_mat2numpy(mat_file):
  2. np_segm = load_mat(mat_file)
  3. return np.rot90(np.fliplr(np.argmax(np_segm, axis=2)))
项目:train-DeepLab    作者:martinkersner    | 项目源码 | 文件源码
  1. def load_binary_segmentation(bin_file, dtype=''int16''):
  2. with open(bin_file, ''rb'') as bf:
  3. rows = struct.unpack(''i'', bf.read(4))[0]
  4. cols = struct.unpack(''i'', bf.read(4))[0]
  5. channels = struct.unpack(''i'', bf.read(4))[0]
  6.  
  7. num_values = rows * cols # expect only one channel in segmentation output
  8. out = np.zeros(num_values, dtype=np.uint8) # expect only values between 0 and 255
  9.  
  10. for i in range(num_values):
  11. out[i] = np.uint8(struct.unpack(''h'', bf.read(2))[0])
  12.  
  13. return np.rot90(np.fliplr(out.reshape((cols, rows))))
项目:PSPNet-Keras-tensorflow    作者:Vladkryvoruchko    | 项目源码 | 文件源码
  1. def rot90(W):
  2. for i in range(W.shape[0]):
  3. for j in range(W.shape[1]):
  4. W[i, j] = np.rot90(W[i, j], 2)
  5. return W
项目:kaggle-dstl-satellite-imagery-feature-detection    作者:u1234x1234    | 项目源码 | 文件源码
  1. def rot90_mat(mat, k):
  2. n_mat = np.zeros(mat.shape, dtype=np.float32)
  3. for i in range(mat.shape[2]):
  4. n_mat[:, i] = np.rot90(mat[:, i], k)
  5. return n_mat
项目:kagglePlanetPytorch    作者:Mctigger    | 项目源码 | 文件源码
  1. def rotate_90(k=1):
  2. def call(x):
  3. x = np.rot90(x, k).copy()
  4. return x
  5.  
  6. return call
项目:quoll    作者:LanguageMachines    | 项目源码 | 文件源码
  1. def visualize_document_topics_heatmap(self, outfile, set_topics=False):
  2. self.sort_doctopics_groups()
  3. doctopics_raw_hm = numpy.rot90(self.document_topics_raw)
  4. rows, columns = doctopics_raw_hm.shape
  5. rownames = self.topic_labels
  6. columnnames = self.document_names
  7. pyplot.pcolor(doctopics_raw_hm, norm=None, cmap=''Blues'')
  8. pyplot.gca().invert_yaxis()
  9. if self.group_names:
  10. ticks_groups = []
  11. bounds = []
  12. current_group = False
  13. start = 0
  14. for i,doc in enumerate(self.document_names):
  15. group = self.document_group_dict[doc]
  16. if group != current_group:
  17. if i != 0:
  18. bounds.append(i-1)
  19. ticks_groups[start+int((i-start)/2)] = current_group
  20. current_group = group
  21. start=i
  22. ticks_groups.append('''')
  23. ticks_groups[start+int((i-start)/2)] = current_group
  24. pyplot.xticks(numpy.arange(columns)+0.5,ticks_groups, fontsize=11)
  25. if set_topics:
  26. for index in set_topics:
  27. pyplot.axhline(y=index)
  28. topic_names = self.return_topic_names(set_topics)
  29. pyplot.yticks(set_topics,topic_names,fontsize=8)
  30. else:
  31. pyplot.yticks(numpy.arange(rows)+0.5, rownames, fontsize=8)
  32. for bound in bounds:
  33. pyplot.axvline(x=bound)
  34. pyplot.colorbar(cmap=''Blues'')
  35. pyplot.savefig(outfile)
  36. pyplot.clf()
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def _rotate(self, im, Meta):
  2. """ Use Orientation information from EXIF Meta data to
  3. orient the image correctly. Freeimage is also supposed to
  4. support that,and I am pretty sure it once did,but Now it
  5. does not,so let''s just do it in Python.
  6. Edit: and Now it works again,just leave in place as a fallback.
  7. """
  8. if self.request.kwargs.get(''exifrotate'', None) == 2:
  9. try:
  10. ori = Meta[''EXIF_MAIN''][''Orientation'']
  11. except KeyError: # pragma: no cover
  12. pass # Orientation not available
  13. else: # pragma: no cover - we cannot touch all cases
  14. # www.impulseadventure.com/photo/exif-orientation.html
  15. if ori in [1, 2]:
  16. pass
  17. if ori in [3, 4]:
  18. im = np.rot90(im, 2)
  19. if ori in [5, 6]:
  20. im = np.rot90(im, 3)
  21. if ori in [7, 8]:
  22. im = np.rot90(im)
  23. if ori in [2, 4, 7]: # Flipped cases (rare)
  24. im = np.fliplr(im)
  25. return im
  26.  
  27. # --
项目:inferno    作者:inferno-pytorch    | 项目源码 | 文件源码
  1. def image_function(self, image):
  2. return np.rot90(image, k=self.get_random_variable(''k''))
项目:image_analysis    作者:CoDaS-Lab    | 项目源码 | 文件源码
  1. def noise_amp(self, size):
  2. """
  3. DESCRIPTION:
  4. Creates a size x size matrix of randomly generated noise with
  5. amplitude values with 1/f slope
  6.  
  7. ARGS:
  8. :size: size of matrix
  9.  
  10. RETURNS:
  11. :returns the amplitudes with noise added
  12. """
  13.  
  14. slope = 1
  15. x = y = np.linspace(1, size, size)
  16. xgrid, ygrid = np.meshgrid(x, y) # coordinates for a square grid
  17. xgrid = np.subtract(xgrid, size // 2)
  18. ygrid = np.subtract(ygrid, size // 2)
  19.  
  20. amp = self.fft.fftshift(np.divide(np.sqrt(np.square(xgrid) +
  21. np.square(ygrid)),
  22. size * np.sqrt(2)))
  23. amp = np.rot90(amp, 2)
  24. amp[0, 0] = 1
  25. amp = 1 / amp**slope
  26. amp[0, 0] = 0
  27. return amp

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 模块-rot90() 实例源码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 ()、数组基本属性等相关知识的信息别忘了在本站进行查找喔。

本文标签: