Python matplotlib.pylab.axis() Examples

The following are 30 code examples of matplotlib.pylab.axis(). 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 matplotlib.pylab , or try the search function .
Example #1
Source File: streams.py    From convis with GNU General Public License v3.0 6 votes vote down vote up
def get(self,i=1):
        """outputs the next slice of length `i` in the stream (see :meth:`convis.streams.Stream`)"""
        a = []
        b = []
        if self.j > 0:
            a.append(self.max_value*(self.buffer[0][self.i].float()/255.0)[None,None,None,:,:].repeat(1,1,self.j,1,1))
            b.append(self.buffer[1][self.i].float().repeat(self.j,28,28)[None,None,:])
        while i > self.j:
            self.j += self.rep
            self.i = (self.i+self.advance)%len(self.buffer[1])
            a.append(self.max_value*(self.buffer[0][self.i].float()/255.0)[None,None,None,:,:].repeat(1,1,self.rep,1,1))
            b.append(self.buffer[1][self.i].float().repeat(self.rep,28,28)[None,None,:])
        a = np.concatenate(a,axis=2)
        b = np.concatenate(b,axis=2)
        self.j = (self.j-i)%self.rep
        if self.include_label:
            return np.concatenate([a,b],axis=0)[:,:,:i,:,:]
        return a[:,:,:i,:,:] 
Example #2
Source File: streams.py    From convis with GNU General Public License v3.0 6 votes vote down vote up
def get_one_frame(self):
        file_list = list(np.repeat(self.file_list,self.repeat))
        if file_list[self.i] in self.cache.keys():
            frame = self.cache[file_list[self.i]]
        else:
            from PIL import Image
            frame = np.array(Image.open(file_list[self.i]))
            if not self.is_color and len(frame.shape) > 2:
                frame = frame.mean(2)
            if self.is_color:
                if len(frame.shape) == 2:
                    print('2 to 3d')
                    frame = frame[:,:,None]
                if frame.shape[2] < 3:
                    frame = np.repeat(frame[:,:,None],3,axis=2)
                if frame.shape[2] > 3:
                    frame = frame[:,:,:3]
            self.cache[file_list[self.i]] = frame
        cropped_frame = self._crop(frame)
        self.last_image = cropped_frame
        self.i += 1
        return cropped_frame 
Example #3
Source File: Orthogonal.py    From PyAero with MIT License 6 votes vote down vote up
def modbc(self):
        self.resorx = 0.0
        self.resory = 0.0

        for i in range(2, self.ni):
            xp = self.x(i, nj - 1)
            yp = self.y(i, nj - 1)
            xb = self.x(i, nj)
            yb = self.y(i, nj)
            ifail = 0
            call e02bcf(nicap7, xkn, cn, xb, 1, sn, ifail)
            interpolate.CubicSpline(x, y, axis=0, bc_type='not-a-knot', extrapolate=None)
            dydxb = min(sn(2), 1.d10)
            dydxb = max(sn(2), 1.d-10)
            if(sn(2).lt.0.0) dydxb = max(sn(2), -1.d10)
            if(sn(2).lt.0.0) dydxb = min(sn(2), -1.d-10)
            x(i, nj) = (yb-yp-xb*dydxb-xp/dydxb)/(-dydxb-1.0/dydxb)
            ifail = 0.0
            call e02bcf(nicap7, xkn, cn, x(i, nj), 1, sn, ifail)
            y(i, nj) = sn(1)
            resxb = abs(xb-x(i, nj))/xl
            resorx = resorx+resxb
            resyb = abs(yb-y(i, nj))/yl
            resory = resory+resyb 
Example #4
Source File: usage_example.py    From tensorflow-ffmpeg with MIT License 6 votes vote down vote up
def _show_video(video, fps=10):
    # Import matplotlib/pylab only if needed
    import matplotlib
    matplotlib.use('TkAgg')
    import matplotlib.pylab as pl
    pl.style.use('ggplot')
    pl.axis('off')

    if fps < 0:
        fps = 25
    video /= 255.  # Pylab works in [0, 1] range
    img = None
    pause_length = 1. / fps
    try:
        for f in range(video.shape[0]):
            im = video[f, :, :, :]
            if img is None:
                img = pl.imshow(im)
            else:
                img.set_data(im)
            pl.pause(pause_length)
            pl.draw()
    except:
        pass 
Example #5
Source File: streams.py    From convis with GNU General Public License v3.0 6 votes vote down vote up
def _repr_html_(self):
        from . import variable_describe
        def _plot(fn):
            from PIL import Image
            try:
                import matplotlib.pylab as plt
                t = np.array(Image.open(fn))
                plt.figure()
                plt.imshow(self._crop(t))
                plt.axis('off')
                return "<img src='data:image/png;base64," + variable_describe._plot_to_string() + "'>"
            except:
                return "<br/>Failed to open."
        s = "<b>ImageSequence</b> size="+str(self.size)
        s += ", offset = "+str(self.offset)
        s += ", repeat = "+str(self.repeat)
        s += ", is_color = "+str(self.is_color)
        s += ", [frame "+str(self.i)+"/"+str(len(self))+"]"
        s += "<div style='background:#ff;padding:10px'><b>Input Images:</b>"
        for t in np.unique(self.file_list)[:10]:
            s += "<div style='background:#fff; margin:10px;padding:10px; border-left: 4px solid #eee;'>"+str(t)+": "+_plot(t)+"</div>"
        s += "</div>"
        return s 
Example #6
Source File: visualization_utils.py    From DeepLearningImplementations with MIT License 6 votes vote down vote up
def format_plot(X, epoch=None, title=None, figsize=(15, 10)):

    plt.figure(figsize=figsize)

    if X.shape[-1] == 1:
        plt.imshow(X[:, :, 0], cmap="gray")
    else:
        plt.imshow(X)

    plt.axis("off")
    plt.gca().xaxis.set_major_locator(mp.ticker.NullLocator())
    plt.gca().yaxis.set_major_locator(mp.ticker.NullLocator())

    if epoch is not None and title is None:
        save_path = os.path.join(FLAGS.fig_dir, "current_batch_%s.png" % epoch)
    elif epoch is not None and title is not None:
        save_path = os.path.join(FLAGS.fig_dir, "%s_%s.png" % (title, epoch))
    elif title is not None:
        save_path = os.path.join(FLAGS.fig_dir, "%s.png" % title)
    plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
    plt.clf()
    plt.close() 
Example #7
Source File: utils.py    From DeepLearningImplementations with MIT License 6 votes vote down vote up
def format_array(arr):
    """
    Utility to format array for tiled plot

    args: arr (numpy array)
            shape : (n_samples, n_channels, img_dim1, img_dim2)
    """
    n_channels = arr.shape[1]
    len_arr = arr.shape[0]
    assert (n_channels == 1 or n_channels == 3), "n_channels should be 1 (Greyscale) or 3 (Color)"
    if n_channels == 1:
        arr = np.repeat(arr, 3, axis=1)

    shape1, shape2 = arr.shape[-2:]
    arr = np.transpose(arr, [1, 0, 2, 3])
    arr = arr.reshape([3, len_arr, shape1 * shape2]).astype(np.float64)
    arr = tuple([arr[i] for i in xrange(3)] + [None])
    return arr, shape1, shape2 
Example #8
Source File: streams.py    From convis with GNU General Public License v3.0 6 votes vote down vote up
def get(self,i=1):
        """outputs the next slice of length `i` in the stream (see :meth:`convis.streams.Stream`)"""
        a = []
        b = []
        if self.j > 0:
            a.append(self.poisson(self.fr*(self.buffer[0][self.i].float()/255.0)[None,:,:].repeat(self.j,1,1)))
            b.append(self.buffer[1][self.i].float().repeat(self.j,28,28)[None,None,:])
        while i > self.j:
            self.j += self.rep
            self.i = (self.i+self.advance)%len(self.buffer[1])
            a.append(self.poisson(self.fr*(self.buffer[0][self.i].float()/255.0)[None,:,:].repeat(self.rep,1,1)))
            b.append(self.buffer[1][self.i].float().repeat(self.rep,28,28)[None,None,:])
        a = np.concatenate(a,axis=2)
        b = np.concatenate(b,axis=2)
        self.j = (self.j-i)%self.rep
        if self.include_label:
            return np.concatenate([a,b],axis=0)[:,:,:i,:,:]
        return a[:,:,:i,:,:] 
Example #9
Source File: streams.py    From convis with GNU General Public License v3.0 6 votes vote down vote up
def get(self,t1,t2):
        t,v = self.stream.get_tsvs(t1-2.0*self.dt,t2+2.0*self.dt)
        try:
            return interp1d(t,
                        v.reshape(len(t),-1),
                        axis=0,
                        fill_value='extrapolate',
                        bounds_error = False
                       )(self.ts(t1,t2)).reshape(
            [len(self.ts(t1,t2))]+list(v.shape[1:]))
        except ValueError:
            # old versions of scipy don't know extrapolate
            # it also doesn't behave as numpy interpolate (extending the first and last values) as only one value is accepted
            # this should not be a problem if we 2*dt before and after the time slice
            return interp1d(t,
                        v.reshape(len(t),-1),
                        axis=0,
                        fill_value=np.mean(v),
                        bounds_error = False
                       )(self.ts(t1,t2)).reshape(
            [len(self.ts(t1,t2))]+list(v.shape[1:])) 
Example #10
Source File: visualization_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def save_image(data, data_format, e):
    """Saves a picture showing the current progress of the model"""

    X_G, X_real = data

    Xg = X_G[:8]
    Xr = X_real[:8]

    if data_format == "NHWC":
        X = np.concatenate((Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] / 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=0)

    if data_format == "NCHW":
        X = np.concatenate((Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] / 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=1)
        Xr = Xr.transpose(1,2,0)

    if Xr.shape[-1] == 1:
        plt.imshow(Xr[:, :, 0], cmap="gray")
    else:
        plt.imshow(Xr)
    plt.axis("off")
    plt.savefig(os.path.join(FLAGS.fig_dir, "current_batch_%s.png" % e))
    plt.clf()
    plt.close() 
Example #11
Source File: utils.py    From TemporalConvolutionalNetworks with MIT License 5 votes vote down vote up
def imshow_(x, **kwargs):
	if x.ndim == 2:
		plt.imshow(x, interpolation="nearest", **kwargs)
	elif x.ndim == 1:
		plt.imshow(x[:,None].T, interpolation="nearest", **kwargs)
		plt.yticks([])
	plt.axis("tight")

# ------------- Data ------------- 
Example #12
Source File: visualization_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def save_image(data, data_format, e, suffix=None):
    """Saves a picture showing the current progress of the model"""

    X_G, X_real = data

    Xg = X_G[:8]
    Xr = X_real[:8]

    if data_format == "NHWC":
        X = np.concatenate((Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] / 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=0)

    if data_format == "NCHW":
        X = np.concatenate((Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] / 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=1)
        Xr = Xr.transpose(1,2,0)

    if Xr.shape[-1] == 1:
        plt.imshow(Xr[:, :, 0], cmap="gray")
    else:
        plt.imshow(Xr)
    plt.axis("off")
    if suffix is None:
        plt.savefig(os.path.join(FLAGS.fig_dir, "current_batch_%s.png" % e))
    else:
        plt.savefig(os.path.join(FLAGS.fig_dir, "current_batch_%s_%s.png" % (suffix, e)))
    plt.clf()
    plt.close() 
Example #13
Source File: visualization_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def get_stacked_tensor(X1, X2):

    X = tf.concat((X1[:16], X2[:16]), axis=0)
    list_rows = []
    for i in range(8):
        Xr = tf.concat([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
        list_rows.append(Xr)

    X = tf.concat(list_rows, axis=1)
    X = tf.transpose(X, (1,2,0))
    X = tf.expand_dims(X, 0)

    return X 
Example #14
Source File: data_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def plot_generated_batch(X_full, X_sketch, generator_model, batch_size, image_data_format, suffix, logging_dir):

    # Generate images
    X_gen = generator_model.predict(X_sketch)

    X_sketch = inverse_normalization(X_sketch)
    X_full = inverse_normalization(X_full)
    X_gen = inverse_normalization(X_gen) 
    
    Xs = X_sketch[:8]
    Xg = X_gen[:8]
    Xr = X_full[:8]
    
    if image_data_format == "channels_last":
        X = np.concatenate((Xs, Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] // 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=0)

    if image_data_format == "channels_first":
        X = np.concatenate((Xs, Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] // 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=1)
        Xr = Xr.transpose(1,2,0)

    if Xr.shape[-1] == 1:
        plt.imshow(Xr[:, :, 0], cmap="gray")
    else:
        plt.imshow(Xr)
    plt.axis("off")
    plt.savefig(os.path.join(logging_dir, "figures/current_batch_%s.png" % suffix))
    plt.clf()
    plt.close() 
Example #15
Source File: utils.py    From TCFPN-ISBA with MIT License 5 votes vote down vote up
def imshow_(x, **kwargs):
    if x.ndim == 2:
        plt.imshow(x, interpolation="nearest", **kwargs)
    elif x.ndim == 1:
        plt.imshow(x[:, None].T, interpolation="nearest", **kwargs)
        plt.yticks([])
    plt.axis("tight")


# ------------- Data ------------- 
Example #16
Source File: visualization_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def save_image(data, data_format, e, suffix=None):
    """Saves a picture showing the current progress of the model"""

    X_G, X_real = data

    Xg = X_G[:8]
    Xr = X_real[:8]

    if data_format == "NHWC":
        X = np.concatenate((Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] / 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=0)

    if data_format == "NCHW":
        X = np.concatenate((Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] / 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=1)
        Xr = Xr.transpose(1,2,0)

    if Xr.shape[-1] == 1:
        plt.imshow(Xr[:, :, 0], cmap="gray")
    else:
        plt.imshow(Xr)
    plt.axis("off")
    if suffix is None:
        plt.savefig(os.path.join(FLAGS.fig_dir, "current_batch_%s.png" % e))
    else:
        plt.savefig(os.path.join(FLAGS.fig_dir, "current_batch_%s_%s.png" % (suffix, e)))
    plt.clf()
    plt.close() 
Example #17
Source File: utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def find_top9_mean_act(data, Dec, target_layer, feat_map, batch_size=32):
    """
    Find images with highest mean activation

    args:  data (numpy array) the image data
           shape : (n_samples, n_channels, img_dim1, img_dim2)

           Dec (DeconvNet) instance of the DeconvNet class

           target_layer (str) Layer name we want to visualise

           feat_map (int) index of the filter to visualise

           batch_size (int) batch size

    returns: top9 (numpy array) index of the top9 images that activate feat_map
    """

    # Theano function to get the layer output
    T_in, T_out = Dec[Dec.model.layers[0].name].input, Dec[target_layer].output
    get_activation = K.function([T_in], T_out)

    list_max = []
    # Loop over batches and store the max activation value for each
    # image in data for the target layer and target feature map
    for nbatch in range(data.shape[0] / batch_size):
        sys.stdout.write("\rProcessing batch %s/%s" %
                         (nbatch + 1, len(range(data.shape[0] / batch_size))))
        sys.stdout.flush()
        X = data[nbatch * batch_size: (nbatch + 1) * batch_size]
        Dec.model.predict(X)
        X_activ = get_activation([X])[:, feat_map, :, :]
        X_sum = np.sum(X_activ, axis=(1,2))
        list_max += X_sum.tolist()
    # Only keep the top 9 activations
    list_max = np.array(list_max)
    i_sort = np.argsort(list_max)
    top9 = i_sort[-9:]
    print("")
    return top9 
Example #18
Source File: visualization_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def save_image(X1, X2, e=None, title=None):

    if FLAGS.data_format == "NCHW":
        X1 = X1.transpose((0, 2, 3, 1))
        X2 = X2.transpose((0, 2, 3, 1))

    Xup = X1[:32]
    Xdown = X2[:32]

    n_cols = 8

    list_rows_f = []
    for i in range(Xup.shape[0] // n_cols):
        Xrow = np.concatenate([Xup[k] for k in range(n_cols * i, n_cols * (i + 1))], axis=1)
        list_rows_f.append(Xrow)
    list_rows_r = []
    for i in range(Xup.shape[0] // n_cols):
        Xrow = np.concatenate([Xdown[k] for k in range(n_cols * i, n_cols * (i + 1))], axis=1)
        list_rows_r.append(Xrow)

    Xup = np.concatenate(list_rows_f, axis=0)
    Xdown = np.concatenate(list_rows_r, axis=0)

    X_ones = 255 * np.ones_like(Xup, dtype=np.uint8)
    X_ones = X_ones[:5, :, :]

    X = np.concatenate((Xup, X_ones, Xdown), axis=0)

    format_plot(X, epoch=e, title=title) 
Example #19
Source File: Time Series Analysis.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def plotCoefficients(model,X_train):
    """
        Plots sorted coefficient values of the model
    """
    
    coefs = pd.DataFrame(model.coef_, X_train.columns)
    coefs.columns = ["coef"]
    coefs["abs"] = coefs.coef.apply(np.abs)
    coefs = coefs.sort_values(by="abs", ascending=False).drop(["abs"], axis=1)
    
    plt.figure(figsize=(15, 7))
    coefs.coef.plot(kind='bar')
    plt.grid(True, axis='y')
    plt.hlines(y=0, xmin=0, xmax=len(coefs), linestyles='dashed'); 
Example #20
Source File: data_utils.py    From Pix2Depth with GNU General Public License v3.0 5 votes vote down vote up
def plot_generated_batch(X_full, X_sketch, generator_model, batch_size, image_data_format, suffix, show_plot=False):

    # Generate images
    X_gen = generator_model.predict(X_sketch)

    X_sketch = inverse_normalization(X_sketch)
    X_full = inverse_normalization(X_full)
    X_gen = inverse_normalization(X_gen)

    Xs = X_sketch[:8]
    Xg = X_gen[:8]
    Xr = X_full[:8]

    if image_data_format == "channels_last":
        X = np.concatenate((Xs, Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] // 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=0)

    if image_data_format == "channels_first":
        X = np.concatenate((Xs, Xg, Xr), axis=0)
        list_rows = []
        for i in range(int(X.shape[0] // 4)):
            Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
            list_rows.append(Xr)

        Xr = np.concatenate(list_rows, axis=1)
        Xr = Xr.transpose(1,2,0)

    if show_plot:
        if Xr.shape[-1] == 1:
            plt.imshow(Xr[:, :, 0], cmap="gray")
        else:
            plt.imshow(Xr)
    plt.axis("off")
    plt.savefig("../../figures/current_batch_%s.png" % suffix)
    plt.clf()
    plt.close() 
Example #21
Source File: streams.py    From convis with GNU General Public License v3.0 5 votes vote down vote up
def put(self,s):
        if len(s.shape) == 5:
            # concatenate batches and swap channels to the last dimension
            s = np.concatenate(s,axis=1)[:,:,:,:,None].swapaxes(0,4)[0]
            if not self.isColor:
                s = s.mean(-1)
        else:
            if self.isColor:
                s = s[:,:,:,None].repeat(3,axis=-1)
        for frame in s:
            self.last_image = frame
            self.out.write(np.uint8(frame)) 
Example #22
Source File: streams.py    From convis with GNU General Public License v3.0 5 votes vote down vote up
def update_image(self):
        from PIL import Image, ImageTk
        if self.decay_activity is not None:
            try:
                da = self.decay_activity
                da = da + np.min(da)
                im = da/max(np.max(da),1.0)
                im = im.clip(0.0,1.0)
                if im.shape[0] < 50:
                    im = np.repeat(im,10,axis=0)
                    im = np.repeat(im,10,axis=1)
                elif im.shape[0] < 100:
                    im = np.repeat(im,5,axis=0)
                    im = np.repeat(im,5,axis=1)
                elif im.shape[0] < 300:
                    im = np.repeat(im,2,axis=0)
                    im = np.repeat(im,2,axis=1)
                if self.cmap is not None:
                    self.image = Image.fromarray(self.cmap(im, bytes=True))
                else:
                    self.image = Image.fromarray(256.0*im).convert('RGB')#Image.open(image_buffer)#cStringIO.StringIO(self.last_buffer))
                #self.image.resize((500,500), Image.ANTIALIAS)
                #self.image.load()
                self.image1 = ImageTk.PhotoImage(self.image)
                self.panel1.configure(image=self.image1)
                self.root.title(str(len(self.last_buffer))+' Images buffered')
                self.display = self.image1
            except Exception as e:
                #print(e)
                raise
                #pass
        self.root.after(int(50), self.update_image) 
Example #23
Source File: streams.py    From convis with GNU General Public License v3.0 5 votes vote down vote up
def put(self,s):
        self.sequence = np.concatenate([self.sequence,s],axis=0.0) 
Example #24
Source File: streams.py    From convis with GNU General Public License v3.0 5 votes vote down vote up
def get(self,i):
        """outputs the next slice of length `i` in the stream (see :meth:`convis.streams.Stream`)"""
        self.i += i
        if len(self.sequence) < self.i:
            pre_index = int(self.i-i)
            self.i -= len(self.sequence)
            return np.concatenate([self.sequence[pre_index:],self.sequence[:self.i]],axis=0)
        return self.sequence[(self.i-i):self.i] 
Example #25
Source File: streams.py    From convis with GNU General Public License v3.0 5 votes vote down vote up
def put(self,s):
        if self.sequence.shape[1:] == s.shape[1:]:
            if len(self.sequence) + len(s) > self.max_frames:
                self.sequence = np.concatenate([self.sequence,s],axis=0)[-self.max_frames:]
            else:
                self.sequence = np.concatenate([self.sequence,s],axis=0)
        else:
            if len(s) > self.max_frames:
                self.sequence = s[-self.max_frames:]
            else:
                self.sequence = s 
Example #26
Source File: food.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def _h_get_unit_vec(x):
    return x/np.linalg.norm(x, axis=1)[:, np.newaxis]
#%% 
Example #27
Source File: food.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def _h_smooth_cnt(food_cnt, resampling_N = 1000, smooth_window=None, _is_debug=False):
    if smooth_window is None:
        smooth_window = resampling_N//20
    
    if not _is_valid_cnt(food_cnt):
        #invalid contour arrays
        return food_cnt
        
    smooth_window = smooth_window if smooth_window%2 == 1 else smooth_window+1
    # calculate the cumulative length for each segment in the curve
    dx = np.diff(food_cnt[:, 0])
    dy = np.diff(food_cnt[:, 1])
    dr = np.sqrt(dx * dx + dy * dy)
    lengths = np.cumsum(dr)
    lengths = np.hstack((0, lengths))  # add the first point
    tot_length = lengths[-1]
    fx = interp1d(lengths, food_cnt[:, 0])
    fy = interp1d(lengths, food_cnt[:, 1])
    subLengths = np.linspace(0 + np.finfo(float).eps, tot_length, resampling_N)
    
    rx = fx(subLengths)
    ry = fy(subLengths)
    
    pol_degree = 3
    rx = savgol_filter(rx, smooth_window, pol_degree, mode='wrap')
    ry = savgol_filter(ry, smooth_window, pol_degree, mode='wrap')
    
    food_cnt_s = np.stack((rx, ry), axis=1)
    
    if _is_debug:
        import matplotlib.pylab as plt
        plt.figure()
        plt.plot(food_cnt[:, 0], food_cnt[:, 1], '.-')
        plt.plot(food_cnt_s[:, 0], food_cnt_s[:, 1], '.-')
        plt.axis('equal')
        plt.title('smoothed contour')
    
    return food_cnt_s

#%% 
Example #28
Source File: curvatures.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def _gradient_windowed(X, points_window, axis):
    '''
    Calculate the gradient using an arbitrary window. The larger window make 
    this procedure less noisy that the numpy native gradient.
    '''
    w_s = 2*points_window
    
    #I use slices to deal with arbritary dimenssions 
    #https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
    n_axis_ini = max(0, axis)
    n_axis_fin = max(0, X.ndim-axis-1)
    
    right_slice = [slice(None, None, None)]*n_axis_ini + [slice(None, -w_s, None)]
    right_slice = tuple(right_slice)
    
    left_slice = [slice(None, None, None)]*n_axis_ini + [slice(w_s, None, None)]
    left_slice = tuple(left_slice)

    right_pad = [(0,0)]*n_axis_ini + [(w_s, 0)] + [(0,0)]*n_axis_fin
    left_pad = [(0,0)]*n_axis_ini + [(0, w_s)] + [(0,0)]*n_axis_fin
    
    right_side = np.pad(X[right_slice], right_pad, 'edge')
    left_side = np.pad(X[left_slice], left_pad, 'edge')
    
    ramp = np.full(X.shape[axis]-2*w_s, w_s*2)
    
    ramp = np.pad(ramp,  pad_width = (w_s, w_s),  mode='linear_ramp', end_values = w_s)
    #ramp = np.pad(ramp,  pad_width = (w_s, w_s),  mode='constant', constant_values = np.nan)
    ramp_slice = [None]*n_axis_ini + [slice(None, None, None)] + [None]*n_axis_fin
    ramp_slice = tuple(ramp_slice)

    grad = (left_side - right_side) / ramp[ramp_slice] #divide it by the time window
    
    return grad 
Example #29
Source File: plot.py    From POT with MIT License 5 votes vote down vote up
def plot1D_mat(a, b, M, title=''):
    """ Plot matrix M  with the source and target 1D distribution

    Creates a subplot with the source distribution a on the left and
    target distribution b on the tot. The matrix M is shown in between.


    Parameters
    ----------
    a : ndarray, shape (na,)
        Source distribution
    b : ndarray, shape (nb,)
        Target distribution
    M : ndarray, shape (na, nb)
        Matrix to plot
    """
    na, nb = M.shape

    gs = gridspec.GridSpec(3, 3)

    xa = np.arange(na)
    xb = np.arange(nb)

    ax1 = pl.subplot(gs[0, 1:])
    pl.plot(xb, b, 'r', label='Target distribution')
    pl.yticks(())
    pl.title(title)

    ax2 = pl.subplot(gs[1:, 0])
    pl.plot(a, xa, 'b', label='Source distribution')
    pl.gca().invert_xaxis()
    pl.gca().invert_yaxis()
    pl.xticks(())

    pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
    pl.imshow(M, interpolation='nearest')
    pl.axis('off')

    pl.xlim((0, nb))
    pl.tight_layout()
    pl.subplots_adjust(wspace=0., hspace=0.2) 
Example #30
Source File: deepjdot_svhn_mnist.py    From deepJDOT with MIT License 5 votes vote down vote up
def tsne_plot(xs, xt, xs_label, xt_label, subset=True, title=None, pname=None):
    num_test=1000
    import matplotlib.cm as cm
    if subset:
        combined_imgs = np.vstack([xs[0:num_test, :], xt[0:num_test, :]])
        combined_labels = np.vstack([xs_label[0:num_test, :],xt_label[0:num_test, :]])
        combined_labels = combined_labels.astype('int')
        combined_domain = np.vstack([np.zeros((num_test,1)),np.ones((num_test,1))])
    
    from sklearn.manifold import TSNE
    tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=3000)
    source_only_tsne = tsne.fit_transform(combined_imgs)
    plt.figure(figsize=(15,15))
    plt.scatter(source_only_tsne[:num_test,0], source_only_tsne[:num_test,1], c=combined_labels[:num_test].argmax(1),
                s=50, alpha=0.5,marker='o', cmap=cm.jet, label='source')
    plt.scatter(source_only_tsne[num_test:,0], source_only_tsne[num_test:,1], c=combined_labels[num_test:].argmax(1),
                s=50, alpha=0.5,marker='+',cmap=cm.jet,label='target')
    plt.axis('off')
    plt.legend(loc='best')
    plt.title(title)
    if filesave:
        plt.savefig(os.path.join(pname,title+'.png'),bbox_inches='tight', pad_inches = 0,
                    format='png')
    else:
        plt.savefig(title+'.png')
    plt.close() 


#%% source model