def test_jpeg_alpha(): Image = pytest.importorskip('PIL.Image') plt.figure(figsize=(1, 1), dpi=300) # Create an image that is all black, with a gradient from 0-1 in # the alpha channel from left to right. im = np.zeros((300, 300, 4), dtype=float) im[..., 3] = np.linspace(0.0, 1.0, 300) plt.figimage(im) buff = io.BytesIO() with rc_context({'savefig.facecolor': 'red'}): plt.savefig(buff, transparent=True, format='jpg', dpi=300) buff.seek(0) image = Image.open(buff) # If this fails, there will be only one color (all black). If this # is working, we should have all 256 shades of grey represented. num_colors = len(image.getcolors(256)) assert 175 <= num_colors <= 185 # The fully transparent part should be red. corner_pixel = image.getpixel((0, 0)) assert corner_pixel == (254, 0, 0)
def plotClusters(websites, amount, clusters=8,xFactor=10, yFactor=10, myDpi=96, sampleSize=20): """ We want to plot every image according to the appropriate point on the x-axis according to its cluster number. We want to plot each new member of a given cluster at a higher y position Inputs: imagePath is a string to where the images are located websites is a list of tuples of the form: (clusterNumber, websitename) """ imagePath = getDataDir(amount, cut=True, big=False) clusterDict = [0 for n in xrange(clusters)] plt.figure(figsize=(800/myDpi, 800/myDpi), dpi=myDpi) for site in websites: clusterIndex, address = site try: yIndex = clusterDict[clusterIndex] if yIndex > sampleSize: continue image = mpimg.imread(imagePath+address) y = yIndex * yFactor clusterDict[clusterIndex]+=1 plt.figimage(image, clusterIndex*xFactor, y) except IOError: # usually if we don't have the small cut image yet pass plt.show()
def plot_montage(images, ndx, ncol=None): N = len(ndx) if not ncol: ncol = int(sqrt(N)) f = plt.figure(dpi=100) row = 0 col = 0 tot_height = 0 for i in range(N): I = sp.array(images[ndx[i]], dtype='float') I = I / I.max() height = I.shape[0] width = I.shape[1] ax = plt.figimage(I, xo=width*col, yo=height*row, origin='lower') col += 1 if col % ncol == 0: row += 1 col = 0 tot_height += height tot_height += height tot_width = width*ncol f.set_figheight(tot_height/100) f.set_figwidth(tot_width/100) return f
def plot_map(res, bins, cmap, cropName, fileName, technologyName, variableName, unitLabel, techFolder): figTitle = cropName + ' ' + technologyName + ' ' + variableName + ' (' + unitLabel + ')' plt.close() plt.figtext(0.025,0.92, figTitle, clip_on = 'True', size = 'large', weight = 'semibold'); plt.figtext(0.025,0.86, 'Spatially disaggregated production statistics of circa 2005 using the Spatial Production Allocation Model (SPAM).', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium'); plt.figtext(0.025,0.835,'Values are for 5 arc-minute grid cells.', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium'); plt.figtext(0.025,0.072, 'You, L., U. Wood-Sichra, S. Fritz, Z. Guo, L. See, and J. Koo. 2014', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium') plt.figtext(0.025,0.051, 'Spatial Production Allocation Model (SPAM) 2005 Version 2.0.', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium') plt.figtext(0.025,0.030, '03.10.2015. Available from http://mapspam.info', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium'); plt.figimage(logos, 4100, 200) map = Basemap(projection='merc',resolution='i', epsg=4326, lat_0 = 0, lon_0 = 20, llcrnrlon=-160, llcrnrlat=-70, urcrnrlon=200, urcrnrlat=90) map.drawlsmask(land_color='#fffff0', lakes = False, zorder = 1) shp_coast = map.readshapefile(baseShpLoc + '/ne_50m_coastline/ne_50m_coastline', 'scalerank', drawbounds=True, linewidth=0.1, color = '#828282', zorder = 7) shp_rivers = map.readshapefile(baseShpLoc + '/ne_110m_rivers_lake_centerlines/ne_110m_rivers_lake_centerlines', 'scalerank', drawbounds=True, color='#e8f8ff', linewidth=0.1, zorder = 5) shp_lakes = map.readshapefile(baseShpLoc + '/ne_110m_lakes/ne_110m_lakes', 'scalerank', drawbounds=True, linewidth=0.1, color='#e8f8ff', zorder=4) paths = [] for line in shp_lakes[4]._paths: paths.append(matplotlib.path.Path(line.vertices, codes=line.codes)) coll_lakes = matplotlib.collections.PathCollection(paths, linewidths=0, facecolors='#e8f8ff', zorder=3) cs = map.pcolormesh(res.lons, res.lats, res.d2, cmap=cmap, norm=BoundaryNorm(bins, 256, clip=True), zorder = 6) map.drawcountries(linewidth=0.1, color='#828282', zorder = 8) ax = plt.gca() ax.add_collection(coll_lakes) cbar = map.colorbar(cs,location='bottom', pad='3%') if (variableName == 'Production' or variableName == 'Yield'): labelSize = 8 else : labelSize = 7 labels = [item.get_text() for item in cbar.ax.get_xticklabels()] labels[0] = '1'; labels[labelSize - 1] = labels[labelSize - 1] + ' <'; labels[labelSize] = '' cbar.ax.set_xticklabels(labels) plt.tight_layout(h_pad=0.9, w_pad = 0.9) outputFile = 'spam2005v2r0_' + techFolder + '_' + fileName + '_' + technologyName.lower() plt.savefig(outputFolder + '/' + techFolder + '/' + outputFile + '.png', format='png', dpi=900)
def plot_digits(X, ndx, ncol=50, width=IM_WIDTH, cmap=cm.gray): """ plot a montage of the examples specified in ndx (as rows of X) """ row = 0 col = 0 for i in range(ndx.shape[0]): plt.figimage(reshape_digit(X, ndx[i]), xo=width*col, yo=width*row, origin='upper', cmap=cmap) col += 1 if col % ncol == 0: row += 1 col = 0
def _mock_worker(exact, estimated, param, nologo): """Plot the exact and estimated values of a parameter for the mock analysis Parameters ---------- exact: Table column Exact values of the parameter. estimated: Table column Estimated values of the parameter. param: string Name of the parameter nologo: boolean Do not add the logo when set to true. """ range_exact = np.linspace(np.min(exact), np.max(exact), 100) # We compute the linear regression if (np.min(exact) < np.max(exact)): slope, intercept, r_value, p_value, std_err = stats.linregress(exact, estimated) else: slope = 0.0 intercept = 1.0 r_value = 0.0 plt.errorbar(exact, estimated, marker='.', label=param, color='k', linestyle='None', capsize=0.) plt.plot(range_exact, range_exact, color='r', label='1-to-1') plt.plot(range_exact, slope * range_exact + intercept, color='b', label='exact-fit $r^2$ = {:.2f}'.format(r_value**2)) plt.xlabel('Exact') plt.ylabel('Estimated') plt.title(param) plt.legend(loc='best', fancybox=True, framealpha=0.5, numpoints=1) plt.minorticks_on() if nologo is False: image = plt.imread(pkg_resources.resource_filename(__name__, "data/CIGALE.png")) plt.figimage(image, 510, 55, origin='upper', zorder=10, alpha=1) plt.tight_layout() plt.savefig(OUT_DIR + 'mock_{}.pdf'.format(param)) plt.close()
def draw_mol_slider(mol, legend, matching, symbol, color, values, index): import matplotlib.pyplot as plt from matplotlib.widgets import Slider if op.isfile('/home/flo/temp.png'): os.remove('/home/flo/temp.png') subimg = MolToImage(mol, (200, 200), legend=legend, highlightAtoms=matching, symbol=symbol, background=color, mol_adder=MolDrawing.AddMol) # Then we will integrate a slider showing the relative ranking of the molecule rank = float(len(values[:index + 1])) / len(values) alpha_axis = plt.axes([0.37, 0.59, 0.14, 0.018], axisbg='grey') Slider(alpha_axis, '1(+)', 0, 1, valinit=rank, facecolor='w', valfmt='(-)%.0f') # Manually set to look good on the svg: [0.37, 0.59, 0.14, 0.018] for alpha_axis and 180, 70 for subimg # Manually set to look good on the png: [0.37, 0.59, 0.14, 0.018] for alpha_axis and 247, 172 for subimg # Now we need to combine subimg and slider in one image plt.figimage(subimg, 247, 172) plt.show() plt.savefig('/home/flo/temp.png') # , bbox_inches='tight')
def hydro_plot(view, hydro_code, image_size, figname): """ view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) """ if not HAS_MATPLOTLIB: return shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe = hydro_code.get_hydro_state_at_point( grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-9 | units.g / units.cm**3 max_rho = 1.0e-5 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr / min_v**2)) / numpy.log((max_v**2 / min_v**2)) log_rho = numpy.log((rho / min_rho)) / numpy.log((max_rho / min_rho)) log_E = numpy.log((E / min_E)) / numpy.log((max_E / min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum( numpy.ones_like(log_v), numpy.maximum( numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))) ) ).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis=2) pyplot.figure(figsize=(image_size[0]/100.0, image_size[1]/100.0), dpi=100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig(figname, transparent=True, dpi=100, facecolor='k', edgecolor='k') print "\nHydroplot was saved to: ", figname pyplot.close()
def make_image(self): rawdata = load(self.binfile) rotated = rot90(rawdata) rotated = rot90(rotated) rotated = rot90(rotated) rotated = reshape(rotated,(1,32,32)) rawshape = shape(rawdata) if self.taking_sky == True: self.skycount += rotated #print 'rawdata shape ', shape(rawdata) newcounts = reshape(rawdata,(1,1024)) self.counts = append(self.counts,newcounts,axis=0) self.rotated_counts = append(self.rotated_counts, rotated, axis=0) #print 'shape of counts', shape(self.counts) tf = self.image_time self.int_time = self.ui.int_time_spinBox.value() ti = tf-self.int_time if ti<0: ti = 0 if tf==0 or tf==ti: image_counts = newcounts else: image_counts = sum(self.counts[ti:tf],axis=0) image_counts = reshape(image_counts,(1,1024)) if self.sky_subtraction == True: image_counts = image_counts-reshape(self.skyrate*(tf-ti),(1,1024)) indices = sort(image_counts) brightest = self.ui.brightpix.value() self.vmax = indices[0,-1*(brightest)] photon_count = reshape(image_counts,rawshape) photon_count = rot90(photon_count) photon_count = rot90(photon_count) photon_count = rot90(photon_count) fig = plt.figure(figsize=(.32,.32), dpi=100, frameon=False) im = plt.figimage(photon_count, cmap='gray', vmax = self.vmax) #im = plt.figimage(rawdata, cmap='gray') plt.savefig("Arcons_frame.png", pad_inches=0) print "Generated image ",tf self.image_time+=1 if self.taking_sky == True: if self.image_time == self.skytime: self.taking_sky = False self.skyrate = self.skycount/self.skytime
def display_guass_pyramid(samples: List[np.ndarray]): len = samples.__len__() # get number of levels # input check if len == 0: return # initial variables for formatting offset = 0 padding = 1 # space between images in window gap = 64 # space between pyramid and top row square_size = 110 # size of squares in top row im_og_dim = samples[0].shape # get width of largest(original) image dpi = 100 # dpi for display if len == 1: # only have to worry about single image width = im_og_dim[0] else: # ensure window is sized wide enough for display width = max(im_og_dim[0]+samples[1].shape[0], square_size*len) # get height of downsampled images for setting offset off bottom of window height = 0 for sample in samples: height += sample.shape[1] offset = 2*im_og_dim[1] - height # set window width and height fig_w = width + padding*(len+1) fig_h = im_og_dim[1] + gap + 2*padding + square_size # create figure fig = plot.figure(figsize=(fig_w/dpi, fig_h/dpi)) # place the original, largest image plot.figimage(samples[0], padding, padding, cmap='gray') # initalize x and y placement values xv = 0 yv = im_og_dim[1] + 2 # ensure downsampled images line up with original image # format spacing and place pyramid images for i in range(1, len): xv = im_og_dim[0] + 2 * padding yv = yv - samples[i].shape[1] - 1 plot.figimage(samples[i], xv, yv, cmap='gray') # setup and place top row of images # uses resize function from skimage to match image sizes # allows easy creation of top row to fully match example image for i in range(0, len): plot.figimage(transform.resize(samples[i], (square_size, square_size), anti_aliasing=False), i * square_size + (i + 1) * padding, im_og_dim[1] + gap - padding, cmap='gray') # make figure fullscreen manager = plot.get_current_fig_manager() manager.full_screen_toggle() plot.suptitle('pyramid', fontsize=16) plot.show() # display figure return
def show_image(img, L=256, scale=False, stretch=False): ''' Show an image img: Grayscale image L: Gray levels (default 256) scale: True for scaled images, False for the original size (default) stretch: True for stretched grayscale, False for 0 to L-1 gray levels (default) ''' if stretch: vmin = np.min(img) vmax = np.max(img) else: vmin = 0. vmax = L - 1. if scale: plt.imshow(img, cmap='gray', vmin=vmin, vmax=vmax) else: dpi = plt.rcParams['figure.dpi'] plt.figure(figsize=(img.shape[0] / dpi, img.shape[1] / dpi)) plt.figimage(img, 0, 0, cmap='gray', vmin=vmin, vmax=vmax) plt.show()
def test_jpeg_alpha(): plt.figure(figsize=(1, 1), dpi=300) # Create an image that is all black, with a gradient from 0-1 in # the alpha channel from left to right. im = np.zeros((300, 300, 4), dtype=float) im[..., 3] = np.linspace(0.0, 1.0, 300) plt.figimage(im) buff = io.BytesIO() plt.savefig(buff, facecolor="red", format='jpg', dpi=300) buff.seek(0) image = Image.open(buff) # If this fails, there will be only one color (all black). If this # is working, we should have all 256 shades of grey represented. num_colors = len(image.getcolors(256)) assert 175 <= num_colors <= 185 # The fully transparent part should be red. corner_pixel = image.getpixel((0, 0)) assert corner_pixel == (254, 0, 0)
def compare_files(dir_path1, dir_path2, name): result = None path1 = os.path.join(dir_path1, name) path2 = os.path.join(dir_path2, name) if not os.path.isfile(path1) or not os.path.isfile(path2): result = Difference(name, 'missing file') else: image1 = plt.imread(path1) image2 = plt.imread(path2) if image1.shape != image2.shape: result = Difference(name, "shape: %s -> %s" % (image1.shape, image2.shape)) else: diff = (image1 != image2).any(axis=2) if diff.any(): diff_path = os.path.join(DIFF_DIR, name) diff_path = os.path.realpath(diff_path) plt.figure(figsize=reversed(diff.shape), dpi=1) plt.figimage(diff, cmap=cm.gray) plt.savefig(diff_path, dpi=1) result = Difference(name, "diff: %s" % diff_path) return result
def compare_images(img1, img2, L=256, scale=False, stretch=False): ''' Compare two images img1: Image 1 img2: Image 2 L: Gray levels (default 256) scale: True for scaled images, False for the original size (default) stretch: True for stretched grayscale, False for 0 to L-1 gray levels (default) ''' if stretch: vmin1 = np.min(img1) vmax1 = np.max(img1) vmin2 = np.min(img2) vmax2 = np.max(img2) else: vmin1 = vmin2 = 0. vmax1 = vmax2 = L - 1. if scale: fig, ax = plt.subplots(1, 2) ax[0].set_title('img1') ax[0].set_axis_off() ax[0].imshow(img1, cmap="gray", vmin=vmin1, vmax=vmax1) ax[1].set_title('img2') ax[1].set_axis_off() ax[1].imshow(img2, cmap="gray", vmin=vmin2, vmax=vmax2) else: dpi = plt.rcParams['figure.dpi'] plt.figure(figsize=((img1.shape[0] + img2.shape[0]) / dpi, max(img1.shape[1], img2.shape[1]) / dpi)) figx = 0 figy = max(img2.shape[1] - img1.shape[1], 0) plt.figimage(img1, figx, figy, cmap='gray', vmin=vmin1, vmax=vmax1) figx += img1.shape[0] figy = max(img1.shape[1] - img2.shape[1], 0) plt.figimage(img2, figx, figy, cmap='gray', vmin=vmin2, vmax=vmax2) plt.show()
def test_jpeg_alpha(): plt.figure(figsize=(1, 1), dpi=300) # Create an image that is all black, with a gradient from 0-1 in # the alpha channel from left to right. im = np.zeros((300, 300, 4), dtype=float) im[..., 3] = np.linspace(0.0, 1.0, 300) plt.figimage(im) buff = io.BytesIO() with rc_context({'savefig.facecolor': 'red'}): plt.savefig(buff, transparent=True, format='jpg', dpi=300) buff.seek(0) image = Image.open(buff) # If this fails, there will be only one color (all black). If this # is working, we should have all 256 shades of grey represented. print("num colors: ", len(image.getcolors(256))) assert len(image.getcolors(256)) >= 175 and len(image.getcolors(256)) <= 185 # The fully transparent part should be red, not white or black # or anything else print("corner pixel: ", image.getpixel((0, 0))) assert image.getpixel((0, 0)) == (254, 0, 0)
def saveFig(w, h, data, output, cmapData=None, minData=None, maxData=None): # --- Save image fig = plt.figure(figsize=((w / 100) + 1, (h / 100) + 1), dpi=100) cax = plt.figimage(data, vmin=minData, vmax=maxData, cmap=cmapData) fig.savefig(output) #, bbox_inches=extent) plt.close() # Load and resave image im = Image.open(output) (widthN, heightN) = im.size logger.info("Detected size: ", widthN, heightN, "targeted", w, h) im2 = im.crop(((widthN - w), (heightN - h), w, h)) im.close() im2.save(output)
def test_jpeg_alpha(): plt.figure(figsize=(1, 1), dpi=300) # Create an image that is all black, with a gradient from 0-1 in # the alpha channel from left to right. im = np.zeros((300, 300, 4), dtype=np.float) im[..., 3] = np.linspace(0.0, 1.0, 300) plt.figimage(im) buff = io.BytesIO() with rc_context({'savefig.facecolor': 'red'}): plt.savefig(buff, transparent=True, format='jpg', dpi=300) buff.seek(0) image = Image.open(buff) # If this fails, there will be only one color (all black). If this # is working, we should have all 256 shades of grey represented. print("num colors: ", len(image.getcolors(256))) assert len(image.getcolors(256)) >= 175 and len(image.getcolors(256)) <= 185 # The fully transparent part should be red, not white or black # or anything else print("corner pixel: ", image.getpixel((0, 0))) assert image.getpixel((0, 0)) == (254, 0, 0)
def plot_movie_mp4(image_array): dpi = 70.0 xpixels, ypixels = image_array[0].shape[0], image_array[0].shape[1] fig = plt.figure(figsize=(ypixels / dpi, xpixels / dpi), dpi=dpi) im = plt.figimage(image_array[0]) def animate(i): im.set_array(image_array[i]) return (im, ) anim = animation.FuncAnimation(fig, animate, frames=len(image_array)) display(HTML(anim.to_html5_video())) anim.save('/home/jesse/Desktop/animation.mp4', writer='imagemagick', fps=40)
def testDivisonOfGrid(): topo = topology.Topology() topoFile = "topology_200.txt" try: topo.importFromFile(topoFile) except: print "could not read topology file", topoFile habNM = simulation.makeNeighConnMap(topo) sects = simulation.divideGridToSection(habNM, GRID_SIZE, GRID_SIZE) print "sects ", sects k = 0 for habs in sects.values(): k = k + 1 X = pylab.ones((10, 10, 3)) * float(k * 0.4) print "habs", habs for hab in habs: hab = hab - 1 xo = int(hab % GRID_SIZE) * 2 yo = int(hab / GRID_SIZE) * 2 print "X ", xo print "Y ", yo plt.figimage(X, xo, yo, origin='lower') plt.show()
def testDivisonOfGrid(): topo = topology.Topology() topoFile="topology_200.txt" try: topo.importFromFile(topoFile) except: print "could not read topology file",topoFile habNM = simulation.makeNeighConnMap(topo) sects = simulation.divideGridToSection(habNM,GRID_SIZE,GRID_SIZE) print "sects ",sects k=0 for habs in sects.values(): k=k+1 X = pylab.ones((10,10,3))*float(k*0.4) print "habs" ,habs for hab in habs: hab=hab-1 xo=int(hab%GRID_SIZE)*2 yo=int(hab/GRID_SIZE)*2 print "X ",xo print "Y ",yo plt.figimage(X, xo, yo, origin='lower') plt.show()
def save_movie_mp4(image_array): writer = animation.FFMpegFileWriter(fps=20, metadata=dict(artist='Me'), bitrate=1800) dpi = 72.0 xpixels, ypixels = image_array[0].shape[0], image_array[0].shape[1] fig = plt.figure(figsize=(ypixels / dpi, xpixels / dpi), dpi=dpi) im = plt.figimage(image_array[0]) def animate(i): im.set_array(image_array[i]) return (im, ) plt.show() ani = animation.FuncAnimation(fig, animate, frames=len(image_array)) ani.save('lin_mod.mp4', writer=writer)
def hydro_plot(view, hydro_code, image_size, figname): """ view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) """ if not HAS_MATPLOTLIB: return shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe = hydro_code.get_hydro_state_at_point(grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-9 | units.g / units.cm**3 max_rho = 1.0e-5 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr / min_v**2)) / numpy.log((max_v**2 / min_v**2)) log_rho = numpy.log((rho / min_rho)) / numpy.log((max_rho / min_rho)) log_E = numpy.log((E / min_E)) / numpy.log((max_E / min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum(numpy.ones_like(log_v), numpy.maximum(numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))))).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis = 2) pyplot.figure(figsize = (image_size[0]/100.0, image_size[1]/100.0), dpi = 100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig(figname, transparent=True, dpi = 100, facecolor='k', edgecolor='k') print "\nHydroplot was saved to: ", figname pyplot.close()
def saveFig(w,h,data,output,cmapData=None, minData=None, maxData=None): # --- Save image fig = plt.figure(figsize=((w/100)+1, (h/100)+1), dpi=100) cax = plt.figimage(data, vmin=minData, vmax=maxData, cmap=cmapData) fig.savefig(output)#, bbox_inches=extent) plt.close() # Load and resave image im = Image.open(output) (widthN, heightN) = im.size logger.info("Detected size: ",widthN,heightN, "targeted", w, h) im2 = im.crop(((widthN-w), (heightN-h), w,h)) im.close() im2.save(output)
def plot_images_as_video(image_array, dpi=72.0, format="html5", jupyter=True, display_index=False): """Takes a list of images and plots them as a playable video sequence. Arguments: image_array: list(np.array) List of successive frames. dpi: float Determines the resolution of the figure. format: ("html5", "jshtml") Format of the video. jupyter: bool Whether to display the video in a jupyter notebook. display_index: bool Whether to display the current frame index as annotated text in the video. Returns: fig, anim: matplotlib figure, animation object. If jupyter=True, None is returned. """ import matplotlib.animation import matplotlib.pyplot as plt xpixels, ypixels = image_array[0].shape[0], image_array[0].shape[1] fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi) im = plt.figimage(image_array[0].astype(np.float32), cmap="gray") txt = plt.figtext(0.025, 0.94, "", backgroundcolor="gray", size=16) def animate(i): im.set_array(image_array[i].astype(np.float32)) if display_index: txt.set_text(str(i)) return (im,) anim = matplotlib.animation.FuncAnimation(fig, animate, frames=len(image_array)) if format == "html5": anim = anim.to_html5_video() elif format == "jshtml": anim = anim.to_jshtml() else: raise ValueError("'format' must be one of 'html5', 'jshtml'!") if jupyter: from IPython.display import display, HTML display(HTML(anim)) plt.close() return None return fig, anim
def convertImageImp(path, out, clMin=-1, clMax=-1, inver=False, usePourcentage=False, pourcent=0.90): (w, h), pRef = rgbe.io.read(path) fig = plt.figure(figsize=((w / 100.0), (h / 100.0)), dpi=100) data = convertImage(pRef, h, w, inver) pRefLum = [p[0] for p in pRef] pRefLum.sort() maxData = pRefLum[-1] minData = pRefLum[0] if (usePourcentage): maxData = pRefLum[int(len(pRefLum) * pourcent)] print("Find the max: " + str(maxData)) print("Find the min: " + str(minData)) if clMin >= 0: minData = clMin if clMax >= 0: maxData = clMax #print(data) cax = plt.figimage(data, vmin=minData, vmax=maxData, cmap=cm.get_cmap("viridis")) fig.savefig(out) #, bbox_inches=extent) plt.close() im = Image.open(out) (widthN, heightN) = im.size im = im.crop(((widthN - w), (heightN - h), w, h)) im.save(out) im.close() return maxData, minData
def loadIm(self): print("Complex load") fig = plt.figure(figsize=((self.width/100.0), (self.height/100.0)), dpi=100) data = convertImage(self.pixelsHDR, self.height, self.width, self.inverse) if(self.inverse): pRefLum = [0.0 if lum(p)==0 else 1.0/lum(p) for p in self.pixelsHDR] else: pRefLum = [lum(p) for p in self.pixelsHDR] pRefLum.sort() maxData = pRefLum[-1] minData = pRefLum[0] print("Find the max: "+str(maxData)) print("Find the min: "+str(minData)) if(self.pMax != -1): maxData = pRefLum[int(len(pRefLum)*self.pMax)] if(self.pMin != -1): minData = pRefLum[int(len(pRefLum)*self.pMin)] if self.minV != -10000.005454: minData = self.minV if self.maxV != 10000.005454: maxData = self.maxV print("Used max: "+str(maxData)) print("Used min: "+str(minData)) # --- Save the figure cax = plt.figimage(data, vmin=minData, vmax=maxData, cmap=self.cmap) fig.savefig(wk + os.path.sep + self.output)#, bbox_inches=extent) self.im = Image.open(wk + os.path.sep + self.output) (widthN, heightN) = self.im.size self.im = self.im.crop(((widthN-self.width), (heightN-self.height), self.width, self.height))
def plot_sequence_images(image_array): ''' Display images sequence as an animation in jupyter notebook Args: image_array(numpy.ndarray): image_array.shape equal to (num_images, height, width, num_channels) ''' dpi = 72.0 xpixels, ypixels = image_array[0].shape[:2] fig = plt.figure(figsize=(ypixels / dpi, xpixels / dpi), dpi=dpi) im = plt.figimage(image_array[0]) def animate(i): im.set_array(image_array[i]) return (im, ) anim = animation.FuncAnimation(fig, animate, frames=len(image_array), interval=200, repeat_delay=1, repeat=True) display(HTML(anim.to_html5_video()))
def loadIm(self): logger.debug("Complex load") fig = plt.figure(figsize=((self.width/100.0), (self.height/100.0)), dpi=100) data = convertImage(self.pixelsHDR, self.height, self.width, self.inverse) if(self.inverse): pRefLum = [0.0 if lum(p)==0 else 1.0/lum(p) for p in self.pixelsHDR] else: pRefLum = [lum(p) for p in self.pixelsHDR] pRefLum.sort() maxData = pRefLum[-1] minData = pRefLum[0] logger.info("Find the min/max: ",str(minData),str(maxData)) if(self.pMax != -1): maxData = pRefLum[int(len(pRefLum)*self.pMax)] if(self.pMin != -1): minData = pRefLum[int(len(pRefLum)*self.pMin)] if self.minV != -10000.005454: minData = self.minV if self.maxV != 10000.005454: maxData = self.maxV logger.info("Used min/max: ",str(minData),str(maxData)) # --- Save the figure cax = plt.figimage(data, vmin=minData, vmax=maxData, cmap=self.cmap) fig.savefig(wk + os.path.sep + self.output)#, bbox_inches=extent) self.im = Image.open(wk + os.path.sep + self.output) (widthN, heightN) = self.im.size self.im = self.im.crop(((widthN-self.width), (heightN-self.height), self.width, self.height))
def plotDatos (x,y,offset,var,path,coorven,dataVen,dataMin,dataMax,dataMean,varBus,varName,stdName,unidades,varCal,paleta,logoPath,muestraDatos): """ ========================================================================================== Función que mapea los datos de la ventana, requiriendo el numpy array creado a partir de los datos de TIFF recortado y reproyectado, además de mostrar la información de la variable ========================================================================================== """ print ('Mapeando datos...') # Tamaño de la figura fig = plt.figure(figsize=(15,15)) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax = plt.axis('off') # Crea el mapa base con las coordenadas extremas bmap = Basemap(llcrnrlon=coorven[0], llcrnrlat=coorven[1], urcrnrlon=coorven[2], urcrnrlat=coorven[3], resolution='i', epsg=4326) bmap.drawcoastlines(linewidth=1.5) bmap.drawcountries(linewidth=1.5) bmap.drawstates(linewidth=0.5) bmap.drawparallels(np.arange(-90.0, 90.0, offset/2.0), linewidth=0.5, color='black') bmap.drawmeridians(np.arange(0.0, 360.0, offset/2.0), linewidth=0.5, color='black') # Plotea los datos con la paleta asignada bmap.imshow(dataVen, origin='upper', cmap=paleta) # Agrega una barra de color tick1,tick2,tick3,tick4,tick5,tick6,tick7 = calculaTicks(dataMin,dataMax) # Agrega los valores de los intervalos a la barra de color cb = bmap.colorbar(location='bottom', size = '2.0%', pad = '-2.0%', ticks=[tick1,tick2,tick3,tick4,tick5,tick6,tick7]) cb.ax.set_xticklabels([str(round(tick1,2)),str(round(tick2,2)),str(round(tick3,2)),str(round(tick4,2)),str(round(tick5,2)),str(round(tick6,2)),str(round(tick7,2))]) cb.outline.set_visible(True) # Coloca una línea en el borde cb.ax.tick_params(width = 0) # Remueve los ticks cb.ax.xaxis.set_tick_params(pad=-20) # Pone lo valores de los intervalos dentro de la barra cb.ax.tick_params(axis='x', colors='black', labelsize=15) # Define el color y tamaño de la letra de los ticks # Agrega un label al punto label = str(round(float(varBus),3))+'\n('+str(x)+','+str(y)+')' # Agrega un marcador del punto buscado estx, esty = bmap(x,y) bmap.plot(estx, esty, marker='+',color='r', markersize=55) plt.text(x+(offset/15.0), y+(offset/15.0), label, fontsize=20) # Obtiene las regiones de las coordenadas xNom,yNom = regionCoordenadas(x,y) # Obtiene la fecha y los tiempos de escaneo ano,dia,horaInicio,horaTerminado,fecha = tiempoEscaneo(path) if muestraDatos == True: # Agrega un rectangulo para colocar los datos currentAxis = plt.gca() currentAxis.add_patch(Rectangle((x-offset, y-offset/1.04),offset*0.75 ,offset*0.11 , alpha=1, facecolor='silver', zorder = 3,ec="black", lw=1.0)) # Agrega los datos de la variable al rectángulo plt.text(x-offset/1.02, y-offset/1.19, 'Archivo: '+path[path.find("OR"):path.find("_s")]+'...\nVariable: '+var+' '+varName+'\nNombre Estandar: ' +stdName+'\nUnidades: '+unidades, fontsize=12) # Agrega los datos de la ventana plt.text(x-offset/1.02, y-offset/1.05, 'Maximo: '+str(round(dataMax,2))+'\nMinimo: '+str(round(dataMin,2))+'\nMedia: '+str(round(dataMean,2)),fontsize=15) # Agrega los datos de la coordenada plt.text(x-offset/1.38, y-offset/1.07,'\nLatitud: '+str(abs(round(y,2)))+' '+yNom+'\nLongitud: '+str(abs(round(x,2)))+' '+xNom, fontsize=15) # Agrega el valor y la calidad del dato de acuerdo al subdataset DQF, que define la calidad con la que fueron calculados los datos, este se encuentra # en todos los NetCDF L1b y L2 de Goes, lo define por el color de la letra if varCal == 0: calColor = 'g' calidad = 'Algoritmo procesado' elif varCal == 16 or varBus == np.nan: calColor = 'b' calidad = 'Algoritmo no procesado' else: calColor = 'r' calidad = 'Algoritmo con calidad: '+str(int(varCal)) plt.text(x-offset/2.22, y-offset/1.09,str(round(float(varBus),2)), fontsize=30, color=calColor) plt.text(x-offset/2.24, y-offset/1.06,calidad,fontsize=7, color=calColor) # Agrega la fecha y los tiempos de escaneo. plt.text(x-offset/1.02,y+offset/1.25,'Fecha: '+ano+'-'+dia+'\nESCANEO\nInicio: '+horaInicio+'\nFinal: '+horaTerminado,fontsize=23) # Agrega un logo logo = plt.imread(logoPath) plt.figimage(logo,965, 19, zorder=3, alpha = 1, origin = 'upper') # Guarda y muestra el mapa plt.savefig('Goes16_'+var+'_'+fecha+'_'+str(abs(y))+yNom+'_'+str(abs(x))+xNom+'.png') plt.show()
y = training_label N = x.shape[0] C = 40 eigenfaces = pca(training_faces) eigenvectors = eigenfaces[:N - C].T transformed_faces = np.dot(training_faces - average_face, eigenvectors) W = lda(transformed_faces, y) W = W[:, :39] fisherfaces = np.dot(eigenvectors, W) firstfish = fisherfaces.T[0] # print(firstfish) # print(np.shape(fisherfaces.T[0])) plt.figure(figsize=(c / 100, r / 100)) plt.axis('off') plt.figimage(firstfish.reshape(r, c), cmap='gray') plt.savefig(output_face) plt.close() # cv2.imwrite(output_face, firstfish.astype(np.uint8).reshape(r, c)) # -------------- for hw2-2(b1) -------------- ''' plt.figure() for i in range(5): plt.subplot(2, 3, i + 1) plt.axis("off") plt.imshow(fisherfaces.T[i].reshape(r, c), cmap="gray") plt.subplots_adjust(wspace=0.2, hspace=0.2) plt.suptitle("fisherfaces") plt.savefig("fisherfaces.png") plt.close()
ax = plt.subplot(2, 2, 4) ax.imshow(small_im, interpolation='nearest') plt.subplots_adjust(left=0.24, wspace=0.2, hspace=0.1, \ bottom=0.05, top=0.86) #Label the rows and columns of the table fig.text(0.03, 0.645, 'Big Image\nScaled Down', ha='left') fig.text(0.03, 0.225, 'Small Image\nBlown Up', ha='left') fig.text(0.383, 0.90, "Interpolation = 'none'", ha='center') fig.text(0.75, 0.90, "Interpolation = 'nearest'", ha='center') #If you were going to run this example on your local machine, you #would save the figure as a PNG, save the same figure as a PDF, and #then compare them. The following code would suffice. txt = fig.text(0.452, 0.95, 'Saved as a PNG', fontsize=18) # plt.savefig('None_vs_nearest-png.png') # txt.set_text('Saved as a PDF') # plt.savefig('None_vs_nearest-pdf.pdf') #Here, however, we need to display the PDF on a webpage, which means #the PDF must be converted into an image. For the purposes of this #example, the 'Nearest_vs_none-pdf.pdf' has been pre-converted into #'Nearest_vs_none-pdf.png' at 80 dpi. We simply need to load and #display it. pdf_im_path = cbook.get_sample_data('None_vs_nearest-pdf.png') pdf_im = plt.imread(pdf_im_path) fig2 = plt.figure(figsize=[8.0, 7.5]) plt.figimage(pdf_im) plt.show()
def figimage(*args, **kwargs): r"""starkplot wrapper for figimage""" return _pyplot.figimage(*args, **kwargs)
def make_png(infile, outdir): """ """ # Get DN sarmp = SARMapper(infile) sarim = SARImage(sarmp) orig_spacing = sarim.get_original_spacing() # n = np.ceil(sarim.get_info('number_of_samples')/600.) # spacing = orig_spacing[1]*n # spacing = orig_spacing[1]*10 im = abs(sarim.get_values('digital_number', step=[10, 10])) final_spacing = orig_spacing*[10, 10] sar_size = sarim.get_full_extent()[2:4] extent = [sar_size[0]/2, sar_size[1]/2, sar_size[0]/2+1, sar_size[1]/2+1] lon = sarim.get_values('lon', extent=extent) lat = sarim.get_values('lat', extent=extent) inc = sarim.get_values('incidence', extent=extent) heading = sarim.get_info('platform_heading') north = 90+heading # north dir in image im_num = sarim.get_info('image_number') dist = (np.array(im.shape)-1)*final_spacing/1000. if sarim.get_info('pass') == 'Descending': im = im[::-1, ::-1] north = north+180 # ind = im.nonzero() # ind = np.where(im > 50) # im2 = im[ind] # vmin = im2.min() # vmax = im2.max() imsh = im.shape im2 = im[imsh[0]*0.1:imsh[0]*0.9, imsh[1]*0.1:imsh[1]*0.9] vmin = im2.min() vmax = im2.max() # Make figure dpi = 100 imsize = np.array(im.shape[::-1]) margin = np.array(((900-imsize[0])/2, 60)) figsize = np.array((900, imsize[1]+2*margin[1])) imsizeN = imsize.astype('float')/figsize marginN = margin.astype('float')/figsize #print imsize, margin, figsize fig = plt.figure(figsize=figsize.astype('float')/dpi, dpi=dpi) # imax = fig.gca() # imax.set_position([marginN[0], marginN[1], imsizeN[0], imsizeN[1]]) imax = fig.add_axes([marginN[0], marginN[1], imsizeN[0], imsizeN[1]]) imax.set_xlim(0, dist[1]) imax.set_ylim(0, dist[0]) plt.imshow(im, origin='lower', interpolation='nearest', vmin=vmin, vmax=vmax, cmap=cm.get_cmap('Greys_r'), extent=[0, dist[1], 0, dist[0]], aspect='auto') imax.set_xlabel('range distance [km]') imax.set_ylabel('azimuth distance [km]') tit = '#%03i / lon=%.2f / lat=%.2f / inc=%.2f' % (im_num, lon, lat, inc) imax.set_title(tit) #imax.set_frame_on(False) #imax.set_axis_off() # Add colorbar cbax = fig.add_axes([1-0.75*marginN[0], .25, 20./figsize[0], .50]) plt.colorbar(label='digital number', cax=cbax, format='%.1e') meanstr = r'$\mu$=%.2f' % im2.mean() cbax.text(0.5, -0.025, meanstr, ha='center', va='top') stdstr = r'$\sigma$=%.2f' % im2.std() cbax.text(0.5, -0.1, stdstr, ha='center', va='top') minstr = 'min=%.2f' % im2.min() cbax.text(0.5, 1.025, minstr, ha='center', va='bottom') maxstr = 'max=%.2f' % im2.max() cbax.text(0.5, 1.1, maxstr, ha='center', va='bottom') # Add north cpsizeN = (margin[0]-margin[1])/figsize.astype('float') cpax = fig.add_axes([0., 0.5-cpsizeN[1]/2, cpsizeN[0], cpsizeN[1]]) plt.arrow(.5, .5, .5*np.cos(north*np.pi/180), .5*np.sin(north*np.pi/180), facecolor='black', width=0.01, length_includes_head=True, head_width=0.1, head_length=0.1) plt.annotate('North', (.5, .5), ha='center', va='top') cpax.set_axis_off() # Add Logos python_logo = '/local/home/gilles/Documents/logo/python-powered-w-70x28.png' #python_logo = '/home/cercache/users/gguitton/Documents/logo/python-powered-w-70x28.png' logo = imread(python_logo) plt.figimage(logo, 5, figsize[1]-logo.shape[0]-5) odl_logo = '/local/home/gilles/Documents/logo/oceandatalab-85x32.png' #odl_logo = '/home/cercache/users/gguitton/Documents/logo/oceandatalab-85x32.png' logo = imread(odl_logo) plt.figimage(logo, 5, 5) # Save as PNG infileid = os.path.basename(os.path.dirname(os.path.dirname(infile))) outdir2 = os.path.join(outdir, infileid) if os.path.exists(outdir2) == False: os.makedirs(outdir2) outfile = os.path.join(outdir2, os.path.basename(infile).replace('.tiff','-digital_number.png')) plt.savefig(outfile, dpi=dpi)#, bbox_inches='tight') plt.close() cmd = 'convert '+outfile+' -colors 256 '+outfile os.system(cmd)
p = reader.PelFile(location+"%04i.pel"%run) image = np.sum(p.make3d(),axis=2) return (p.header._asdict(),image) if __name__=="__main__": plt.figure(figsize=(4,4)) g = gaingen() gain = g.next() old = -1000 d={gain:{}} x = np.arange(512) for i in range(1,75): (h,im) = extract(i) plt.clf() plt.figimage(im,vmin=0,vmax=200,cmap="spectral") plt.savefig(location+"%04i.png"%i,dpi=128) plt.clf() plt.fill_between(x,np.sum(im,axis=0)) plt.savefig(location+"x%04i.png"%i,dpi=128) plt.clf() plt.fill_between(x,np.sum(im,axis=1)) plt.savefig(location+"y%04i.png"%i,dpi=128) if h[gain] < old: #we've moved on to the next gain print (gain,h[gain],old) gain = g.next() if not d.has_key(gain): d[gain] = {} d[gain][h[gain]] = i old = h[gain] with open(location+"gains.html","w") as outfile:
def _make_plot(station, sknt, drct, units, nsector, rmax, hours, months, sname, minvalid, maxvalid, level, bins): """Generate a matplotlib windrose plot Args: station (str): station identifier sknt (list): list of wind obs drct (list): list of wind directions units (str): units of wind speed nsector (int): number of bins to use for windrose rmax (float): radius of the plot hours (list): hour limit for plot month (list): month limit for plot sname (str): station name minvalid (datetime): minimum observation time maxvalid (datetime): maximum observation time level (int): RAOB level in hPa of interest bins (list): values for binning the wind speeds Returns: matplotlib.Figure """ # Generate figure fig = plt.figure(figsize=(7, 7), dpi=80, facecolor='w', edgecolor='w') rect = [0.15, 0.15, 0.7, 0.7] ax = WindroseAxes(fig, rect, axisbg='w') fig.add_axes(ax) wu = WINDUNITS[units] if level is None else RAOB_WINDUNITS[units] if len(bins) > 0: wu['bins'] = bins wu['binlbl'] = [] for i, mybin in enumerate(bins[1:-1]): wu['binlbl'].append("%g-%g" % (mybin, bins[i+2])) wu['binlbl'].append("%g+" % (bins[-1],)) ax.bar(drct, sknt, normed=True, bins=wu['bins'], opening=0.8, edgecolor='white', nsector=nsector, rmax=rmax) handles = [] for p in ax.patches_list: color = p.get_facecolor() handles.append(plt.Rectangle((0, 0), 0.1, 0.3, facecolor=color, edgecolor='black')) l = fig.legend(handles, wu['binlbl'], loc=(0.01, 0.01), ncol=6, title='Wind Speed [%s]' % (wu['abbr'],), mode=None, columnspacing=0.9, handletextpad=0.45) plt.setp(l.get_texts(), fontsize=10) # Now we put some fancy debugging info on the plot tlimit = "Time Domain: " if len(hours) == 24 and len(months) == 12: tlimit = "All Year" if len(hours) < 24: if len(hours) > 4: tlimit += "%s-%s" % ( datetime.datetime(2000, 1, 1, hours[0]).strftime("%-I %p"), datetime.datetime(2000, 1, 1, hours[-1]).strftime("%-I %p") ) else: for h in hours: tlimit += "%s," % ( datetime.datetime(2000, 1, 1, h).strftime("%-I %p"),) if len(months) < 12: for h in months: tlimit += "%s," % (datetime.datetime(2000, h, 1).strftime("%b"),) label = """[%s] %s%s Windrose Plot [%s] Period of Record: %s - %s""" % ( station, sname if sname is not None else "((%s))" % (station, ), "" if level is None else " @%s hPa" % (level, ), tlimit, minvalid.strftime("%d %b %Y"), maxvalid.strftime("%d %b %Y")) plt.gcf().text(0.14, 0.99, label, va='top') plt.gcf().text(0.96, 0.11, ( "Stats\nn: %s\nCalm: %.1f%%\nAvg Speed: %.1f %s" ) % (np.shape(sknt)[0], np.sum(np.where(sknt < 2., 1., 0.)) / np.shape(sknt)[0] * 100., np.average(sknt), wu['abbr']), ha='right') plt.gcf().text(0.01, 0.11, "Generated: %s" % ( datetime.datetime.now().strftime("%d %b %Y"),), verticalalignment="bottom") # Make a logo im = mpimage.imread('%s/%s' % (DATADIR, 'logo.png')) plt.figimage(im, 10, 625) return fig
def __call__(self, clusters): features = self.sink_features.get() if clusters is None or features is None: return None valid = clusters.labels_ != -1 view_data = features[valid] labels = clusters.labels_ valid_labels = labels[valid] if len(valid_labels) == 0: return None choice = np.random.choice(range(len(valid_labels)), size=min(2000, len(valid_labels)), replace=False) view_data = self.reducer.fit(view_data[choice, :]).transform(features) print view_data.shape fig, ax = plt.subplots(figsize=(15, 15), dpi=300) num_clusters = len(set(valid_labels)) patches = [] for l in range(num_clusters): cluster = view_data[labels == l, :] try: hull = ConvexHull(cluster) patches.append(Polygon(cluster[hull.vertices, :])) except: pass p = PatchCollection(patches, cmap=matplotlib.cm.rainbow, alpha=0.4) ax.add_collection(p) invalid = np.invert(valid) plt.scatter(view_data[invalid, 0], view_data[invalid, 1], c='w', s=0.1) ax.set_facecolor('black') plt.scatter(view_data[valid, 0], view_data[valid, 1], c=valid_labels, s=0.1, cmap='rainbow') # Add a few images to the figure choices = [] imgs_per_label = max(1, int(self.num_images / num_clusters)) for l in range(num_clusters): cluster_ind = np.where(labels == l)[0] choices += np.random.choice(cluster_ind, size=min(imgs_per_label, len(cluster_ind)), replace=False).tolist() plt.scatter(view_data[choices, 0], view_data[choices, 1], c=labels[choices], s=180, marker='s', cmap='rainbow') # Get the x and y data and transform it into pixel coordinates xy_pixels = ax.transData.transform( np.vstack([view_data[choices, 0], view_data[choices, 1]]).T) xpix, ypix = xy_pixels.T for i, c in enumerate(choices): img = self.sink_image.get(c) if img is None: continue scale = 50.0 / np.max(img.shape) img = cv2.cvtColor(cv2.resize( img, dsize=(0, 0), fx=scale, fy=scale), code=cv2.COLOR_BGR2RGB).astype(np.float32) / 255 plt.figimage(img, xo=int(xpix[i]) - 25, yo=int(ypix[i]) - 25, zorder=10) pylab.savefig(self.sink_filename.get(), dpi=fig.dpi) plt.close('all')
def make_png(infile, outdir, vmax=None): """ """ # Get Sea Surface Roughness sarim = sarimage(infile) spacing_ra = np.ceil(sarim.get_info('number_of_samples')/600.) spacing_ra_m = sarim.pixels2meters(spacing_ra)[1] spacing = np.round(sarim.meters2pixels(spacing_ra_m)) spacing_m = sarim.pixels2meters(spacing) ssr = sarim.get_data('roughness', spacing=spacing) lon = sarim.get_data('lon', midrange=True, midazimuth=True)[0, 0] lat = sarim.get_data('lat', midrange=True, midazimuth=True)[0, 0] inc = sarim.get_data('incidence', midrange=True, midazimuth=True)[0, 0] heading = sarim.get_info('platform_heading') north = 90 + heading # north dir in image im_num = sarim.get_info('image_number') dist = (np.array(ssr.shape)-1)*spacing_m/1000. # vmin = ssr[ind].min() # vmax = ssr[ind].max() vmin = scoreatpercentile(ssr[25:-25, 25:-25], 0.1) if vmax is None: vmax = scoreatpercentile(ssr[25:-25, 25:-25], 99.9) if sarim.get_info('pass') == 'Descending': ssr = ssr[::-1, ::-1] north = north+180 # Make figure dpi = 100 imsize = np.array(ssr.shape[::-1]) margin = np.array(((900-imsize[0])/2, 60)) figsize = np.array((900, imsize[1]+2*margin[1])) imsizeN = imsize.astype('float')/figsize marginN = margin.astype('float')/figsize #print imsize, margin, figsize fig = plt.figure(figsize=figsize.astype('float')/dpi, dpi=dpi) # imax = fig.gca() # imax.set_position([marginN[0], marginN[1], imsizeN[0], imsizeN[1]]) imax = fig.add_axes([marginN[0], marginN[1], imsizeN[0], imsizeN[1]]) imax.set_xlim(0, dist[1]) imax.set_ylim(0, dist[0]) plt.imshow(ssr, origin='lower', interpolation='nearest', vmin=vmin, vmax=vmax, cmap=cm.get_cmap('Greys_r'), extent=[0, dist[1], 0, dist[0]], aspect='auto') imax.set_xlabel('range distance [km]') imax.set_ylabel('azimuth distance [km]') tit = '#%03i / lon=%.2f / lat=%.2f / inc=%.2f' % (im_num, lon, lat, inc) imax.set_title(tit) #imax.set_frame_on(False) #imax.set_axis_off() # Add colorbar cbax = fig.add_axes([1-0.75*marginN[0], .25, 20./figsize[0], .50]) plt.colorbar(label='sea surface roughness', cax=cbax, format='%.1e') meanstr = r'$\mu$=%.1f' % ssr.mean() cbax.text(0.5, -0.025, meanstr, ha='center', va='top') # Add north cpsizeN = (margin[0]-margin[1])/figsize.astype('float') cpax = fig.add_axes([0., 0.5-cpsizeN[1]/2, cpsizeN[0], cpsizeN[1]]) plt.arrow(.5, .5, .5*np.cos(north*np.pi/180), .5*np.sin(north*np.pi/180), facecolor='black', width=0.01, length_includes_head=True, head_width=0.1, head_length=0.1) plt.annotate('North', (.5, .5), ha='center', va='top') cpax.set_axis_off() # Add Logos python_logo = os.path.join(LOGO_PATH, 'python-powered-w-70x28.png') logo = imread(python_logo) plt.figimage(logo, 5, figsize[1]-logo.shape[0]-5) odl_logo = os.path.join(LOGO_PATH, 'oceandatalab-85x32.png') logo = imread(odl_logo) plt.figimage(logo, 5, 5) # Save as PNG outbase = os.path.splitext(os.path.basename(infile))[0]+'-roughness.png' outfile = os.path.join(outdir, outbase) plt.savefig(outfile, dpi=dpi)#, bbox_inches='tight') plt.close() cmd = 'convert '+outfile+' -colors 256 '+outfile os.system(cmd)
""" This illustrates placing images directly in the figure, with no axes. """ import numpy as np import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt fig = plt.figure() Z = np.arange(10000.0) Z.shape = 100, 100 Z[:, 50:] = 1. im1 = plt.figimage(Z, xo=50, yo=0, origin='lower') im2 = plt.figimage(Z, xo=100, yo=100, alpha=.8, origin='lower') plt.show()
matplotlib.rcParams["font.family"] = "sans-serif" pythonInfo = open('./python_.txt', 'r', encoding='utf-8', errors='ignore') # 切割 myPythonCut = jieba.cut(pythonInfo.read(), cut_all=True) pythonInfo.close() myPythonCut = ' '.join(myPythonCut) # RGB格式矩阵 bg = np.array(Image.open('./bf.jpg')) print(bg) myWordCloud = WordCloud( font_path='./simkai.ttf', # 字体 width=1000, height=600, mask=bg, # 字体颜色 scale=0.6, # 缩放 max_words=300, # 词云最大数量 min_font_size=4, # 最小字体 stopwords=STOPWORDS, # 停止词 random_state=100, # 随机状态 background_color='white', # 背景颜色 ).generate(myPythonCut) # 生成词云 plt.figimage(myWordCloud) # plt.show() # 保存 plt.savefig('python_.jpg')
def plot_streamlines(u, v, xlim=(-1, 1), ylim=(-1, 1)): global COUNTER #define a grid on which to calculate everything Y,X = np.ogrid[y0 - 0.25 * abs(y0):y1 + 0.25 * abs(y1):size*1j, x0 - 0.25 * abs(x0):x1 + 0.25 * abs(x1):size*1j] print "Evaluating the velocity at each grid point..." uu = u(X,Y) #Evaluate the horizontal derivative at each grid point. vv = v(X,Y) #Evaluate the vertical derivative at each grid point. print "Plotting..." #color map for the convolution plot cmap = LinearSegmentedColormap.from_list('name', ['black','white','black','white']) #define the kernel (just a vector of numbers) kernel = np.arange(kernel_density).astype(np.float32) #reshape the velocities to fill in grid squ = np.reshape(uu, (int(size),int(size))).astype(np.float32) sqv = np.reshape(vv, (int(size),int(size))).astype(np.float32) #stack the velocities element-wise so we have a 2-tuple at each grid point. vectors = np.dstack((squ,sqv)).astype(np.float32) #generate the background noise. texture = np.random.rand(size/grain_size,size/grain_size).astype(np.float32) #resize the background noise to the resolution of the image by nearest neighbor interpolation (in order to provide support for larger grain size) texture = scipy.ndimage.zoom(texture, grain_size, order=1) print " Integrating for LIC plot (if this takes too long, try decreasing the kernel_density)" #Do the Line Integral Convolution. image = lic_internal.line_integral_convolution(vectors, texture, kernel) if flip_h: image = np.fliplr(image) if flip_v: image = np.flipud(image) plt.axis('off') plt.figimage(image,cmap=cmap) #calculate the velocities (ie: norm of velocity vector) velocity = np.linalg.norm(vectors, axis=2) #Cap the velocities at 10x the mean velocity (to prevent singularities from #skewing the color map # np.putmask(velocity, velocity>10*np.mean(velocity), 10*np.mean(velocity)) #sqrt the velocities, to make the differences less drastic. velocity = np.sqrt(velocity) theCM = plt.cm.get_cmap('bwr') theCM._init() #oldcm = matplotlib.cm.bwr oldcm = matplotlib.cm.Spectral_r v_at_infty = math.sqrt(u(1e9,1e9)**2 + v(1e9,1e9)**2) scm = cmap_center_point_adjust(oldcm, (np.min(velocity),np.max(velocity)), v_at_infty) if flip_h: velocity = np.fliplr(velocity) if flip_v: velocity = np.flipud(velocity) #plot the heat map dpi=300 imm = plt.figimage(velocity, cmap=scm, alpha=0.5) plt.gcf().set_size_inches((size/float(dpi),size/float(dpi))) plt.savefig("flow-image{0}.png".format(name),dpi=dpi)
s = s0.copy() s[s0 < 10.0] = b[s0 < 10.0] H = s - b L = 750.0 # s(x) and b(x) versus x, with 100x exaggeration plt.figure(figsize=(10, 7)) plt.subplot(2, 1, 1) plt.plot(x, s, 'k', label='$s$') plt.plot(x, b, 'k--', label='$b$') plt.grid(True) plt.xlabel('') plt.ylabel('elevation (m)', fontsize=18.0) plt.xticks(fontsize=14.0) plt.yticks(fontsize=14.0) plt.minorticks_off() plt.axis([0.0, L, -1000.0, 3500.0]) plt.legend(loc='upper left', fontsize=14.0) fig = plt.subplot(2, 1, 2) plt.plot(x, H, 'k') plt.grid(True) plt.xlabel('$x$ (km)', fontsize=18.0) plt.ylabel('$H$ (m)', fontsize=18.0) plt.xticks(fontsize=14.0) plt.yticks(fontsize=14.0) plt.minorticks_off() plt.axis([0.0, L, -100.0, 3500.0]) im = plt.imread('gis/gris-profile-gray.png') # image is 200 pixels tall plt.figimage(im, 135.0, 100.0) # offset in pixels writeout('giscross.pdf')
address_list.append(sub_address_list) combined_distance_list.append(sub_combined_list) # im = Image.open(address_list[5][0]) # plt.figimage(im, 0, 0) # counter = 0 # for item in address_list[5]: # im = Image.open(item) # plt.figimage(im, 400*color_distance_list[5][counter], 300*texture_distance_list[5][counter]) # counter = counter + 1 # plt.show() im = Image.open("images/i06.ppm") plt.figimage(im, 0, 0) counter = 0 for item in address_list[05]: im = Image.open(item) plt.figimage(im, 600*(1-color_distance_list[05][counter]), 1800*(1-texture_distance_list[05][counter])) counter = counter + 1 plt.show()
ax = plt.subplot(2,2,4) ax.imshow(small_im, interpolation = 'nearest') plt.subplots_adjust(left = 0.24, wspace = 0.2, hspace = 0.1, \ bottom = 0.05, top = 0.86) #Label the rows and columns of the table fig.text(0.03, 0.645, 'Big Image\nScaled Down', ha = 'left') fig.text(0.03, 0.225, 'Small Image\nBlown Up', ha = 'left') fig.text(0.383, 0.90, "Interpolation = 'none'", ha = 'center') fig.text(0.75, 0.90, "Interpolation = 'nearest'", ha = 'center') #If you were going to run this example on your local machine, you #would save the figure as a PNG, save the same figure as a PDF, and #then compare them. The following code would suffice. txt = fig.text(0.452, 0.95, 'Saved as a PNG', fontsize = 18) # plt.savefig('None_vs_nearest-png.png') # txt.set_text('Saved as a PDF') # plt.savefig('None_vs_nearest-pdf.pdf') #Here, however, we need to display the PDF on a webpage, which means #the PDF must be converted into an image. For the purposes of this #example, the 'Nearest_vs_none-pdf.pdf' has been pre-converted into #'Nearest_vs_none-pdf.png' at 80 dpi. We simply need to load and #display it. pdf_im_path = cbook.get_sample_data('None_vs_nearest-pdf.png') pdf_im = plt.imread(pdf_im_path) fig2 = plt.figure(figsize = [8.0, 7.5]) plt.figimage(pdf_im) plt.show()
def run(self): if not self.exiting: if not isfile(str(self.bin_directory)+"/lock.bin"): f=open(str(self.bin_directory)+"/lock.bin",'wb') #lock bin file so dataBin cannot access it f.close() datafile = str(self.bin_directory) + "/data.bin" #unpack file sent from organizer that has reorganized the raw data darray = self.unpack_file(datafile) os.remove(str(self.bin_directory)+"/lock.bin") #Break data into counts for energy slices 0-9 self.C0=darray[:,0] self.C1=darray[:,1] self.C2=darray[:,2] self.C3=darray[:,3] self.C4=darray[:,4] self.C5=darray[:,5] self.C6=darray[:,6] self.C7=darray[:,7] self.C8=darray[:,8] self.C9=darray[:,9] #get median energy's for every bin for sky subtraction and SNR calculation self.medians = [median(self.C0),median(self.C1),median(self.C2),median(self.C3),median(self.C4),\ median(self.C5),median(self.C6),median(self.C7),median(self.C8),median(self.C9)] #do sky subtraction from these arrays of counts per pixel in each energy slice if self.sky_subtraction == True: self.subtract_sky(self.medians) for m in range(self.total_pix): self.pc[m]=self.C0[m]+self.C1[m]+self.C2[m]+self.C3[m]+self.C4[m]+self.C5[m]+self.C6[m]+\ self.C7[m]+self.C8[m]+self.C9[m] self.calc_mean_energy() if self.simple_imaging == False: self.satpercent = 0.10 #default to 0.10 im = make_image_import(self.pc, self.me, self.color_on,self.satpercent) im.save("TV_frame.bmp") else: print "Reshaping image from ", shape(self.pc), photon_count = array(self.pc) photon_count = photon_count.reshape(32,32) photon_count = flipud(photon_count) print " to ", shape(photon_count) fig = plt.figure(figsize=(.32,.32), dpi=100, frameon=False) im = plt.figimage(photon_count, cmap='gray') plt.savefig("TV_frame.png", pad_inches=0) if self.spectrum_pixel != []: totalcounts = [0,0,0,0,0,0,0,0,0,0] for p in self.spectrum_pixel: counts = [self.C0[p],self.C1[p],self.C2[p],self.C3[p],self.C4[p],self.C5[p],self.C6[p],\ self.C7[p],self.C8[p],self.C9[p]] for i in range(len(counts)): totalcounts[i] += counts[i] #calculate SNR self.calculate_SNR(totalcounts, self.medians, len(self.spectrum_pixel)) if self.plot_mode == "spectra": self.make_spectrum(median(self.spectrum_pixel),totalcounts) else: self.make_spectrum(median(self.spectrum_pixel),self.SNR) pylab.clf() self.imaging = False else: print "lock is in place on bin file, cannot image" time.sleep(0.1) self.emit(SIGNAL("retry_image()"))
def plotCrop(variableFolder, crop): print crop filename = crop + '.tiff.nc' #datafile = Dataset(variablePath + variableFolder + filename) datafile = Dataset(variablePath + filename) data = datafile.variables['Band1'][:] lats = datafile.variables['lat'][:] lons = datafile.variables['lon'][:] d2 = ma.masked_where(data <= 1, data) df = pd.DataFrame(d2) s = df.unstack() s_one = s[~np.isnan(s)] if len(s_one) == 0 : return jc = br.Jenks_Caspall(s_one, k = 8) for i in range(0,len(jc.bins)): if len(str(int(jc.bins[i]))) >= 3: jc.bins[i] = np.round(jc.bins[i] / 100.0 ,0) * 100 if 'harvested' in variableFolder: bmap = sequential.Oranges[7]; unitLabel = 'ha'; parentFolder = 'quickstart_harvested'; variableName = 'Harvested Area'; if 'area' in variableFolder: bmap = sequential.Oranges[7]; unitLabel = 'ha'; parentFolder = 'quickstart_area'; variableName = 'Physical Area'; if 'yield' in variableFolder: bmap = sequential.YlGnBu[7]; unitLabel = 'kg/ha'; parentFolder = 'quickstart_yield'; variableName = 'Yield'; if 'prod' in variableFolder: bmap = sequential.Greens[7]; unitLabel = 'mt'; parentFolder = 'quickstart_prod'; variableName = 'Production'; cropArr = crop.split('_'); if len(cropArr) == 1: technologyName = 'Total' else: if cropArr[1] == 'r': technologyName = 'Rainfed' else: technologyName = 'Irrigated' cropName = cropList[cropList['varCode'] == cropArr[0]].varName.values[0] cmap = bmap.get_mpl_colormap(N=256) figTitle = cropName + ' ' + technologyName + ' ' + variableName + ' (' + unitLabel + ')' plt.close() plt.figtext(0.025,0.92, figTitle, clip_on = 'True', size = 'large', weight = 'semibold'); plt.figtext(0.025,0.86,'Spatially disaggregated production statistics of circa 2005 using the Spatial Production Allocation Model (SPAM).', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium'); plt.figtext(0.025,0.835,'Values are for 5 arc-minute grid cells.', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium'); plt.figtext(0.025,0.072, 'You, L., U. Wood-Sichra, S. Fritz, Z. Guo, L. See, and J. Koo. 2014', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium') plt.figtext(0.025,0.051, 'Spatial Production Allocation Model (SPAM) 2005 Beta Version.', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium') plt.figtext(0.025,0.030, '08.15.2014. Available from http://mapspam.info', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium'); logos = Image.open('/home/mcomanescu/logos/spam_logos2.png') #logos = Image.open('/Users/maria/Projects/tests/results/spam_logos2.png') plt.figimage(logos,1830, 100) #map = Basemap(projection='merc',resolution='i', epsg=4326, lat_0 = 0, lon_0 = 20) map = Basemap(projection='merc',resolution='l', epsg=4326, lat_0 = 0, lon_0 = 20, llcrnrlon=-160, llcrnrlat=-70, urcrnrlon=200, urcrnrlat=90) cs = map.pcolormesh(lons, lats, d2, cmap=cmap, norm=BoundaryNorm(jc.bins, 256, clip=True)) map.drawlsmask(land_color='#fafafa', lakes = True) map.drawcountries(linewidth=0.05) map.drawcoastlines(linewidth=0.05) cbar = map.colorbar(cs,location='bottom', pad='3%') #cbar.ax.set_xlabel(unitLabel, fontsize = 'x-small'); labels = [item.get_text() for item in cbar.ax.get_xticklabels()] labels[0] = '1'; labels[6] = labels[6] + ' <'; labels[7] = '' cbar.ax.set_xticklabels(labels) plt.tight_layout(h_pad=0.9, w_pad = 0.9) plt.savefig('/home/tmp/png/' + parentFolder + '/' + crop + '.png', format='png', dpi=400)
technologyName = 'Irrigated' res = result_r technologyName = 'Rainfed' figTitle = cropName + ' ' + technologyName + ' ' + variableName + ' (' + unitLabel + ')' plt.close() plt.figtext(0.025,0.92, figTitle, clip_on = 'True', size = 'large', weight = 'semibold'); plt.figtext(0.025,0.86, 'Spatially disaggregated production statistics of circa 2005 using the Spatial Production Allocation Model (SPAM).', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium'); plt.figtext(0.025,0.835,'Values are for 5 arc-minute grid cells.', clip_on = 'True', size = 'x-small', stretch = 'semi-condensed', weight = 'medium'); plt.figtext(0.025,0.072, 'You, L., U. Wood-Sichra, S. Fritz, Z. Guo, L. See, and J. Koo. 2014', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium') plt.figtext(0.025,0.051, 'Spatial Production Allocation Model (SPAM) 2005 Version 2.0.', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium') plt.figtext(0.025,0.030, '03.10.2015. Available from http://mapspam.info', clip_on = 'True', size = 'xx-small', stretch = 'semi-condensed', weight = 'medium'); plt.figimage(logos, 4100, 200) map = Basemap(projection='merc',resolution='i', epsg=4326, lat_0 = 0, lon_0 = 20, llcrnrlon=-160, llcrnrlat=-70, urcrnrlon=200, urcrnrlat=90) map.drawlsmask(land_color='#fffff0', lakes = False, zorder = 1) shp_coast = map.readshapefile(baseShpLoc + '/ne_50m_coastline/ne_50m_coastline', 'scalerank', drawbounds=True, linewidth=0.1, color = '#828282', zorder = 7) shp_rivers = map.readshapefile(baseShpLoc + '/ne_110m_rivers_lake_centerlines/ne_110m_rivers_lake_centerlines', 'scalerank', drawbounds=True, color='#e8f8ff', linewidth=0.1, zorder = 5) shp_lakes = map.readshapefile(baseShpLoc + '/ne_110m_lakes/ne_110m_lakes', 'scalerank', drawbounds=True, linewidth=0.1, color='#e8f8ff', zorder=4) paths = [] for line in shp_lakes[4]._paths: paths.append(matplotlib.path.Path(line.vertices, codes=line.codes)) coll_lakes = matplotlib.collections.PathCollection(paths, linewidths=0, facecolors='#e8f8ff', zorder=3) cs = map.pcolormesh(res.lons, res.lats, res.d2, cmap=cmap, norm=BoundaryNorm(bins, 256, clip=True), zorder = 6) map.drawcountries(linewidth=0.1, color='#828282', zorder = 8)
def _make_plot(station, df, units, nsector, rmax, hours, months, sname, level, bins): """Generate a matplotlib windrose plot Args: station (str): station identifier df (pd.DataFrame): observations drct (list): list of wind directions units (str): units of wind speed nsector (int): number of bins to use for windrose rmax (float): radius of the plot hours (list): hour limit for plot month (list): month limit for plot sname (str): station name level (int): RAOB level in hPa of interest bins (list): values for binning the wind speeds Returns: matplotlib.Figure """ # Generate figure fig = plt.figure(figsize=(8, 8), dpi=100, facecolor='w', edgecolor='w') rect = [0.15, 0.15, 0.7, 0.7] ax = WindroseAxes(fig, rect, facecolor='w', rmax=rmax) fig.add_axes(ax) wu = WINDUNITS[units] if level is None else RAOB_WINDUNITS[units] if bins: wu['bins'] = bins wu['binlbl'] = [] for i, mybin in enumerate(bins[1:-1]): wu['binlbl'].append("%g-%g" % (mybin, bins[i + 2])) wu['binlbl'].append("%g+" % (bins[-1], )) # Filters the missing values df2 = df[df['drct'] >= 0] try: # Unsure why this bombs out sometimes ax.bar(df2['drct'].values, df2['speed'].values, normed=True, bins=wu['bins'], opening=0.8, edgecolor='white', nsector=nsector) except Exception as exp: pass handles = [] for p in ax.patches_list: color = p.get_facecolor() handles.append( plt.Rectangle((0, 0), 0.1, 0.3, facecolor=color, edgecolor='black')) l = fig.legend(handles, wu['binlbl'], bbox_to_anchor=(0.01, 0.01, 0.98, 0.09), loc='center', ncol=6, title='Wind Speed [%s]' % (wu['abbr'], ), mode=None, columnspacing=0.9, handletextpad=0.45, fontsize=14) plt.setp(l.get_texts(), fontsize=10) # Now we put some fancy debugging info on the plot tlimit = "Time Domain: " if len(hours) == 24 and len(months) == 12: tlimit = "All Year" if len(hours) < 24: if len(hours) > 4: tlimit += "%s-%s" % ( datetime.datetime(2000, 1, 1, hours[0]).strftime("%-I %p"), datetime.datetime(2000, 1, 1, hours[-1]).strftime("%-I %p")) else: for h in hours: tlimit += "%s," % (datetime.datetime(2000, 1, 1, h).strftime("%-I %p"), ) if len(months) < 12: for h in months: tlimit += "%s," % (datetime.datetime(2000, h, 1).strftime("%b"), ) label = """[%s] %s%s Windrose Plot [%s] Period of Record: %s - %s""" % ( station, sname if sname is not None else "((%s))" % (station, ), "" if level is None else " @%s hPa" % (level, ), tlimit, df['valid'].min().strftime("%d %b %Y"), df['valid'].max().strftime("%d %b %Y")) plt.gcf().text(0.14, 0.99, label, va='top', fontsize=14) plt.gcf().text( 0.96, 0.11, ("Summary\nn: %s\nMissing: %s\nCalm: %.1f%%\nAvg Speed: %.1f %s") % (len(df.index), len(df.index) - len(df2.index), len(df[df['sknt'] == 0].index) / float(len(df2.index)) * 100., df['speed'].mean(), wu['abbr']), ha='right', fontsize=14) plt.gcf().text(0.01, 0.11, "Generated: %s" % (datetime.datetime.now().strftime("%d %b %Y"), ), verticalalignment="bottom", fontsize=14) # Make a logo im = mpimage.imread('%s/%s' % (DATADIR, 'logo.png')) plt.figimage(im, 10, 735) return fig
return np.concatenate((np.arange(L), np.ones(2*L+1, dtype=np.int64)*L, np.arange(L-1,-L,-1), np.ones(2*L+1, dtype=np.int64)*-L, np.arange(1-L,0))) count = 1 arr = np.ones((layers*2-1,layers*2-1), dtype=np.uint32) for layer in range(1, layers): # Generate the Y indices for the layer and offset based on the center coordinates sequenceY = getsequence(layer) + layers - 1 # Offset X indices from the generated Y sequenceX = np.roll(sequenceY, -2*layer) # Assign incremental values to the indices in order for x, y in zip(sequenceX, sequenceY): count += 1 arr[x,y] = count return arr if __name__ == '__main__': # Testing import matplotlib.pyplot as plt layers = 100 a = spiral(layers) for x in range(layers*2-1): for y in range(layers*2-1): a[x,y] = isprime(a[x,y]) plt.figimage(a*255) plt.show()
""" See pcolor_demo2 for a much faster way of generating pcolor plots """ import numpy as np import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt fig = plt.figure(frameon=False) Z = np.arange(10000.0) Z.shape = 100,100 Z[:,50:] = 1. im1 = plt.figimage(Z, xo=50, yo=0, cmap=cm.jet) im2 = plt.figimage(Z, xo=100, yo=100, alpha=.8, cmap=cm.jet) plt.show()
def etape(self): self._croissance() if __name__ == "__main__": # monEnv = Carte(1366, 768) monEnv = Carte(720, 720, echelle=10) monEnv.generer_carte() monEnv.generer_image() monEnv.generer_matrices() monEnv.poser_tribu(4) monEnv.generer_matrice_tribus() monEnv.mise_a_jour() dpi = 96 figsize = monEnv.img_carte.size[0] / float(dpi), monEnv.img_carte.size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi, facecolor=(10/255, 65/255, 145/255)) fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False) plt.figimage(monEnv.img_carte) im = plt.imshow(monEnv.img_transp, cmap=monEnv.colormap_indiv, norm=monEnv.norm, interpolation='nearest', animated=True) def updatefig(*args): monEnv.mise_a_jour() im.set_array(monEnv.img_transp) return im, ani = anim.FuncAnimation(fig, updatefig, interval=100) plt.show()
""" This illustrates placing images directly in the figure, with no axes. """ import numpy as np import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt fig = plt.figure() Z = np.arange(10000.0) Z.shape = 100,100 Z[:,50:] = 1. im1 = plt.figimage(Z, xo=50, yo=0, cmap=cm.jet, origin='lower') im2 = plt.figimage(Z, xo=100, yo=100, alpha=.8, cmap=cm.jet, origin='lower') plt.show()
im_src = imread('input_car.png').astype(dtype=np.uint16) shape_dst = (im_src.shape[0] * SCALE_FACTOR, im_src.shape[1] * SCALE_FACTOR) im_dst = np.empty(shape=shape_dst, dtype=np.uint16) src_buff = cl.image_from_array(context, im_src, mode='r') dst_buff = cl.image_from_array(context, im_dst, mode='w') # Enqueue kernel # Note: Global indices is reversed due to OpenCL using column-major order when reading images global_size = im_src.shape[::-1] local_size = None # __call__(queue, global_size, local_size, *args, global_offset=None, wait_for=None, g_times_l=False) prog.interp(queue, global_size, local_size, src_buff, dst_buff) # Enqueue command to copy from buffers to host memory # Note: Region indices is reversed due to OpenCL using column-major order when reading images cl.enqueue_copy(queue, dest=im_dst, src=dst_buff, is_blocking=True, origin=(0, 0), region=im_dst.shape[::-1]) # Plot images with built-in scaling disabled plt.figure() plt.figimage(im_src, cmap='gray', vmin=0, vmax=np.iinfo(np.uint16).max) plt.figure() plt.figimage(im_dst, cmap='gray', vmin=0, vmax=np.iinfo(np.uint16).max) plt.show()
plt.text(extent[2] + lon_difference * 0.2, extent[1] + lat_difference * 0.5, ColorBarLabel, verticalalignment='center', rotation="vertical", color='black', size=10) # Add logos / images to the plot logo_Lamce = plt.imread( "/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Logos/logo_lamce_RJ.png" ) logo_Baia = plt.imread( "/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Logos/baia_logo_RJ.png" ) plt.figimage(logo_Lamce, 700, 10, zorder=3, alpha=1, origin='upper') plt.figimage(logo_Baia, 70, 0, zorder=3, alpha=1, origin='upper') # Save the result as a JPG # Format: sistconvectivos_rj_${ano}${mes}${dia}_${hora}15.jpg fileName = "" if minute == 0: fileName = 'sistconvectivos_rj' + '_' + str(year) + str(month) + str( day) + '_' + hora + minutoZero plt.savefig( '/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Output/RegiaoSerraMetro/' + fileName + '.jpg', dpi=DPI, pad_inches=0, bbox_inches='tight', transparent=True)
def netcdf2png(url, colormapPath, colormapName, dirDest, lat_name, lon_name, data_name, geos=False): # Dataset is the class behavior to open the file # and create an instance of the ncCDF4 class nc_fid = netCDF4.Dataset(url, 'r') # extract/copy the data data = nc_fid.variables[data_name][0] X_mat = nc_fid.variables[lon_name][:] Y_mat = nc_fid.variables[lat_name][:] X = X_mat[0] # longitud, eje X Y = numpy.transpose(Y_mat)[0] nc_fid.close() # xc, size: 976, lon # yc, size: 453, lat # print X # print Y print data print len(X) print len(Y) # mpl_toolkits.basemap.interp(datain, xin, yin, xout, yout, checkbounds=False, masked=False, order=1)¶ # http://earthpy.org/interpolation_between_grids_with_basemap.html # a lon sumarle 2 # a lat restarle 1 # X = X[::4] # Y = Y[::4] # seteo los minimos y maximos de la imagen en funcion de los min y max de lat y long # axes = plt.gca() # axes.set_xlim([min_lon, max_lon]) # axes.set_ylim([min_lat, max_lat]) name = basename(url) banda = name[23:30] yyyy = name[7:11] doy = name[12:15] hh = name[16:18] mm = name[18:20] ss = name[20:22] yyyy, mt, dd = ymd(int(yyyy), int(doy)) note_name = banda + " " + str(dd).zfill(2) + "-" + str(mt).zfill( 2) + "-" + str(yyyy) + " " + hh + ":" + mm print name print note_name band_num = int(banda[-1]) print band_num # if banda == 'BAND_04': # data /= numpy.amax(data) # data *= 100 # elif banda == 'BAND_01': # data /= numpy.amax(data) # data *= 100 # data /= numpy.amax(data) # data *= 100 zona = 'plata' if zona == 'plata' and not geos: # proyecto con mercator en la región del río de la plata print "Ventana Río de la Plata" X_mat = map(lambda x: x + 0.05, X_mat) # incremento X lon, positivos mueven -> Y_mat = map(lambda y: y + 0.04, Y_mat) # restarle Y lat, positivos mueven ^ shape = (len(Y), len(X)) # guardo el shape original de data # data_vector = numpy.reshape(data,numpy.size(data)) # genero un vector de data usando su size (largo*ancho) data = calibrarData(band_num, data) # invoco la funcion sobre el vector img = numpy.reshape( data, shape) # paso el vector a matriz usando shape como largo y ancho print img.shape # Región ax = Basemap(projection='merc',\ llcrnrlat=-42.94,urcrnrlat=-22.0,\ llcrnrlon=-67.0,urcrnrlon=-45.04,\ resolution='f') # ax = Basemap(projection='merc',\ # llcrnrlat=-80,urcrnrlat=80,\ # llcrnrlon=-179,urcrnrlon=179,\ # resolution='f') print numpy.amin(img) print numpy.amax(img) X_mat = numpy.reshape(X_mat, shape) Y_mat = numpy.reshape(Y_mat, shape) # lons, lats = numpy.meshgrid(X_mat,Y_mat) x, y = ax(X_mat, Y_mat) # end if # agrego los vectores de las costas, departamentos/estados/provincias y paises ax.drawcoastlines(linewidth=0.25) ax.drawcountries(linewidth=0.50) ax.drawstates(linewidth=0.25) if not geos: # dibujo los valores de latitudes y longitudes al margen de la imagen par = ax.drawparallels(numpy.arange(-45, -20, 5), labels=[1, 0, 0, 0], linewidth=0.0, fontsize=10, color='white') mer = ax.drawmeridians(numpy.arange(-70, -45, 5), labels=[0, 0, 1, 0], linewidth=0.0, fontsize=10, color='white') setcolor(par, 'white') setcolor(mer, 'white') # llamo al garbage collector para que borre los elementos que ya no se van a usar gc.collect() # vmin = 0 # vmax = 100 vmin, vmax = rangoColorbar(banda) img = numpy.ma.masked_where(numpy.isnan(img), img) # dibujo img en las coordenadas x e y calculadas # cmap = gmtColormap(colormapName, colormapPath, 2048) ticks = [0, 20, 40, 60, 80, 100] ticksLabels = ticks # defino el colormap y la disposicion de los ticks segun la banda if banda == 'BAND_01' or banda == 'BAND_02' or banda == 'BAND_03': ticks = [0, 20, 40, 60, 80, 100] ticksLabels = ticks else: ticks = [ -80, -75.2, -70.2, -65.2, -60.2, -55.2, -50.2, -45.2, -40.2, -35.2, -30.2, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70 ] ticksLabels = [ -80, -75, -70, -65, -60, -55, -50, -45, -40, -35, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70 ] # if FR o RP cmap = gmtColormap(colormapName, colormapPath, 2048) cs = ax.pcolormesh(x, y, img, vmin=vmin, vmax=vmax, cmap=cmap) # seteo los limites del colorbar plt.clim(vmin, vmax) # agrego el colorbar cbar = ax.colorbar(cs, location='bottom', pad='3%', ticks=ticks) cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white') if banda == 'BAND_01' or banda == 'BAND_02' or banda == 'BAND_03': cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white') else: cbar.ax.set_xticklabels(ticksLabels, rotation=45, fontsize=7, color='white') cbar.ax.set_xlabel("Temperatura de brillo ($^\circ$C)", fontsize=7, color='white') # if banda != 'C02': # cbar.ax.xaxis.labelpad = 0 # agrego el logo en el documento logo = plt.imread('./logo_300_bw.png') plt.figimage(logo, 5, 5) # si estoy dibujando toda la proyección geos adjunto el string al nombre del archivo if geos: destFile = dirDest + name + '_geos.png' # determino el nombre del archivo a escribir else: destFile = dirDest + name + '.png' # determino el nombre del archivo a escribir # llamo al garbage collector para que borre los elementos que ya no se van a usar gc.collect() print destFile # genero el pie de la imagen, con el logo y la info del archivo plt.annotate(note_name, (0, 0), (106, -60), xycoords='axes fraction', textcoords='offset points', va='top', fontsize=14, family='monospace', color='white') plt.savefig(destFile, bbox_inches='tight', dpi=200, transparent=True) # , facecolor='#4F7293' plt.close()
print('Build log:') print(prog.get_build_info(dev, cl.program_build_info.LOG)) raise # Data and buffers im_src = imread('input_car.png').astype(dtype=np.uint16) shape_dst = (im_src.shape[0]*SCALE_FACTOR, im_src.shape[1]*SCALE_FACTOR) im_dst = np.empty(shape=shape_dst, dtype=np.uint16) src_buff = cl.image_from_array(context, im_src, mode='r') dst_buff = cl.image_from_array(context, im_dst, mode='w') # Enqueue kernel # Note: Global indices is reversed due to OpenCL using column-major order when reading images global_size = im_src.shape[::-1] local_size = None # __call__(queue, global_size, local_size, *args, global_offset=None, wait_for=None, g_times_l=False) prog.interp(queue, global_size, local_size, src_buff, dst_buff) # Enqueue command to copy from buffers to host memory # Note: Region indices is reversed due to OpenCL using column-major order when reading images cl.enqueue_copy(queue, dest=im_dst, src=dst_buff, is_blocking=True, origin=(0, 0), region=im_dst.shape[::-1]) # Plot images with built-in scaling disabled plt.figure() plt.figimage(im_src, cmap='gray', vmin=0, vmax=np.iinfo(np.uint16).max) plt.figure() plt.figimage(im_dst, cmap='gray', vmin=0, vmax=np.iinfo(np.uint16).max) plt.show()
u = g_grid_mean_array_u #.flatten() v = g_grid_mean_array_v #.flatten() #fig = plt.figure() ''' plt.streamplot(xv, yv, u, v, density=5, linewidth=None, \ color='black', cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', transform=None) #ax = fig.add_subplot(1,1,1) #ax.yaxis.grid(color=None)#, linestyle='dashed') #ax.xaxis.grid(color=None)#, linestyle='dashed') plt.show() ''' kernellen = 31 kernel = np.sin(np.arange(kernellen) * np.pi / kernellen) kernel = kernel.astype(np.float32) print 'going into lic_internal' image = lic_internal.line_integral_convolution(vectors, texture, kernel) #plt.imshow(image) #plt.show() dpi = 100 plt.clf() plt.axis('off') plt.figimage(image) plt.gcf().set_size_inches((size / float(dpi), size / float(dpi))) plt.show() #if __name__ == '__main__': # main()
extent[1] + lat_difference * 0.5, ColorBarLegend, verticalalignment='center', rotation="vertical", color='black', size=15) # Add logos / images to the plot logo_Lamce = plt.imread( "/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Logos/logo_lamce_RJ.png" ) logo_Baia = plt.imread( "/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Logos/baia_logo_RJ.png" ) plt.figimage(logo_Lamce, 1300, 60, zorder=3, alpha=1, origin='upper') plt.figimage(logo_Baia, 120, 60, zorder=3, alpha=1, origin='upper') # Save the result as a JPG # Format: sistconvectivos_rj_${ano}${mes}${dia}_${hora}15.jpg fileName = "" if minute == 0: fileName = 'sistconvectivos_rj' + '_' + str(year) + str(month) + str( day) + '_' + hora + minutoZero plt.savefig( '/home/cendas/GOES16_WS_Rodrigo/CloudTopTemperature/Output/RJ/ConvectiveSystem/' + fileName + '.jpg', dpi=DPI, pad_inches=0, bbox_inches='tight', transparent=True)
def plotter(slice_list, colour_map_list, file_name=None, overlay_alpha=1.0, intensity_range=None, enhance=1.0): """ This is the background plotting function that does the actual plotting of images. :param slice_list: List of 2D images with the same size. The first image [0] will be plotted in the background :param colour_map_list: List of colour maps. The first colour map corresponds to the first image. The number of colour maps should match the number of slices in slice_list :param file_name: Full path with file name for writing the image to. If set to None (default), the image is not saved to file, but displayed in a separate window instead. :param overlay_alpha: Transparency of overlay images, i.e. the second, third etc. images in the slice list. :param intensity_range: Intensity range for the intensities in the plot. :return: None """ from skimage.transform import rescale # Determine whether the image should be plotted or written if file_name is None: display_frame = True else: display_frame = False # Determine width and height of the figure dpi = 72 fig_width = slice_list[0].shape[1] / dpi fig_height = (slice_list[0].shape[0]) / dpi # Create figure fig = plt.figure(frameon=display_frame, dpi=dpi, figsize=(fig_width, fig_height)) # Create image list im_list = [] # Iterate over slices, starting with the first slice for ii in np.arange(len(slice_list)): # Determine transparency. The first image is always opaque. if ii == 0: curr_alpha = 1.0 else: curr_alpha = overlay_alpha # Add images to figure if ii == 0 and intensity_range is not None: im_list.append( plt.figimage(rescale(image=slice_list[ii], scale=enhance, anti_aliasing=False, multichannel=False, mode="edge"), cmap=plt.get_cmap(colour_map_list[ii]), alpha=curr_alpha, vmin=intensity_range[0], vmax=intensity_range[1], resize=True)) else: im_list.append( plt.figimage(rescale(image=slice_list[ii], scale=enhance, anti_aliasing=False, multichannel=False, order=0, mode="edge"), cmap=plt.get_cmap(colour_map_list[ii]), alpha=curr_alpha, resize=True)) # Show figure if display_frame: plt.show() # Save figure to file if not display_frame: plt.savefig(file_name, pad_inches=0.0, bbox_inches='tight') # Close figure plt.close()