Python pylab.array() Examples

The following are 19 code examples of pylab.array(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pylab , or try the search function .
Example #1
Source File: PiScope.py    From PiScope with MIT License 6 votes vote down vote up
def draw(self):
    self.read() #read current values
    #self.read_test() #testing reading
    print "Plotting..."
    if len(self.channels) == 1:
      NumberSamples = min(len(self.values), self.scale1.get())
      CurrentXAxis = pylab.arange(len(self.values) - NumberSamples, len(self.values), 1)
      self.line1[0].set_data(CurrentXAxis, pylab.array(self.values[-NumberSamples:]))
      self.ax.axis([CurrentXAxis.min(), CurrentXAxis.max(), 0, 3.5])
    elif len(self.channels) == 2:
      NumberSamplesx = min(len(self.valuesx), self.scale1.get())
      NumberSamplesy = min(len(self.valuesy), self.scale1.get())
      self.line1[0].set_data(pylab.array(self.valuesx[-NumberSamplesx:]), pylab.array(self.valuesy[-NumberSamplesy:]))
    self.drawing.draw()
    self.root.after(25, self.draw)
    return 
Example #2
Source File: preprocess.py    From jama16-retina-replication with MIT License 6 votes vote down vote up
def _increase_contrast(image):
    """
    Helper function for increasing contrast of image.
    """
    # Create a local copy of the image.
    copy = image.copy()

    maxIntensity = 255.0
    x = arange(maxIntensity)

    # Parameters for manipulating image data.
    phi = 1.3
    theta = 1.5
    y = (maxIntensity/phi)*(x/(maxIntensity/theta))**0.5

    # Decrease intensity such that dark pixels become much darker,
    # and bright pixels become slightly dark.
    copy = (maxIntensity/phi)*(copy/(maxIntensity/theta))**2
    copy = array(copy, dtype=uint8)

    return copy 
Example #3
Source File: ocrd_anybaseocr_dewarp.py    From ocrd_anybaseocr with Apache License 2.0 6 votes vote down vote up
def _process_segment(self, model, dataset, page, page_xywh, page_id, input_file, orig_img_size, n):
        for i, data in enumerate(dataset):
            w,h = orig_img_size
            generated = model.inference(data['label'], data['inst'], data['image'])
            dewarped = array(generated.data[0].permute(1,2,0).detach().cpu())
            bin_array = array(255*(dewarped>ocrolib.midrange(dewarped)),'B')
            dewarped = ocrolib.array2pil(bin_array)
            dewarped = dewarped.resize((w,h))                        
            
            page_xywh['features'] += ',dewarped'  
            
            file_id = input_file.ID.replace(self.input_file_grp, self.image_grp)
            if file_id == input_file.ID:
                file_id = concat_padded(self.image_grp, n)
        
            file_path = self.workspace.save_image_file(dewarped,
                                   file_id,
                                   page_id=page_id,
                                   file_grp=self.image_grp,
                                   force=self.parameter['force']
                )     
            page.add_AlternativeImage(AlternativeImageType(filename=file_path, comments=page_xywh['features'])) 
Example #4
Source File: _spline.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, max_y_splines=100, simple=0):
        # create this class, then add spline curves to it    

        # the splines are stored in a dictionary with the key
        # as the parameter and the value is the spline_single
        self.x_splines = {}   # supplied by you
        self.y_splines = [{},{},{},{},{}] # generated by this class, index is x-derivative
        self.max_y_splines = max_y_splines # this sets the minimum x_parameter spacing of the y-splines
        self.xmin = None      # set the minimum and maximum values over which this is valid
        self.xmax = None
        self.ymin = None
        self.ymax = None
        self.xlabel = None
        self.ylabel = None
        self.zlabel = None
        self._path = "(spline array not saved)"
        self.simple=simple 
Example #5
Source File: plotutils.py    From pyoptools with GNU General Public License v3.0 6 votes vote down vote up
def spot_diagram_c(s):
    """Plot the spot diagram for the given surface, or element using
    the rays colors.

    Args:
        s: Object (usually :class:`~pyoptools.raytrace.comp_lib.CCD`)
            whose spot diagram will be plotted.
 
    """
    hl=s.hit_list
    X=[]
    Y=[]
    COL=[]
    if len(hl) >0:
        for i in hl:
            p=i[0]
            # Hitlist[1] points to the incident ray
            col=wavelength2RGB(i[1].wavelength)
            plot(p[0],p[1],"o",color=col)
            #X.append(p[0])
            #Y.append(p[1])
            #COL.append(col)
    #max=array(X+Y).max
    #min=array(X+Y).min
    axis("equal") 
Example #6
Source File: plotutils.py    From pyoptools with GNU General Public License v3.0 6 votes vote down vote up
def spot_diagram(s):
    """Plot the spot diagram for the given surface, or element.

    Args:
        s: Object (usually :class:`~pyoptools.raytrace.comp_lib.CCD`)
            whose spot diagram will be plotted.
    """
    hl=s.hit_list
    X=[]
    Y=[]
    COL=[]
    if len(hl) >0:
        for i in hl:
            p=i[0]
            # Hitlist[1] points to the incident ray
            col=wavelength2RGB(i[1].wavelength)
            X.append(p[0])
            Y.append(p[1])
            COL.append(col)
    max=array(X+Y).max
    min=array(X+Y).min
    plot(X,Y,"o",)
    axis("equal") 
Example #7
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def scale_x(scale, axes="current"):
    """

    This function scales lines horizontally.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            line.set_xdata(_pylab.array(line.get_xdata())*scale)

    # update the title
    title = axes.title.get_text()
    title += ", x_scale="+str(scale)
    axes.title.set_text(title)

    # zoom to surround the data properly
    auto_zoom() 
Example #8
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def shift(xshift=0, yshift=0, progressive=0, axes="gca"):
    """

    This function adds an artificial offset to the lines.

    yshift          amount to shift vertically
    xshift          amount to shift horizontally
    axes="gca"      axes to do this on, "gca" means "get current axes"
    progressive=0   progressive means each line gets more offset
                    set to 0 to shift EVERYTHING

    """

    if axes=="gca": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for m in range(0,len(lines)):
        if isinstance(lines[m], _mpl.lines.Line2D):
            # get the actual data values
            xdata = _n.array(lines[m].get_xdata())
            ydata = _n.array(lines[m].get_ydata())

            # add the offset
            if progressive:
                xdata += m*xshift
                ydata += m*yshift
            else:
                xdata += xshift
                ydata += yshift

            # update the data for this line
            lines[m].set_data(xdata, ydata)

    # zoom to surround the data properly

    auto_zoom() 
Example #9
Source File: lineshape_analysis.py    From quantum-python-lectures with MIT License 5 votes vote down vote up
def voigt(x,c1,w1,c2,w2):
	""" Voigt function: convolution of Lorentzian and Gaussian.
		Convolution implemented with the FFT convolve function in scipy.
		NOT NORMALISED """
	
	### Create larger array so convolution doesn't screw up at the edges of the arrays
	# this assumes nicely behaved x-array...
	# i.e. x[0] == x.min() and x[-1] == x.max(), monotonically increasing
	dx = (x[-1]-x[0])/len(x)
	xp_min = x[0] - len(x)/3 * dx
	xp_max = x[-1] + len(x)/3 * dx
	xp = linspace(xp_min,xp_max,3*len(x))
	
	L = lorentzian(xp,c1,w1)
	G = gaussian(xp,c2,w2)
	
	#convolve
	V = conv(L,G,mode='same')
	
	#normalise to unity height !!! delete me later !!!
	V /= V.max()
	
	#create interpolation function to convert back to original array size
	fn_out = interp(xp,V)
	
	return fn_out(x) 
Example #10
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_yticks(start, step, axes="gca"):
    """
    This will generate a tick array and apply said array to the axis
    """
    if axes=="gca": axes = _pylab.gca()

    # first get one of the tick label locations
    xposition = axes.yaxis.get_ticklabels()[0].get_position()[0]

    # get the bounds
    ymin, ymax = axes.get_ylim()

    # get the starting tick
    nstart = int(_pylab.floor((ymin-start)/step))
    nstop  = int(_pylab.ceil((ymax-start)/step))
    ticks = []
    for n in range(nstart,nstop+1): ticks.append(start+n*step)

    axes.set_yticks(ticks)

    # set the x-position
    for t in axes.yaxis.get_ticklabels():
        x, y = t.get_position()
        t.set_position((xposition, y))

    _pylab.draw() 
Example #11
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def scale_y(scale, axes="current", lines="all"):
    """

    This function scales lines vertically.
    You can specify a line index, such as lines=0 or lines=[1,2,4]

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            line.set_ydata(_pylab.array(line.get_ydata())*scale)

    # update the title
    title = axes.title.get_text()
    if not title == "":
        title += ", y_scale="+str(scale)
        axes.title.set_text(title)


    # zoom to surround the data properly
    auto_zoom() 
Example #12
Source File: PiScope.py    From PiScope with MIT License 5 votes vote down vote up
def setup(self, channels):
    print "Setting up the channels..."
    self.channels = channels
    # Setup oscilloscope window
    self.root = Tkinter.Tk()
    self.root.wm_title("PiScope")
    if len(self.channels) == 1:
      # Create x and y axis
      xAchse = pylab.arange(0, 4000, 1)
      yAchse = pylab.array([0]*4000)
      # Create the plot
      fig = pylab.figure(1)
      self.ax = fig.add_subplot(111)
      self.ax.set_title("Oscilloscope")
      self.ax.set_xlabel("Time")
      self.ax.set_ylabel("Amplitude")
      self.ax.axis([0, 4000, 0, 3.5])
    elif len(self.channels) == 2:
      # Create x and y axis
      xAchse = pylab.array([0]*4000)
      yAchse = pylab.array([0]*4000)
      # Create the plot
      fig = pylab.figure(1)
      self.ax = fig.add_subplot(111)
      self.ax.set_title("X-Y Plotter")
      self.ax.set_xlabel("Channel " + str(self.channels[0]))
      self.ax.set_ylabel("Channel " + str(self.channels[1]))
      self.ax.axis([0, 3.5, 0, 3.5])
    self.ax.grid(True)
    self.line1 = self.ax.plot(xAchse, yAchse, '-')
    # Integrate plot on oscilloscope window
    self.drawing = FigureCanvasTkAgg(fig, master=self.root)
    self.drawing.show()
    self.drawing.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
    # Setup navigation tools
    tool = NavigationToolbar2TkAgg(self.drawing, self.root)
    tool.update()
    self.drawing._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
    return 
Example #13
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def image_neighbor_smooth(xlevel=0.2, ylevel=0.2, image="auto"):
    """
    This will bleed nearest neighbor pixels into each other with
    the specified weight factors.
    """
    if image == "auto": image = _pylab.gca().images[0]

    Z = _n.array(image.get_array())

    # store this image in the undo list
    global image_undo_list
    image_undo_list.append([image, Z])
    if len(image_undo_list) > 10: image_undo_list.pop(0)

    # get the diagonal smoothing level (eliptical, and scaled down by distance)
    dlevel = ((xlevel**2+ylevel**2)/2.0)**(0.5)

    # don't touch the first column
    new_Z = [Z[0]*1.0]

    for m in range(1,len(Z)-1):
        new_Z.append(Z[m]*1.0)
        for n in range(1,len(Z[0])-1):
            new_Z[-1][n] = (Z[m,n] + xlevel*(Z[m+1,n]+Z[m-1,n]) + ylevel*(Z[m,n+1]+Z[m,n-1])   \
                                   + dlevel*(Z[m+1,n+1]+Z[m-1,n+1]+Z[m+1,n-1]+Z[m-1,n-1])   )  \
                                   / (1.0+xlevel*2+ylevel*2 + dlevel*4)

    # don't touch the last column
    new_Z.append(Z[-1]*1.0)

    # images have transposed data
    image.set_array(_n.array(new_Z))

    # update the plot
    _pylab.draw() 
Example #14
Source File: _spline.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def load_spline_array(path=None, text="Give me a spline array to load, jerkface! No, YOU'RE the jerkface."):
    a = _s.load_object(path, text)

    b = copy_spline_array(a)
    b._path = a._path
    _s.save_object(b, b._path)

    return b 
Example #15
Source File: _spline.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1):
        """
        plots the data at a fixed y-value, so z vs y
        """
        if simple=='auto': simple=self.simple


        # get the min and max
        if xmin=="auto": xmin = self.xmin
        if xmax=="auto": xmax = self.xmax
        if clear: _pylab.gca().clear()

        if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values]

        for y in y_values:
            # define a new simple function to plot, then plot it
            def f(x): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, xmin, xmax, steps, 0, True)

            # label it
            a = _pylab.gca()
            th = "th"
            if x_derivative == 1: th = "st"
            if x_derivative == 2: th = "nd"
            if x_derivative == 3: th = "rd"
            if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline")
            else:            a.set_ylabel(self.zlabel)
            a.set_xlabel(self.xlabel)
            a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel)
            a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y))
        if format: _s.format_figure()
        return a 
Example #16
Source File: _spline.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1):
        """
        plots the data at fixed x-value, so z vs x
        """
        if simple=='auto': simple=self.simple
        
        # get the min and max
        if ymin=="auto": ymin = self.ymin
        if ymax=="auto": ymax = self.ymax
        if clear: _pylab.gca().clear()

        if not type(x_values) in [type([]), type(_pylab.array([]))]: x_values = [x_values]

        for x in x_values:
    
            # define a new simple function to plot, then plot it
            def f(y): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, ymin, ymax, steps, 0, False)

            # label it
            a = _pylab.gca()
            a.set_xlabel(self.ylabel)
            if x_derivative: a.set_ylabel(str(x_derivative)+" "+str(self.xlabel)+" derivative of "+self.zlabel)
            else:            a.set_ylabel(self.zlabel)
            a.set_title(self._path+"\nSpline array plot at fixed x = "+self.xlabel)
            a.get_lines()[-1].set_label("x ("+self.xlabel+") = "+str(x))

        if format: _s.format_figure()
        return a 
Example #17
Source File: _spline.py    From spinmob with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, xdata, ydata, smoothing=5000, degree=5, presmoothing=0, plot=True, xlabel="x", ylabel="y", show_derivative=0, xmin="same", xmax="same", simple=0):
        """
        Create a spline object and fit xdata vs ydata with spline
        Set type="interpolate" to simply interpolate the raw data
        """

        # store this stuff for later use
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.xdata  = xdata
        self.ydata  = ydata
        self.simple = simple
        self.xmin = min(xdata)
        self.xmax = max(xdata)
        self._path = "(spline not saved)"
        self.smoothing    = smoothing
        self.degree       = degree
        self.presmoothing = presmoothing
        self.plot_flag    = plot
        self.message = ""
                
        
        # if we're not in simple mode, we have to do a spline fit, not just store the data
        if not simple:        
            # self.ydata might be smoothed
            self.ydata_smoothed = list(ydata)

            # if we're supposed to, presmooth the data
            if presmoothing: _fun.smooth_array(self.ydata_smoothed, presmoothing)

            print("presmoothing = ", str(presmoothing))
            print("smoothing = ",    str(smoothing))
            print("degree    = ",    str(degree))
        
            # do the fit
            self.pfit = _interpolate.splrep(xdata, self.ydata_smoothed, s=smoothing, k=degree)


        # now plot if we're supposed to
        if plot:
            fig  = _pylab.gcf()
            fig.clear()
            axes = fig.gca()
            axes.plot(xdata,ydata, "xr")
            axes.set_xlabel(xlabel)
            axes.set_ylabel(ylabel)
            if not simple:
                axes.plot(xdata,self.ydata_smoothed,"+g")
                self.plot(steps=len(xdata)*5, clear=False)
                _pylab_help.set_all_line_attributes("lw", 2)
                if show_derivative: self.plot(steps=len(xdata)*5, clear=False, derivative=show_derivative, yaxis='right')
                _pylab_help.set_all_line_attributes("lw", 1)
                _pylab_help.set_all_line_attributes("color", "r")

            _pylab_help.set_xrange(xmin, xmax)
            fig.canvas.Refresh()
        

        
    # this takes a single value or an array! 
Example #18
Source File: cwavelet.py    From stock with Apache License 2.0 4 votes vote down vote up
def getWavePacketData(values, waveletName, level, forecastCount):
    wp = pywt.WaveletPacket(data=values, wavelet=waveletName, mode='sym', maxlevel=level)
    print waveletName, ":", wp.maxlevel
    #nodes = wp.get_level(level)
    #labels = [n.path for n in nodes]
    #values = pylab.array([n.data for n in nodes], 'd')
    #print labels
    #print [n.data for n in nodes]
    #print [node.path for node in wp.get_leaf_nodes(decompose=False)]
    #print [node.path for node in wp.get_leaf_nodes(decompose=True)]
    coeffs = [(node.path, node.data) for node in wp.get_leaf_nodes(decompose=True)]
    #print coeffs
    for node in wp.get_leaf_nodes(decompose=True):
        print node.path, len(node.data)
    
    
    coeffsNew = []
    for path, data in coeffs:
        data = cleastsq.getFitYValues(range(len(data)), data, range(len(data)+forecastCount))
        coeffsNew.append((path, data))                                   
    
    #print coeffsNew
    
    wp2 = pywt.WaveletPacket(None, waveletName, maxlevel=level)
    for path, data in coeffsNew:
        wp2[path] = data
    
    #print wp["a"]
    #print [node.path for node in wp2.get_leaf_nodes(decompose=False)]
    value2s= wp2.reconstruct(update=True)
    newLen = len(values)+forecastCount
    print newLen
    return value2s[:newLen]
    
#     print len(value2s)
#     value2s_n= wp2.reconstruct(update=False)
#     plt.plot(range(18), value2s[0:18], color="b", linewidth=1)
#     #plt.plot(range(len(value2s_n)), value2s_n, color="r", linewidth=1)
#     plt.xlabel("Time")
#     plt.ylabel("Price")
#     plt.grid()
#     plt.legend()
#     plt.show()
    
#     print wp['a'].data
#     print wp['d'].data
#     print wp['add'].data
#     print wp['ada'].data
#     print [node.path for node in wp.get_level(3, 'freq')] 
Example #19
Source File: myAirSimClient.py    From AirGym with MIT License 4 votes vote down vote up
def getScreenDepthVis(self, track):

        responses = self.simGetImages([ImageRequest(0, AirSimImageType.DepthPerspective, True, False)])
        img1d = np.array(responses[0].image_data_float, dtype=np.float)
        img1d = 255/np.maximum(np.ones(img1d.size), img1d)
        img2d = np.reshape(img1d, (responses[0].height, responses[0].width))
        
        
        image = np.invert(np.array(Image.fromarray(img2d.astype(np.uint8), mode='L')))
        
        factor = 10
        maxIntensity = 255.0 # depends on dtype of image data
        
        # Decrease intensity such that dark pixels become much darker, bright pixels become slightly dark 
        newImage1 = (maxIntensity)*(image/maxIntensity)**factor
        newImage1 = array(newImage1,dtype=uint8)
        
        
        small = cv2.resize(newImage1, (0,0), fx=0.39, fy=0.38)
                
        cut = small[20:40,:]
        
        info_section = np.zeros((10,cut.shape[1]),dtype=np.uint8) + 255
        info_section[9,:] = 0
        
        line = np.int((((track - -180) * (100 - 0)) / (180 - -180)) + 0)
        
        if line != (0 or 100):
            info_section[:,line-1:line+2]  = 0
        elif line == 0:
            info_section[:,0:3]  = 0
        elif line == 100:
            info_section[:,info_section.shape[1]-3:info_section.shape[1]]  = 0
            
        total = np.concatenate((info_section, cut), axis=0)
            
        #cv2.imshow("Test", total)
        #cv2.waitKey(0)
        
        return total