Python pylab 模块,imshow() 实例源码

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

项目:yt    作者:yt-project    | 项目源码 | 文件源码
def plot_rgb(image, name, label=None, label_color='w', label_size='large'):
    """
    This will plot the r,g,b channels of an *image* of shape (N,M,3) or
    (N,M,4).  *name* is the prefix of the file name, which will be supplemented
    with "_rgb.png."  *label*, *label_color* and *label_size* may also be
    specified.
    """
    import pylab
    Nvec = image.shape[0]
    image[np.isnan(image)] = 0.0
    if image.shape[2] >= 4:
        image = image[:,:,:3]
    pylab.clf()
    pylab.gcf().set_dpi(100)
    pylab.gcf().set_size_inches((Nvec/100.0, Nvec/100.0))
    pylab.gcf().subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.0, hspace=0.0)
    pylab.imshow(image, interpolation='nearest')
    if label is not None:
        pylab.text(20, 20, label, color = label_color, size=label_size) 
    pylab.savefig("%s_rgb.png" % name)
    pylab.clf()
项目:AdK_analysis    作者:orbeckst    | 项目源码 | 文件源码
def plot(self,**kwargs):
        """plot landscape (kwargs are passed on to imshow()

        Use interpolation='bilinear' or 'bicubic' for a smooth
        surface. Default is 'nearest', which shows exact bin
        boundaries.
        """
        import pylab

        kwargs.setdefault('interpolation','nearest')
        pylab.clf()
        pylab.xlabel('x')
        pylab.ylabel('y')
        pylab.imshow(self.pmf_masked.T,**kwargs)
        pylab.colorbar()
        pylab.show()
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
def disp(iimg, label = "", gray=False):
    """ Display an image using pylab
    """
    try:
        import pylab
        dimage = iimg.copy()
        if iimg.ndim==3:
            dimage[...,0] = iimg[...,2]
            dimage[...,2] = iimg[...,0]

        pylab.imshow(dimage, interpolation='none')
        if gray: pylab.gray()
        #pylab.gca().format_coord = format_coord
        pylab.text(1500, -30, label)
        pylab.axis('off')
        pylab.show()
    except ImportError:
        print "Module pylab not available"
项目:keras    作者:GeekLiB    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % epoch))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])

        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words, 1, i + 1)
            if K.image_dim_ordering() == 'th':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\' Decoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 12)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % epoch))
        pylab.close()

# Input Parameters
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def _extract_lines(img, edges=None, mask=None, min_line_length=20, max_line_gap=3):
    global __i__
    __i__ += 1

    if edges is None:
        edges = canny(rgb2grey(img))
    if mask is not None:
        edges = edges & mask

    # figure()
    # subplot(131)
    # imshow(img)
    # subplot(132)
    #vimshow(edges)
    # subplot(133)
    # if mask is not None:
    #     imshow(mask, cmap=cm.gray)
    # savefig('/home/shared/Projects/Facades/src/data/for-labelme/debug/foo/{:06}.jpg'.format(__i__))

    lines = np.array(probabilistic_hough_line(edges, line_length=min_line_length, line_gap=max_line_gap))

    return lines
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_rectified(self):
        import pylab
        pylab.title('rectified')
        pylab.imshow(self.rectified)

        for line in self.vlines:
            p0, p1 = line
            p0 = self.inv_transform(p0)
            p1 = self.inv_transform(p1)
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')

        for line in self.hlines:
            p0, p1 = line
            p0 = self.inv_transform(p0)
            p1 = self.inv_transform(p1)
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')

        pylab.axis('image');
        pylab.grid(c='yellow', lw=1)
        pylab.plt.yticks(np.arange(0, self.l, 100.0));
        pylab.xlim(0, self.w)
        pylab.ylim(self.l, 0)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_original(self):
        import pylab
        pylab.title('original')
        pylab.imshow(self.data)

        for line in self.lines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='blue', alpha=0.3)

        for line in self.vlines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')

        for line in self.hlines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')

        pylab.axis('image');
        pylab.grid(c='yellow', lw=1)
        pylab.plt.yticks(np.arange(0, self.l, 100.0));
        pylab.xlim(0, self.w)
        pylab.ylim(self.l, 0)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self):
        """ Plot the layer data (for debugging)
        :return: The current figure
        """
        import pylab as pl
        aspect = self.nrows / float(self.ncols)
        figure_width = 6 #inches

        rows = max(1, int(np.sqrt(self.nlayers)))
        cols = int(np.ceil(self.nlayers/rows))
        # noinspection PyUnresolvedReferences
        pallette = {i:rgb for (i, rgb) in enumerate(pl.cm.jet(np.linspace(0, 1, 4), bytes=True))}
        f, a = pl.subplots(rows, cols)
        f.set_size_inches(6 * cols, 6 * rows)
        a = a.flatten()
        for i, label in enumerate(self.label_names):
            pl.sca(a[i])
            pl.title(label)
            pl.imshow(self.color_data)
            pl.imshow(colorize(self.label_data[:, :, i], pallette), alpha=0.5)
            # axis('off')
        return f
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self, overlay_alpha=0.5):
        import pylab as pl
        rows = int(sqrt(self.layers()))
        cols = int(ceil(self.layers()/rows))

        for i in range(rows*cols):
            pl.subplot(rows, cols, i+1)
            pl.axis('off')
            if i >= self.layers():
                continue
            pl.title('{}({})'.format(self.labels[i], i))
            pl.imshow(self.image)
            pl.imshow(colorize(self.features[i].argmax(0),
                               colors=np.array([[0,     0, 255],
                                                [0,   255, 255],
                                                [255, 255, 0],
                                                [255, 0,   0]])),
                      alpha=overlay_alpha)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def _plot_background(self, bgimage):
        import pylab as pl
        # Show the portion of the image behind this facade
        left, right = self.facade_left, self.facade_right
        top, bottom = 0, self.mega_facade.rectified.shape[0]
        if bgimage is not None:
            pl.imshow(bgimage[top:bottom, left:right], extent=(left, right, bottom, top))
        else:
            # Fit the facade in the plot
            y0, y1 = pl.ylim()
            x0, x1 = pl.xlim()
            x0 = min(x0, left)
            x1 = max(x1, right)
            y0 = min(y0, top)
            y1 = max(y1, bottom)
            pl.xlim(x0, x1)
            pl.ylim(y1, y0)
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def show_mpl(self, im, enhance=True, clear_fig=True):
        if self._pylab is None:
            import pylab
            self._pylab = pylab
        if self._render_figure is None:
            self._render_figure = self._pylab.figure(1)
        if clear_fig: self._render_figure.clf()

        if enhance:
            nz = im[im > 0.0]
            nim = im / (nz.mean() + 6.0 * np.std(nz))
            nim[nim > 1.0] = 1.0
            nim[nim < 0.0] = 0.0
            del nz
        else:
            nim = im
        ax = self._pylab.imshow(nim[:,:,:3]/nim[:,:,:3].max(), origin='upper')
        return ax
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def plot_allsky_healpix(image, nside, fn, label = "", rotation = None,
                        take_log = True, resolution=512, cmin=None, cmax=None):
    import matplotlib.figure
    import matplotlib.backends.backend_agg
    if rotation is None: rotation = np.eye(3).astype("float64")

    img, count = pixelize_healpix(nside, image, resolution, resolution, rotation)

    fig = matplotlib.figure.Figure((10, 5))
    ax = fig.add_subplot(1,1,1,projection='aitoff')
    if take_log: func = np.log10
    else: func = lambda a: a
    implot = ax.imshow(func(img), extent=(-np.pi,np.pi,-np.pi/2,np.pi/2),
                       clip_on=False, aspect=0.5, vmin=cmin, vmax=cmax)
    cb = fig.colorbar(implot, orientation='horizontal')
    cb.set_label(label)
    ax.xaxis.set_ticks(())
    ax.yaxis.set_ticks(())
    canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
    canvas.print_figure(fn)
    return img, count
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def interpolate2dDiffusion(arr1, arr2, steps=10, diffusivity=0.2):

    psf = np.zeros((5, 5))
    numbaGaussian2d(psf, 1, 1)
#     plt.imshow(psf)
#     plt.show()
    last = arr1

    out = []
    for s in range(steps):
        next = np.zeros_like(arr1)
        diff = diffusivity * (last - arr2)
#         plt.imshow(diff)
#         plt.show()
        weightedConvolution(last, next, diff, psf)

        out.append(next)
        last = next
    return out
项目:keras-customized    作者:ambrite    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_dim_ordering() == 'th':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close()
项目:Keras_note    作者:LibCorner    | 项目源码 | 文件源码
def train(sentences,discriminator_gen=discriminator_gen,discriminator=discriminator,gen_model=gen_model):

    data,real_word=getData(sentences)

    fake_word=gen_model.predict(data)
    pylab.imshow(fake_word[0][0], cmap=cm.Greens,origin='lower')

    real_label=np.zeros((1,))
    fake_label=np.ones((1,))

    #discriminator.predict(real_word)

    discriminator_gen.fit(data,fake_label,nb_epoch=5)
    fake_word=gen_model.predict(data)
    discriminator.fit(fake_word,real_label,nb_epoch=5)
    discriminator.fit(real_word,fake_label,nb_epoch=5)
项目:keras-mxnet-benchmarks    作者:sandeep-krishnamurthy    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_dim_ordering() == 'th':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close()
项目:adversarial-autoencoder    作者:musyoku    | 项目源码 | 文件源码
def tile_images(image_batch, image_width=28, image_height=28, image_channel=1, dir=None, filename="images"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    pylab.gray()
    for m in range(100):
        pylab.subplot(10, 10, m + 1)
        pylab.imshow(image_batch[m].reshape((image_width, image_height)), interpolation="none")
        pylab.axis("off")
    pylab.savefig("{}/{}.png".format(dir, filename))
项目:Captcha-recognition-TF    作者:dukn    | 项目源码 | 文件源码
def view_(_pred,_lable):

    fname = ['Captcha/lv3/%i.jpg' %i for i in range(20)]
    img = []
    for fn in fname:
        img.append(Image.open(open(fn)))
        #img.append(misc.imread(fn).astype(np.float))
    for i in range(len(img)):
        pylab.subplot(4,5,i+1); pylab.axis('off')

        pylab.imshow(img[i])
        #pylab.imshow( np.dot(np.array(img[i])[...,:3],[0.299,0.587,0.114]) , cmap=plt.get_cmap("gray"))
        #pylab.text(40,60,_pred[i],color = 'b')
        if ( _pred[i] == _lable[i] ):
            pylab.text(40,65,_pred[i],color = 'b',size = 15)
        else:
            pylab.text(40,65,_pred[i],color = 'r',size = 15)

        pylab.text(40,92,_lable[i],color = 'g',size = 15)

    pylab.show()
项目:chainer-adversarial-autoencoder    作者:fukuta0614    | 项目源码 | 文件源码
def visualize_reconstruction(xp, model, x, visualization_dir, epoch, gpu=False):
    x_variable = chainer.Variable(xp.asarray(x))
    _x = model.decode(model.encode(x_variable), test=True)
    _x.to_cpu()
    _x = _x.data

    fig = pylab.gcf()
    fig.set_size_inches(8.0, 8.0)
    pylab.clf()
    pylab.gray()
    for m in range(50):
        i = m / 10
        j = m % 10
        pylab.subplot(10, 10, 20 * i + j + 1, xticks=[], yticks=[])
        pylab.imshow(x[m].reshape((28, 28)), interpolation="none")
        pylab.subplot(10, 10, 20 * i + j + 10 + 1, xticks=[], yticks=[])
        pylab.imshow(_x[m].reshape((28, 28)), interpolation="none")
        # pylab.imshow(np.clip((_x_batch.data[m] + 1.0) / 2.0, 0.0, 1.0).reshape(
        # (config.img_channel, config.img_width, config.img_width)), interpolation="none")
        pylab.axis("off")
    pylab.savefig("{}/reconstruction_{}.png".format(visualization_dir, epoch))
    # pylab.show()
项目:PyME    作者:vikramsunkara    | 项目源码 | 文件源码
def plot_2D_heat_map(states,p,labels, inter=False):
    import pylab as pl
    X = np.unique(states[0,:])
    Y = np.unique(states[1,:])
    X_len = len(X)
    Y_len = len(Y)
    Z = np.zeros((X.max()+1,Y.max()+1))
    for i in range(len(p)):
        Z[states[0,i],states[1,i]] = p[i]
    pl.clf()    
    pl.imshow(Z.T, origin='lower')
    pl.xlabel(labels[0])
    pl.ylabel(labels[1])
    if inter== True:
        pl.draw()
    else:
        pl.show()
项目:keras    作者:NVIDIA    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_dim_ordering() == 'th':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close()
项目:unrolled-gan    作者:musyoku    | 项目源码 | 文件源码
def tile_binary_images(x, dir=None, filename="x", row=10, col=10):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(col * 2, row * 2)
    pylab.clf()
    pylab.gray()
    for m in range(row * col):
        pylab.subplot(row, col, m + 1)
        pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
        pylab.axis("off")
    pylab.savefig("{}/{}.png".format(dir, filename))
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:LSGAN    作者:musyoku    | 项目源码 | 文件源码
def tile_binary_images(x, dir=None, filename="x", row=10, col=10):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(col * 2, row * 2)
    pylab.clf()
    pylab.gray()
    for m in range(row * col):
        pylab.subplot(row, col, m + 1)
        pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
        pylab.axis("off")
    pylab.savefig("{}/{}.png".format(dir, filename))
项目:adgm    作者:musyoku    | 项目源码 | 文件源码
def tile_binary_images(x, dir=None, filename="x"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    pylab.gray()
    for m in range(100):
        pylab.subplot(10, 10, m + 1)
        pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
        pylab.axis("off")
    pylab.savefig("{}/{}.png".format(dir, filename))
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
def generate(self, filename, show=True):
        '''Generate a sample sequence, plot the resulting piano-roll and save
it as a MIDI file.

filename : string
  A MIDI file will be created at this location.
show : boolean
  If True, a piano-roll of the generated sequence will be shown.'''

        piano_roll = self.generate_function()
        midiwrite(filename, piano_roll, self.r, self.dt)
        if show:
            extent = (0, self.dt * len(piano_roll)) + self.r
            pylab.figure()
            pylab.imshow(piano_roll.T, origin='lower', aspect='auto',
                         interpolation='nearest', cmap=pylab.cm.gray_r,
                         extent=extent)
            pylab.xlabel('time (s)')
            pylab.ylabel('MIDI note number')
            pylab.title('generated piano-roll')
项目:variational-autoencoder    作者:musyoku    | 项目源码 | 文件源码
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    if image_channel == 1:
        pylab.gray()
    for m in range(100):
        pylab.subplot(10, 10, m + 1)
        if image_channel == 1:
            pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none")
        elif image_channel == 3:
            pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none")
        pylab.axis("off")
    pylab.savefig("%s/reconstructed_x.png" % dir)
项目:keras-101    作者:burness    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_dim_ordering() == 'th':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close()
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def convert16to8(self, smooth = False):
        if smooth:
            matout = self.smooth
        else:
            matout = self.image
        p = np.percentile(matout, 98)
        lowp = np.percentile(matout, 1)
        matout -= lowp
        if p == 0:
            p = np.max(matout)
        #print lowp, p, np.max(matout)
        matout[matout < 0] = 0
        matout[matout > p] = p
        #pylab.imshow(matout/p*255, 'gray')
        #pylab.show()
        return np.array(matout/p*255, np.uint8)
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def removeIllumination2(self, size, title = ''):
        out = ndimage.filters.gaussian_filter(self.image, size)
        pylab.figure()
        pylab.subplot(2,2,1)
        pylab.axis('off')
        pylab.imshow(self.image)
        pylab.subplot(2,2,2)
        pylab.axis('off')
        pylab.imshow(out)
        pylab.subplot(2,2,3)
        pylab.axis('off')
        pylab.imshow(self.image - out)
        pylab.subplot(2,2,4)
        pylab.axis('off')
        pylab.imshow(self.smooth - out)
        if title != '':
            pylab.savefig(title)
            pylab.close()
        else:
            pylab.show()
        self.smooth -= out
        return self.image - out
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
    # Receptive Fields Summary
    try:
        W = layer.W
    except:
        W = layer
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape) 
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

    fig = mpl.figure(figOffset); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,np.shape(fields)[0]):
        im = grid[i].imshow(fields[i],cmap=cmap); 

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    # 
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    try:
        W = layer.output
    except:
        W = layer
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf(); 

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
    # Receptive Fields Summary
    W = layer.W
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    fieldsN = min(fields.shape[0],maxFields)
    perRow = int(math.floor(math.sqrt(fieldsN)))
    perColumn = int(math.ceil(fieldsN/float(perRow)))

    fig = mpl.figure(figName); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,fieldsN):
        im = grid[i].imshow(fields[i],cmap=cmap);

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    #
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    W = layer.output
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf();

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_performance(file_name, triggers, lims=(150,150)):

    params          = CircusParser(file_name)
    N_e             = params.getint('data', 'N_e')
    N_total         = params.getint('data', 'N_total')
    sampling_rate   = params.getint('data', 'sampling_rate')
    do_temporal_whitening = params.getboolean('whitening', 'temporal')
    do_spatial_whitening  = params.getboolean('whitening', 'spatial')
    spike_thresh     = params.getfloat('detection', 'spike_thresh')
    file_out_suff    = params.get('data', 'file_out_suff')
    N_t              = params.getint('detection', 'N_t')
    nodes, edges     = get_nodes_and_edges(params)
    chunk_size       = N_t

    if do_spatial_whitening:
        spatial_whitening  = load_data(params, 'spatial_whitening')
    if do_temporal_whitening:
        temporal_whitening = load_data(params, 'temporal_whitening')

    thresholds       = load_data(params, 'thresholds')    

    try:
        result    = load_data(params, 'results')
    except Exception:
        result    = {'spiketimes' : {}, 'amplitudes' : {}}

    curve     = numpy.zeros((len(triggers), len(result['spiketimes'].keys()), lims[1]+lims[0]), dtype=numpy.int32)
    count     = 0

    for count, t_spike in enumerate(triggers):
        for key in result['spiketimes'].keys():
            elec  = int(key.split('_')[1])
            idx   = numpy.where((result['spiketimes'][key] > t_spike - lims[0]) & (result['spiketimes'][key] <  t_spike + lims[0]))
            curve[count, elec, t_spike - result['spiketimes'][key][idx]] += 1
    pylab.subplot(111)
    pylab.imshow(numpy.mean(curve, 0), aspect='auto') 
    return curve
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_whitening(data):
    pylab.subplot(121)
    pylab.imshow(data['spatial'], interpolation='nearest')
    pylab.title('Spatial')
    pylab.xlabel('# Electrode')
    pylab.ylabel('# Electrode')
    pylab.colorbar()
    pylab.subplot(122)
    pylab.title('Temporal')
    pylab.plot(data['temporal'])
    pylab.xlabel('Time [ms]')
    x, y = pylab.xticks()
    pylab.xticks(x, (x-x[-1]//2)//10)
    pylab.tight_layout()
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def get_performance(file_name, name):

    a, b            = os.path.splitext(os.path.basename(file_name))
    file_name, ext  = os.path.splitext(file_name)
    file_out        = os.path.join(os.path.abspath(file_name), a)
    data            = {}
    result          = h5py.File(file_out + '.basis.hdf5')
    data['spatial']  = result.get('spatial')[:]
    data['temporal'] = numpy.zeros(61) #result.get('temporal')[:]

    pylab.figure()
    pylab.subplot(121)
    pylab.imshow(data['spatial'], interpolation='nearest')
    pylab.title('Spatial')
    pylab.xlabel('# Electrode')
    pylab.ylabel('# Electrode')
    pylab.colorbar()
    pylab.subplot(122)
    pylab.title('Temporal')
    pylab.plot(data['temporal'])
    pylab.xlabel('Time [ms]')
    x, y = pylab.xticks()
    pylab.xticks(x, (x-x[-1]//2)//10)
    pylab.tight_layout()
    plot_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
    plot_path = os.path.join(plot_path, 'plots')
    plot_path = os.path.join(plot_path, 'whitening')
    if not os.path.exists(plot_path):
        os.makedirs(plot_path)
    output = os.path.join(plot_path, '%s.pdf' %name)
    pylab.savefig(output)

    return data
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
def showlabels(x,n=7):
    pylab.imshow(where(x>0,x%n+1,0),cmap=pylab.cm.gist_stern)
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
def plotgrid(data,d=10,shape=(30,30)):
    """Plot a list of images on a grid."""
    ion()
    gray()
    clf()
    for i in range(min(d*d,len(data))):
        subplot(d,d,i+1)
        row = data[i]
        if shape is not None: row = row.reshape(shape)
        imshow(row)
    ginput(1,timeout=0.1)
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
def showrgb(r,g=None,b=None):
    if g is None: g = r
    if b is None: b = r
    imshow(array([r,g,b]).transpose([1,2,0]))
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
def showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):
    if "cmap" not in kw: kw["cmap"] = cm.gray
    if "interpolation" not in kw: kw["interpolation"] = "nearest"
    n = minimum(n,len(l))
    if cols is None: cols = int(sqrt(n))
    rows = (n+cols-1)//cols
    for i in range(n):
        pylab.xticks([]) ;pylab.yticks([])
        pylab.subplot(rows,cols,i+1)
        pylab.imshow(l[i],**kw)
        if titles is not None: pylab.title(str(titles[i]))
        if xlabels is not None: pylab.xlabel(str(xlabels[i]))
        if ylabels is not None: pylab.ylabel(str(ylabels[i]))
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def edgeplot(self, TT, ps):
        for ei,X in enumerate(self.edges):
            (i, j) = X[:2]
            Ta = TT[i]
            Tb = TT[j]
            plt.clf()
            if len(Ta) > 1000:
                nbins = 101
                ra = np.hstack((Ta.ra, Tb.ra))
                dec = np.hstack((Ta.dec, Tb.dec))
                H,xe,ye = np.histogram2d(ra, dec, bins=nbins)
                (matchRA, matchDec, dr,dd) = self.edge_matches(ei, goodonly=True)
                G,xe,ye = np.histogram2d(matchRA, matchDec, bins=(xe,ye))
                assert(G.shape == H.shape)
                img = antigray(H / H.max())
                img[G>0,:] = matplotlib.cm.hot(G[G>0] / H[G>0])
                ax = setRadecAxes(xe[0], xe[-1], ye[0], ye[-1])
                plt.imshow(img, extent=(min(xe), max(xe), min(ye), max(ye)),
                           aspect='auto', origin='lower', interpolation='nearest')
                plt.axis(ax)

            else:
                self.plotallstars([Ta,Tb])
                self.plotmatchedstars(ei)
                plt.xlabel('RA (deg)')
                plt.ylabel('Dec (deg)')
            ps.savefig()

    # one plot per edge
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self, overlay_alpha=0.5):
        import pylab as pl
        #pl.imshow(self.image)
        tinted = ((1-overlay_alpha)*self.image
                  + overlay_alpha*colorize(np.argmax(self.features, 0), self.colors))
        from skimage.segmentation import mark_boundaries
        tinted = mark_boundaries(tinted.clip(0, 255).astype(np.uint8), np.argmax(self.features, 0))
        pl.imshow(tinted)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_grids(self):
        import pylab as pl
        pl.imshow(self.rectified)
        for facade in self.facade_candidates:
            facade.plot()
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_regions(self, fill=True, alpha=0.5):
        import pylab as pl
        pl.imshow(self.rectified)
        for facade in self.facade_candidates:
            assert isinstance(facade, FacadeCandidate)
            facade.plot_regions(fill=fill, alpha=alpha)
项目:pCVR    作者:xjtushilei    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close()
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def snapshot(self, fn = None, clip_ratio = None):
        import matplotlib.pylab as pylab
        pylab.figure(2)
        self.transfer_function.show()
        pylab.draw()
        im = Camera.snapshot(self, fn, clip_ratio)
        pylab.figure(1)
        pylab.imshow(im / im.max())
        pylab.draw()
        self.frames.append(im)
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def plot_channel(image, name, cmap='gist_heat', log=True, dex=3, zero_factor=1.0e-10, 
                 label=None, label_color='w', label_size='large'):
    """
    This function will plot a single channel. *image* is an array shaped like
    (N,M), *name* is the pefix for the output filename.  *cmap* is the name of
    the colormap to apply, *log* is whether or not the channel should be
    logged.  Additionally, you may optionally specify the minimum-value cutoff
    for scaling as *dex*, which is taken with respect to the minimum value of
    the image.  *zero_factor* applies a minimum value to all zero-valued
    elements.  Optionally, *label*, *label_color* and *label_size* may be
    specified.
    """
    import matplotlib
    import pylab
    Nvec = image.shape[0]
    image[np.isnan(image)] = 0.0
    ma = image[image>0.0].max()
    image[image==0.0] = ma*zero_factor
    if log:
        mynorm = matplotlib.colors.LogNorm(ma/(10.**dex), ma)

    pylab.clf()
    pylab.gcf().set_dpi(100)
    pylab.gcf().set_size_inches((Nvec/100.0, Nvec/100.0))
    pylab.gcf().subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.0, hspace=0.0)
    mycm = pylab.cm.get_cmap(cmap)
    if log:
        pylab.imshow(image,cmap=mycm, norm=mynorm, interpolation='nearest')
    else:
        pylab.imshow(image,cmap=mycm, interpolation='nearest')
    if label is not None:
        pylab.text(20, 20,label, color = label_color, size=label_size) 
    pylab.savefig("%s_%s.png" % (name,cmap))
    pylab.clf()
项目:NADE    作者:MarcCote    | 项目源码 | 文件源码
def main():
    parser = buildArgsParser()
    args = parser.parse_args()

    # Load experiments hyperparameters
    try:
        hyperparams = smartutils.load_dict_from_json_file(pjoin(args.experiment, "hyperparams.json"))
    except:
        hyperparams = smartutils.load_dict_from_json_file(pjoin(args.experiment, '..', "hyperparams.json"))

    model = load_model(args.experiment)
    print(str(model))

    with Timer("Generating {} samples from Conv Deep NADE".format(args.count)):
        sample = model.build_sampling_function(seed=args.seed)
        samples, probs = sample(args.count, return_probs=True, ordering_seed=args.seed)

    if args.out is not None:
        outfile = pjoin(args.experiment, args.out)
        with Timer("Saving {0} samples to '{1}'".format(args.count, outfile)):
            np.save(outfile, samples)

    if args.view:
        import pylab as plt
        from convnade import vizu
        if hyperparams["dataset"] == "binarized_mnist":
            image_shape = (28, 28)
        else:
            raise ValueError("Unknown dataset: {0}".format(hyperparams["dataset"]))

        plt.figure()
        data = vizu.concatenate_images(samples, shape=image_shape, border_size=1, clim=(0, 1))
        plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
        plt.title("Samples")

        plt.figure()
        data = vizu.concatenate_images(probs, shape=image_shape, border_size=1, clim=(0, 1))
        plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
        plt.title("Probs")

        plt.show()