Exemple #1
0
def plot_imgs(imgs, ratios=[1, 1]):
    plt.gray()
    gs = gridspec.GridSpec(1, len(imgs), width_ratios=ratios)
    for i in range(len(imgs)):
        plt.subplot(gs[i])
        plt.imshow(imgs[i])
    return gs
Exemple #2
0
 def __init__(self,panelName,outBaseDir):
     print("""Keybindings:
         x : restart current rectangle
         n : start next rectangle
         w : save results and move to next image
         = : (twice) terminate the program (without saving)
         """)
     self.outBaseDir=outBaseDir
     self.quit=False
     self.panelName=panelName
     tif = TIFF.open(panelName, mode='r')
     panel = tif.read_image()
     if (np.max(panel>255)):
         dmax=65535.0
     else:
         dmax=255.0
     self.panel=np.uint8(255*(panel/dmax)) #16-> 8 bits
     self.crops=[]
     self.curCrop=[]
     self.rects=[]
     self.curRect=[]
     self.fig, self.ax = plt.subplots()
     self.fig.canvas.mpl_connect('button_press_event', self.onclick)
     self.fig.canvas.mpl_connect('key_press_event', self.press)
     plt.gray()
     plt.title(basename(panelName))
     self.ax.imshow(self.panel)
     plt.show()
Exemple #3
0
def plot_imgs(imgs, ratios=[1, 1]):
    plt.gray()
    gs = gridspec.GridSpec(1, len(imgs), width_ratios=ratios)
    for i in range(len(imgs)):
        plt.subplot(gs[i])
        plt.imshow(imgs[i])
    return gs
Exemple #4
0
def plot_from_xml(fn1=None, fnx=None, window=7):
    """Makes a dot-plot from xml and fasta sequence.

    :param fn1: Fasta file.
    :param fnx: XML file.
    :param window: Threshold, for example (5)'
    :return: None
    """
    if fn1 is not None and fnx is not None:
        with open(fn1, 'r') as fh, open(fnx, 'r') as fx:
            window = int(window)
            file1 = NCBIXML.read(fh)
            filex = NCBIXML.read(fx)
            seq_one = str(file1.seq).upper()
            seq_two = str(filex.seq).upper()
            data = [[(seq_one[i:i + window] != seq_two[j:j + 5]) for j in range(len(seq_one) - window)] for i
                    in range(len(seq_two) - window)]

            pylab.gray()
            pylab.imshow(data)
            pylab.xlabel(
                '{} (length {} bp)'.format(file1.seq, len(file1.seq)))
            pylab.ylabel(
                '{} (length {} bp)'.format(filex.seq, len(filex.seq)))
            pylab.title('Dot plot using window size {}\n(allowing no mis-matches)'.format(window))
            pylab.show()
Exemple #5
0
def rec_test(file_name, sino_start, sino_end):

    print "\n#### Processing " + file_name
    sino_start = sino_start + 200
    sino_end = sino_start + 2
    print "Test reconstruction of slice [%d]" % sino_start
    # Read HDF5 file.
    prj, flat, dark = tomopy.io.exchange.read_aps_32id(file_name, sino=(sino_start, sino_end))

    # Manage the missing angles:
    theta = tomopy.angles(prj.shape[0])
    prj = np.concatenate((prj[0 : miss_angles[0], :, :], prj[miss_angles[1] + 1 : -1, :, :]), axis=0)
    theta = np.concatenate((theta[0 : miss_angles[0]], theta[miss_angles[1] + 1 : -1]))

    # normalize the prj
    prj = tomopy.normalize(prj, flat, dark)

    # reconstruct
    rec = tomopy.recon(prj, theta, center=best_center, algorithm="gridrec", emission=False)

    # Write data as stack of TIFs.
    tomopy.io.writer.write_tiff_stack(rec, fname=output_name)

    print "Slice saved as [%s_00000.tiff]" % output_name
    # show the reconstructed slice
    pl.gray()
    pl.axis("off")
    pl.imshow(rec[0])
    def __init__(self, ax, collection, mmc, img):
        self.colornormalizer = Normalize(vmin=0, vmax=1, clip=False)
        self.scat = plt.scatter(img[:, 0], img[:, 1], c=mmc.classvec)
        plt.gray()
        plt.setp(ax.get_yticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.xaxis.set_tick_params(size=0)
        self.img = img
        self.canvas = ax.figure.canvas
        self.collection = collection
        #self.alpha_other = alpha_other
        self.mmc = mmc
        self.prevnewclazz = None

        self.xys = collection
        self.Npts = len(self.xys)
        
        self.lockedset = set([])

        self.lasso = LassoSelector(ax, onselect=self.onselect)#, lineprops = {:'prism'})
        self.lasso.disconnect_events()
        self.lasso.connect_event('button_press_event', self.lasso.onpress)
        self.lasso.connect_event('button_release_event', self.onrelease)
        self.lasso.connect_event('motion_notify_event', self.lasso.onmove)
        self.lasso.connect_event('draw_event', self.lasso.update_background)
        self.lasso.connect_event('key_press_event', self.onkeypressed)
        #self.lasso.connect_event('button_release_event', self.onrelease)
        self.ind = []
        self.slider_axis = plt.axes(slider_coords, visible = False)
        self.slider_axis2 = plt.axes(obj_fun_display_coords, visible = False)
        self.in_selection_slider = None
        newws = list(set(range(len(self.collection))) - self.lockedset)
        self.mmc.new_working_set(newws)
        self.lasso.line.set_visible(False)
Exemple #7
0
def show_map(map):
    num = len(map)
    pylab.figure()
    pylab.gray()
    for i in xrange(num):
        pylab.subplot(1, num, i + 1)
        pylab.imshow(squareStack(map[i]))
    pylab.show()
Exemple #8
0
def show_beta(beta):
    size, channels = beta.shape
    beta = beta.T.reshape((channels, int(np.sqrt(size)), int(np.sqrt(size))))
    beta = squareStack(beta)
    pylab.figure()
    pylab.gray()
    pylab.imshow(beta)
    pylab.show()
Exemple #9
0
def testFaceImg():
    read_file=open(imgPath+'olivettifaces.pkl','rb')
    faces=pickle.load(read_file)
    read_file.close()
    img1=faces[1].reshape(57,47)
    pylab.imshow(img1)
    pylab.gray()
    pylab.show()
def plot_harris_points(image, filtered_coords):
    #绘制Harris检测结果
    pylab.figure()
    pylab.gray()
    pylab.imshow(image)
    pylab.plot([p[1] for p in filtered_coords],
               [p[0] for p in filtered_coords], '*')
    pylab.axis('off')
    pylab.show()
Exemple #11
0
def contour(image):
    """
    contour plot
    """
    plt.figure()
    image = image.convert('L')
    plt.gray()
    plt.contour(image, origin='image')
    plt.axis('equal')
Exemple #12
0
def plot_representation(n_subplot_vertical, n_suplot_horizontal, location, filename, label):
    # let's use this inappropriatly named function
    [n_inputs, n_neurons, weights] = weights_filename_to_array(filename)
    representations = weights

    pylab.subplot(n_subplot_vertical, n_suplot_horizontal, location)
    pylab.imshow(representations, aspect="auto", interpolation="nearest")
    pylab.xlabel(label)
    pylab.gray()
Exemple #13
0
def plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal, location, filename, do_transpose, label):

    [n_inputs, n_neurons, weights] = weights_filename_to_array(filename)
    if do_transpose:
        weights = numpy.transpose(weights)

    pylab.subplot(nsubplot_vertical, nsubplot_horizontal, location)
    pylab.imshow(weights, aspect="auto", interpolation="nearest")
    pylab.xlabel(label)
    pylab.gray()
Exemple #14
0
def plot_representation(n_subplot_vertical, n_suplot_horizontal, location,
                        filename, label):
    # let's use this inappropriatly named function
    [n_inputs, n_neurons, weights] = weights_filename_to_array(filename)
    representations = weights

    pylab.subplot(n_subplot_vertical, n_suplot_horizontal, location)
    pylab.imshow(representations, aspect='auto', interpolation='nearest')
    pylab.xlabel(label)
    pylab.gray()
Exemple #15
0
def plot_feature_maps(layer, num_features, filename):
    plt.figure()
    plt.gray()
    layer_array = np.array(layer)
    for i in range(num_features):
        plt.subplot(num_features / 10, 10, i + 1)
        plt.axis("off")
        plt.imshow(layer_array[0, :, :, i])
    plt.savefig("../Out/" + filename + ".png")
    plt.close()
Exemple #16
0
def plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal, location,
                       filename, do_transpose, label):

    [n_inputs, n_neurons, weights] = weights_filename_to_array(filename)
    if do_transpose:
        weights = numpy.transpose(weights)

    pylab.subplot(nsubplot_vertical, nsubplot_horizontal, location)
    pylab.imshow(weights, aspect='auto', interpolation='nearest')
    pylab.xlabel(label)
    pylab.gray()
Exemple #17
0
def gray(image):
    """
    plot gray image
    :param image: PIL.Image object
    :return:
    """
    plt.figure()
    image = image.convert('L')
    aimage = np.array(image)
    print(aimage.shape, aimage.dtype)
    plt.gray()
    plt.imshow(np.array(aimage))
Exemple #18
0
def save_energy_map(img):
    im = rgb2gray(imageio.imread(img)) # RGB image to gray scale
    plt.gray()
    plt.figure(figsize=(20,10))
    plt.subplot(221)
    plt.imshow(im)
    plt.title('original', size=10)
    plt.subplot(222)
    edges = filters.sobel(im)
    plt.imshow(edges)
    plt.title('sobel', size=10)
    plt.savefig('../energy/energymap.png', dpi = 100, bbox_inches='tight')
Exemple #19
0
 def save_D_figs(self, patchsize, dirname='./image/'):
     from utils.image_patch_utils import gen_patch_image
     import matplotlib
     matplotlib.use('Agg')
     import matplotlib.pylab as plt
     plt.gray()
     for i in range(len(self._ancestor_history)):
         D = self._gen_D(i)
         patch_img = gen_patch_image(D, patchsize, emphasis=True)
         plt.imshow(patch_img)
         plt.axis('off')
         plt.savefig(dirname + 'bases_' + str(i) + '.png', bbox_inches='tight')
 def show_image(self):
     n = 8  # how many digits we will display
     plt.figure(figsize=(20, 4))
     for i in range(n):
         # display original
         ax = plt.subplot(2, n, i + 1)
         plt.imshow(self.images[i])
         plt.gray()
         ax.get_xaxis().set_visible(False)
         ax.get_yaxis().set_visible(False)
         ax.title.set_text(self.labels[i])
     plt.show()
Exemple #21
0
def im_hist_eq_2(image):
    aimage = np.array(image.convert('L'))
    ae_image, cdf = histeq(aimage)

    plt.figure()
    plt.gray()

    plt.subplot(211)
    plt.imshow(aimage)

    plt.subplot(212)
    plt.imshow(ae_image)
    plt.axis('off')
Exemple #22
0
 def save_images(self, n_image, result):
     pic = np.zeros((n_image * self.n_canvas, n_image * self.n_canvas))
     images = np.squeeze(self.__call__(False, n_image))
     images = images.reshape((-1, self.n_canvas, self.n_canvas))
     for i in six.moves.range(n_image):
         for j in six.moves.range(n_image):
             pic[self.n_canvas * i:self.n_canvas * i + self.n_canvas,
                 self.n_canvas * j:self.n_canvas * j + self.n_canvas] = \
                 images[i * n_image + j]
     plt.imshow(pic, vmin=-1, vmax=1, interpolation='none')
     plt.gray()
     plt.savefig('{}/image_{}.png'.format(result, self.n_saved))
     self.n_saved += 1
Exemple #23
0
def test_rect():
    im = array(Image.open('face.bmp').convert('L'))
    pts = array([[90, 260], [90, 530], [400, 530], [400, 260]])
    i0, j0 = pts.min(axis=0)
    i1, j1 = pts.max(axis=0)
    plt.figure()
    plt.subplot(1, 2, 1)
    plt.gray()
    plt.imshow(im)
    add_rect(i0, j0, i1 - i0, j1 - j0)
    plt.subplot(1, 2, 2)
    box = im[i0:i1, j0:j1]
    plt.imshow(box)
    plt.show()
Exemple #24
0
def test_rect():
    im = array(Image.open('face.bmp').convert('L'))
    pts = array([[90, 260], [90, 530], [400, 530], [400, 260]])
    i0, j0 = pts.min(axis=0)
    i1, j1 = pts.max(axis=0)
    plt.figure()
    plt.subplot(1, 2, 1)
    plt.gray()
    plt.imshow(im)
    add_rect(i0, j0, i1 - i0, j1 - j0)
    plt.subplot(1, 2, 2)
    box = im[i0:i1, j0:j1]
    plt.imshow(box)
    plt.show()
Exemple #25
0
def save_beta_lrf(beta, dir, name):
    global img_count
    save_path = os.path.join('/home', username, 'images', dir)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    pic_path = os.path.join(save_path, str(img_count) + name + '.png')
    img_count += 1
    size, channels = beta.shape
    beta = beta.T.reshape((channels, int(np.sqrt(size)), int(np.sqrt(size))))
    pylab.figure()
    pylab.gray()
    pylab.imshow(squareStack(beta), interpolation=interpolation)
    pylab.savefig(pic_path)
    pylab.close()
Exemple #26
0
def save_map_lrf(map, dir, name):
    global img_count
    save_path = os.path.join('/home', username, 'images', dir)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    pic_path = os.path.join(save_path, str(img_count) + name + '.png')
    img_count += 1
    num = len(map)
    pylab.figure()
    pylab.gray()
    for i in xrange(num):
        pylab.subplot(1, num, i + 1)
        pylab.imshow(squareStack(map[i]), interpolation=interpolation)
    pylab.savefig(pic_path)
    pylab.close()
def make_onechannel_movie( image_data_file, outfile_name, lower_threshold = 0 ):
	
	###This function takes a .tif stack as input and makes an .mp4 movie.
	
	###Parameters:
	
	###image_data: numpy array containing images; TxYxX
	###outfile_name: output file to write to; should be .mp4
	###lower_threshold: pixel values will be thresholded frame-by-frame at the percentile chosen as 'lower_threshold'. Default is 0.
	
	import matplotlib
	matplotlib.use("Agg")
	import matplotlib.pylab as pt
	import matplotlib.animation as manimation
	import numpy
	from skimage import io
	
	image_data = io.imread( image_data_file )
	
	ntsteps, nx, ny = image_data.shape
	
	figdimx = int(nx/200)
	figdimy = int(ny/200)
	
	FFMpegWriter = manimation.writers['ffmpeg']
	metadata = dict(title=outfile_name.strip('.mp4'), artist='Matplotlib', comment='Movie support!')
	writer = FFMpegWriter(fps=15, metadata=metadata)
	
	pt.gray()
	
	fig = pt.figure(figsize=(figdimx,figdimy))
	l = pt.imshow(image_data[0,:,:].T/numpy.max(image_data[0,:,:]))
	ax = pt.gca()
	with writer.saving(fig, outfile_name, dpi=400):
		for t in range(ntsteps):
			
			#drift_mask = numpy.nonzero(image_data[t, :, :]) ###
		
			frame_min = numpy.percentile(image_data[t, :, :], lower_threshold)
			
			frame_max = numpy.max(image_data[t, :, :])
			
			l.set_data( (image_data[t,:,:].T - frame_min)/(frame_max - frame_min))
			ax.set_yticks([])
			ax.set_xticks([])
			
			writer.grab_frame()
Exemple #28
0
def save_beta_mch(beta, mch, dir, name):
    global img_count
    save_path = os.path.join('/home', username, 'images', dir)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    pic_path = os.path.join(save_path, str(img_count) + name + '.png')
    img_count += 1
    size, channels = beta.shape
    size /= mch
    beta = np.split(beta.T, mch, axis=1)
    beta = np.concatenate(beta, axis=0)
    beta = beta.reshape((mch * channels, int(np.sqrt(size)), int(np.sqrt(size))))
    pylab.figure()
    pylab.gray()
    pylab.imshow(squareStack(beta))
    pylab.savefig(pic_path)
    pylab.close()
Exemple #29
0
def save_beta_fc(beta):
    save_path = os.path.join('/home', username, 'images', time.asctime())
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    n_feature, n_hidden = beta.shape
    num = int(np.ceil(n_hidden / 100.))
    img_side = int(np.sqrt(n_feature))
    img = beta.T.reshape((-1, img_side, img_side))
    pylab.figure()
    pylab.gray()
    for i in xrange(num):
        one_img = img[:100]
        img = img[100:]
        pylab.imshow(squareStack(one_img), interpolation=interpolation)
        pic_path = os.path.join(save_path, str(i) + '.png')
        pylab.savefig(pic_path)
    pylab.close()
Exemple #30
0
def draw_out_put_digit(data, n, ans, recog):
    """
    学習済みのモデルが判定した画像を描画します.
    @param data 画像データ 
    @param n 画像の通し番号
    @param ans 正解ラベル
    @param recog 推定した数字
    """
    plt.subplot(10, 10, n)
    Z = data.reshape(SIZE, SIZE)
    Z = Z[::-1, :]
    plt.xlim(0, 27)
    plt.ylim(0, 27)
    plt.pcolor(Z)
    plt.title('ans=%d, recog=%d' % (ans, recog), size=8)
    plt.gray()
    plt.tick_params(labelbottom='off')
    plt.tick_params(labelleft='off')
def restruct_picture(x_test, decoded_imgs, dim):
    n = 10  # how many digits we will display
    plt.figure(figsize=(20, 4))
    for i in range(n):
        # display original
        ax = plt.subplot(2, n, i + 1)
        plt.imshow(x_test[i].reshape(dim, dim))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        # display reconstruction
        ax = plt.subplot(2, n, i + 1 + n)
        plt.imshow(decoded_imgs[i].reshape(dim, dim))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    plt.show()
def plot_matches(img1, img2, locs1, locs2, matchscores, show_below=True):
    pylab.figure()
    pylab.gray()
    img3 = append_images(img1, img2)
    if show_below:
        img3 = np.vstack((img3, img3))
    pylab.imshow(img3)
    clos1 = img1.shape[1]
    count = 0
    for i, m in enumerate(matchscores):
        if (m > 0):
            pylab.plot([locs1[i][1], locs2[m][1] + clos1],
                       [locs1[i][0], locs2[m][0]], 'c')
            if (count > 10):
                break
            count += 1
    pylab.axis('off')
    pylab.show()
Exemple #33
0
 def _update_image(self):
   " redraw image "
   if self.AxesImage is not None: self.AxesImage.remove();
   self.AxesImage = self.axis.imshow(self.image.T,cmap=plt.gray(),\
       origin='lower',aspect='equal',extent=self.imginfo['extent']);
   self.axis.set_xlabel("x [%s]" % self.imginfo['xunits']);
   self.axis.set_ylabel("y [%s]" % self.imginfo['yunits']);
   self.axis.set_xlim(*self.imginfo['extent'][0:2]);
   self.axis.set_ylim(*self.imginfo['extent'][2:4]);
   self._update();
Exemple #34
0
def array_manipulate(image):
    aimage = np.array(image.convert('L'))
    ai_image = 255 - aimage  # f(x) = 255 - x
    ac_image = (100.0 / 255) * aimage + 100  # f(x) = (100 / 255)* x + 100
    aq_image = 255.0 * (aimage / 255.0)**2  # f(x) = 255 * (x/255)
    plt.figure()
    plt.gray()

    plt.subplot(311)
    plt.imshow(ai_image)
    plt.axis('off')

    plt.subplot(312)
    plt.imshow(ac_image)
    plt.axis('off')

    plt.subplot(313)
    plt.imshow(aq_image)
    plt.axis('off')
        def test_ff_on_image(test_image_name):

            print test_image_name
            test_image = double(asarray(PIL.Image.open(test_image_name)))
            if len(test_image.shape) == 3:
                test_image = mean(test_image, 2)

            radial_ff = FastRadialFeatureFinder()
            radial_ff.target_kpixels = 3.0
            radial_ff.correct_downsampling = True
            radial_ff.radius_steps = 20
            radial_ff.min_radius_fraction = 1. / 200
            radial_ff.max_radius_fraction = 1. / 5
            starburst_ff = \
                CLSubpixelStarburstFeatureFinder()
            composite_ff = CompositeFeatureFinder(radial_ff, starburst_ff)

            composite_ff.analyze_image(test_image, {'timestamp': 0})
            features = composite_ff.get_result()

            # do it twice to allow compilation
            composite_ff.analyze_image(test_image)
            features = composite_ff.get_result()

            plt.figure()
            plt.imshow(test_image, interpolation='nearest')
            plt.gray()
            plt.hold(True)
            cr_position = features['cr_position']
            pupil_position = features['pupil_position']

            plt.plot([cr_position[1]], [cr_position[0]], 'g+')
            plt.plot([pupil_position[1]], [pupil_position[0]], 'g+')

            sb = features['starburst']
            cr_bounds = sb['cr_boundary']
            pupil_bounds = sb['pupil_boundary']

            for b in cr_bounds:
                plt.plot([b[1]], [b[0]], 'rx')

            for b in pupil_bounds:
                plt.plot([b[1]], [b[0]], 'gx')
        def test_ff_on_image(test_image_name):

            print test_image_name
            test_image = double(asarray(PIL.Image.open(test_image_name)))
            if len(test_image.shape) == 3:
                test_image = mean(test_image, 2)

            radial_ff = FastRadialFeatureFinder()
            radial_ff.target_kpixels = 3.0
            radial_ff.correct_downsampling = True
            radial_ff.radius_steps = 20
            radial_ff.min_radius_fraction = 1. / 200
            radial_ff.max_radius_fraction = 1. / 5
            starburst_ff = \
                CLSubpixelStarburstEyeFeatureFinder()
            composite_ff = CompositeEyeFeatureFinder(radial_ff, starburst_ff)

            composite_ff.analyze_image(test_image, {'timestamp': 0})
            features = composite_ff.get_result()

            # do it twice to allow compilation
            composite_ff.analyze_image(test_image)
            features = composite_ff.get_result()

            plt.figure()
            plt.imshow(test_image, interpolation='nearest')
            plt.gray()
            plt.hold(True)
            cr_position = features['cr_position']
            pupil_position = features['pupil_position']

            plt.plot([cr_position[1]], [cr_position[0]], 'g+')
            plt.plot([pupil_position[1]], [pupil_position[0]], 'g+')

            sb = features['starburst']
            cr_bounds = sb['cr_boundary']
            pupil_bounds = sb['pupil_boundary']

            for b in cr_bounds:
                plt.plot([b[1]], [b[0]], 'rx')

            for b in pupil_bounds:
                plt.plot([b[1]], [b[0]], 'gx')
Exemple #37
0
def plot_hidden_space(x_test, encode_func, zoom=0.5):
    encoded = encode_func(x_test)

    fig, ax = plt.subplots(figsize=(11, 11))
    imscatter(encoded[:, 0],
              encoded[:, 1],
              x_test.reshape((-1, 28, 28)),
              zoom=zoom,
              ax=ax)

    ax.spines['left'].set_position('center')
    ax.spines['bottom'].set_position('center')
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    plt.gray()
    plt.show()
def show_images(imnames, titles=None, rows=1, figsize=(30, 8)):

    images = [plt.imread(imname) for imname in flatten(imnames)]
    n_images = len(images)

    if titles is None: titles = ['Image (%d)' % i for i in range(n_images + 1)]
    elif type(titles) == str:
        titles = [titles + '(%d)' % i for i in range(n_images + 1)]

    fig = plt.figure(figsize=figsize)
    for n, (image, title) in enumerate(zip(images, titles)):
        a = fig.add_subplot(rows, np.ceil(n_images / float(rows)), n + 1)
        image = np.squeeze(image)
        if image.ndim == 2:
            plt.gray()
        plt.imshow(image)
        plt.axis('off')
        a.set_title(title, fontsize=20)
    # fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
    plt.show()
Exemple #39
0
def plot_from_fasta(fn1=None, fn2=None, window=7):
    """Makes a dot-plot two fasta files.

    :param fn1: Fasta file.
    :param fn2: Fasta file.
    :param window: Threshold, for example (5)
    :return: None
    """
    if fn1 is not None and fn2 is not None:
        with open(fn1, 'r') as fh1, open(fn2, 'r') as fh2:
            window = int(window)
            file1 = SeqIO.read(fh1, format='fasta')
            file2 = SeqIO.read(fh2, format='fasta')
            dict_one = {}
            dict_two = {}
            for (seq, section_dict) in [(str(file1.seq).upper(), dict_one),
                                        (str(file2.seq).upper(), dict_two)]:
                for i in range(len(seq) - window):
                    section = seq[i:i + window]
                    try:
                        section_dict[section].append(i)
                    except KeyError:
                        section_dict[section] = [i]
            matches = set(dict_one).intersection(dict_two)
            print('{} unique matches'.format(len(matches)))
            x, y = [], []
            for section in matches:
                for i in dict_one[section]:
                    for j in dict_two[section]:
                        x.append(i)
                        y.append(j)
            pylab.cla()
            pylab.gray()
            pylab.scatter(x, y)
            pylab.xlim(0, len(file1) - window)
            pylab.ylim(0, len(file2) - window)
            pylab.xlabel('{} (length {} bp)'.format(file1.id, len(file1.seq)))
            pylab.ylabel('{} (length {} bp)'.format(file2.id, len(file2.seq)))
            pylab.title('Dot plot using window size {}\n(allowing no mis-matches)'.format(window))
            pylab.show()
def main():
    valve = utils.valve_io.read_valve(sys.argv[1])
    image = valve["image"]


    # extract the patch
    patch_size = 30
    seg, smooth = filters.segmentation.segment_by_valve_patch(
            image, valve["i1"], 
            float(sys.argv[2]), (patch_size,patch_size))


       
    # display the image
    fig, (ax1,ax2,ax3) = plt.subplots(1,3)

    plt.gray()
    ax1.imshow(image)
    ax2.imshow(smooth)
    ax3.imshow(seg)


    plt.show()
Exemple #41
0
  def _reset_image(self):
    " redraw image "
    self.vmin = np.min(self.image);
    self.vmax = np.max(self.image);
    self.vmean= np.mean(self.image);
    self.cmap = plt.cm.gray;      

    if self.AxesImage is not None: self.AxesImage.remove();
    self.AxesImage = self.axis.imshow(self.image,cmap=plt.gray(),\
        extent=self.imginfo['extent'],**self.kwargs);
    self.axis.set_xlabel("%s [%s]" % (self.imginfo['xlabel'], self.imginfo['xunits']));
    self.axis.set_ylabel("%s [%s]" % (self.imginfo['ylabel'], self.imginfo['yunits']));
    self.axis.set_xlim(*self.imginfo['extent'][0:2]);
    self.axis.set_ylim(*self.imginfo['extent'][2:4]);
    self.set_style(self.currentstyle);
            #figsize = fig_bmp.size[0]/dpi, fig_bmp.size[1]/dpi

            #figure(figsize=figsize)
            
            #ax2.axis('scaled')
            
            #ax2.get_xaxis().set_ticks([]);
            #ax2.get_yaxis().set_ticks([]);

            ax3.get_xaxis().set_ticks([]);
            ax3.get_yaxis().set_ticks([]);

            #im2 = ax2.imshow(fig_bmp, origin='lower')
            #im2 = ax2.imshow(fig_bmp, origin='lower', cmap=pylab.gray())
            #im2 = ax2.imshow(fig_bmp, cmap=pylab.gray())
            im3 = ax3.imshow(fig_tv03, cmap=pylab.gray())
            
            pylab.savefig(filename+'.png',fmt='png',transparent=False,bbox_inches='tight');
            
            pylab.clf()
            
            
   # Merging to make .avi
   
   not_found_msg = """
       The mencoder command was not found;
       mencoder is used by this script to make an avi file from a set of pngs.
       It is typically not installed by default on linux distros because of
       legal restrictions, but it is widely available.
         """
   
            
            #figsize = fig_bmp.size[0]/dpi, fig_bmp.size[1]/dpi

            #figure(figsize=figsize)
            
            #ax2.axis('scaled')
            
            ax2.get_xaxis().set_ticks([]);
            ax2.get_yaxis().set_ticks([]);

            ax3.get_xaxis().set_ticks([]);
            ax3.get_yaxis().set_ticks([]);

            #im2 = ax2.imshow(fig_bmp, origin='lower')
            #im2 = ax2.imshow(fig_bmp, origin='lower', cmap=pylab.gray())
            im2 = ax2.imshow(fig_bmp, cmap=pylab.gray())
            im3 = ax3.imshow(fig_tv03)
            
            pylab.savefig(filename+'.png',fmt='png',transparent=False,bbox_inches='tight');
            
            pylab.clf()
            
            
   # Merging to make .avi
   
   not_found_msg = """
       The mencoder command was not found;
       mencoder is used by this script to make an avi file from a set of pngs.
       It is typically not installed by default on linux distros because of
       legal restrictions, but it is widely available.
         """
Exemple #44
0
def show(im, gray=True):
    plt.figure()
    if gray:
        plt.gray() 
    plt.imshow(im)
    plt.show()
#-----------------------------------------------------------------------

import astra
import numpy as np

vol_geom = astra.create_vol_geom(256, 256)
proj_geom = astra.create_proj_geom('parallel', 1.0, 384, np.linspace(0,np.pi,180,False))

# As before, create a sinogram from a phantom
import scipy.io
P = scipy.io.loadmat('phantom.mat')['phantom256']
proj_id = astra.create_projector('line',proj_geom,vol_geom)
sinogram_id, sinogram = astra.create_sino(P, proj_id, gpuIndex=0)

import matplotlib.pylab as pylab
pylab.gray()
pylab.figure(1)
pylab.imshow(P)
pylab.figure(2)
pylab.imshow(sinogram)

# Create a data object for the reconstruction
rec_id = astra.data2d.create('-vol', vol_geom)

# Set up the parameters for a reconstruction algorithm using the GPU
cfg = astra.astra_dict('SIRT_CUDA')
cfg['ReconstructionDataId'] = rec_id
cfg['ProjectionDataId'] = sinogram_id

# Available algorithms:
# SIRT_CUDA, SART_CUDA, EM_CUDA, FBP_CUDA (see the FBP sample)
Exemple #46
0
import numpy
from matplotlib import pylab
from PIL import Image
from conv import f

img = Image.open(open('./3wolfmoon.jpg'))
img = numpy.asarray(img, dtype='float64')/256

img_ = img.swapaxes(0,2).swapaxes(1,2).reshape(1,3,584,487)
#img_ = img.swapaxes(0,2).swapaxes(1,2).reshape(1,3,128,128)
filtered_img = f(img_)

pylab.subplot(1, 3, 1); pylab.axis('off'); pylab.imshow(img)
pylab.gray();
pylab.subplot(1, 3, 2); pylab.axis('off'); pylab.imshow(filtered_img[0,0,:,:])
pylab.subplot(1, 3, 3); pylab.axis('off'); pylab.imshow(filtered_img[0,1,:,:])
#pylab.savefig('lena_conv.jpg')
#pylab.savefig('conv.jpg')
pylab.show('./3wolfmoon.jpg')

Exemple #47
0
data2dsmoth = smooth_2d(data2d, n_times)
mask2d = find_mask_2d(data2d, data2dsmoth, n_times)

# end code that will become production code


from matplotlib import pyplot as plt
col_from = 0
col_to = 950
row_from = 0
row_to = 550

print "Plotting data2d"
data2d = data2d.as_numpy_array()
data2d = data2d[row_from:row_to,col_from:col_to]
plt.imshow(data2d, interpolation = "nearest")
plt.show()


print "Plotting data2dsmoth"
np_data2dsmoth = data2dsmoth.as_numpy_array()
np_data2dsmoth = np_data2dsmoth[row_from:row_to,col_from:col_to]
plt.imshow(np_data2dsmoth, interpolation = "nearest")#, cmap = pylab.gray())
plt.show()

print "Plotting data2d mask"
np_data2dmask = mask2d.as_numpy_array()
np_data2dmask = np_data2dmask[row_from:row_to,col_from:col_to]
plt.imshow(np_data2dmask, interpolation = "nearest", cmap = pylab.gray())#, cmap = pylab.gray())
plt.show()
Exemple #48
0
 def set_cmap(self,cmap=None):
   "Change the colormap"
   if cmap is None: self.cmap=plt.gray();
   else:            self.cmap=cmap;
Exemple #49
0
	
#----------------------------------------------------------
# Programme

#on passe en niveau de gris (marche seulement avec des .jpg)
img0 = cv2.cvtColor(img0,cv2.COLOR_GRAY2BGR)

#on passe à un seul channel
img1 = mh.colors.rgb2grey(img0)

#on supprime les composantes connexes de trop petite taille
img12 = binary(img1,200)
img1 = areaclose(img12,2000)

plt.imshow(img1)
plt.gray()
plt.show()

#on supprime tout ce qui n'est pas barre horizontal (à quelques degrés près)
a = 7
img2 = close(img1,seline(a,90))
img3 = close(img1,seline(a,89))
img4 = close(img1,seline(a,88))
img5 = close(img1,seline(a,87))
img6 = close(img1,seline(a,91))
img7 = close(img1,seline(a,92))
img8 = close(img1,seline(a,93))
img9 = close(img1,seline(a,94))

img = union(img2,img3,img4,img5,img6,img7,img8,img9)
plt.imshow(img)
Exemple #50
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PhloxAR.descriptor import harris
from PIL import Image
from matplotlib.pylab import gray
from numpy import array

img = array(Image.open('../data/empire.jpg').convert('L'))
gray()
harrisimg = harris.compute_harris_response(img)
filtered_coords = harris.get_harris_points(harrisimg, 6)
harris.plot_harris_points(img, filtered_coords)
Exemple #51
0
# line plot connecting the first two points
pl.plot(x[:2], y[:2])

# add title and show the plot
pl.title('Plotting: "empire.jpg"')
pl.axis('off')


# Image Contours and Histograms
gray_im = pl.array(Image.open(PATH_TO_IMAGES + 'empire.jpg').convert('L'))

# figure 2
pl.figure()

# don't use clors
pl.gray()

# show contours with origin upper left corner
pl.contour(gray_im, origin='image')
pl.axis('equal')
pl.axis('off')

# Histogram - figure 3
pl.figure()
pl.hist(im.flatten(), 128)


# Interactive notation

# figure 4
pl.figure()
Exemple #52
0
    def plot_predictions(self):
        epoch, batch, data = self.get_next_batch(train=False)  # get a test batch
        num_classes = self.test_data_provider.get_num_classes()
        NUM_ROWS = 2
        NUM_COLS = 4
        NUM_IMGS = NUM_ROWS * NUM_COLS if not self.save_preds else data[0].shape[1]
        NUM_TOP_CLASSES = min(num_classes, 5)  # show this many top labels
        NUM_OUTPUTS = self.model_state["layers"][self.softmax_name]["outputs"]
        PRED_IDX = 1

        label_names = [lab.split(",")[0] for lab in self.test_data_provider.batch_meta["label_names"]]
        if self.only_errors:
            preds = n.zeros((data[0].shape[1], NUM_OUTPUTS), dtype=n.single)
        else:
            preds = n.zeros((NUM_IMGS, NUM_OUTPUTS), dtype=n.single)
            # rand_idx = nr.permutation(n.r_[n.arange(1), n.where(data[1] == 552)[1], n.where(data[1] == 795)[1], n.where(data[1] == 449)[1], n.where(data[1] == 274)[1]])[:NUM_IMGS]
            rand_idx = nr.randint(0, data[0].shape[1], NUM_IMGS)
            if NUM_IMGS < data[0].shape[1]:
                data = [n.require(d[:, rand_idx], requirements="C") for d in data]
        #        data += [preds]
        # Run the model
        print [d.shape for d in data], preds.shape
        self.libmodel.startFeatureWriter(data, [preds], [self.softmax_name])
        IGPUModel.finish_batch(self)
        print preds
        data[0] = self.test_data_provider.get_plottable_data(data[0])

        if self.save_preds:
            if not gfile.Exists(self.save_preds):
                gfile.MakeDirs(self.save_preds)
            preds_thresh = preds > 0.5  # Binarize predictions
            data[0] = data[0] * 255.0
            data[0][data[0] < 0] = 0
            data[0][data[0] > 255] = 255
            data[0] = n.require(data[0], dtype=n.uint8)
            dir_name = "%s_predictions_batch_%d" % (os.path.basename(self.save_file), batch)
            tar_name = os.path.join(self.save_preds, "%s.tar" % dir_name)
            tfo = gfile.GFile(tar_name, "w")
            tf = TarFile(fileobj=tfo, mode="w")
            for img_idx in xrange(NUM_IMGS):
                img = data[0][img_idx, :, :, :]
                imsave = Image.fromarray(img)
                prefix = (
                    "CORRECT"
                    if data[1][0, img_idx] == preds_thresh[img_idx, PRED_IDX]
                    else "FALSE_POS"
                    if preds_thresh[img_idx, PRED_IDX] == 1
                    else "FALSE_NEG"
                )
                file_name = "%s_%.2f_%d_%05d_%d.png" % (
                    prefix,
                    preds[img_idx, PRED_IDX],
                    batch,
                    img_idx,
                    data[1][0, img_idx],
                )
                #                gf = gfile.GFile(file_name, "w")
                file_string = StringIO()
                imsave.save(file_string, "PNG")
                tarinf = TarInfo(os.path.join(dir_name, file_name))
                tarinf.size = file_string.tell()
                file_string.seek(0)
                tf.addfile(tarinf, file_string)
            tf.close()
            tfo.close()
            #                gf.close()
            print "Wrote %d prediction PNGs to %s" % (preds.shape[0], tar_name)
        else:
            fig = pl.figure(3, figsize=(12, 9))
            fig.text(0.4, 0.95, "%s test samples" % ("Mistaken" if self.only_errors else "Random"))
            if self.only_errors:
                # what the net got wrong
                if NUM_OUTPUTS > 1:
                    err_idx = [i for i, p in enumerate(preds.argmax(axis=1)) if p not in n.where(data[2][:, i] > 0)[0]]
                else:
                    err_idx = n.where(data[1][0, :] != preds[:, 0].T)[0]
                    print err_idx
                err_idx = r.sample(err_idx, min(len(err_idx), NUM_IMGS))
                data[0], data[1], preds = data[0][:, err_idx], data[1][:, err_idx], preds[err_idx, :]

            import matplotlib.gridspec as gridspec
            import matplotlib.colors as colors

            cconv = colors.ColorConverter()
            gs = gridspec.GridSpec(NUM_ROWS * 2, NUM_COLS, width_ratios=[1] * NUM_COLS, height_ratios=[2, 1] * NUM_ROWS)
            # print data[1]
            for row in xrange(NUM_ROWS):
                for col in xrange(NUM_COLS):
                    img_idx = row * NUM_COLS + col
                    if data[0].shape[0] <= img_idx:
                        break
                    pl.subplot(gs[(row * 2) * NUM_COLS + col])
                    # pl.subplot(NUM_ROWS*2, NUM_COLS, row * 2 * NUM_COLS + col + 1)
                    pl.xticks([])
                    pl.yticks([])
                    img = data[0][img_idx, :, :, :]
                    img = img.squeeze()
                    if len(img.shape) > 2:  # more than 2 dimensions
                        if img.shape[2] is 2:  # if two channels
                            # copy 2nd to 3rd channel for visualization
                            a1 = img
                            a2 = img[:, :, 1]
                            a2 = a2[:, :, n.newaxis]
                            img = n.concatenate((a1, a2), axis=2)
                        pl.imshow(img, interpolation="lanczos")
                    else:
                        pl.imshow(img, interpolation="lanczos", cmap=pl.gray())
                    show_title = data[1].shape[0] == 1
                    true_label = [int(data[1][0, img_idx])] if show_title else n.where(data[1][:, img_idx] == 1)[0]
                    # print true_label
                    # print preds[img_idx,:].shape
                    # print preds[img_idx,:].max()
                    true_label_names = [label_names[i] for i in true_label]
                    img_labels = sorted(zip(preds[img_idx, :], label_names), key=lambda x: x[0])[-NUM_TOP_CLASSES:]
                    # print img_labels
                    axes = pl.subplot(gs[(row * 2 + 1) * NUM_COLS + col])
                    height = 0.5
                    ylocs = n.array(range(NUM_TOP_CLASSES)) * height
                    pl.barh(
                        ylocs,
                        [l[0] for l in img_labels],
                        height=height,
                        color=["#ffaaaa" if l[1] in true_label_names else "#aaaaff" for l in img_labels],
                    )
                    # pl.title(", ".join(true_labels))
                    if show_title:
                        pl.title(", ".join(true_label_names), fontsize=15, fontweight="bold")
                    else:
                        print true_label_names
                    pl.yticks(
                        ylocs + height / 2,
                        [l[1] for l in img_labels],
                        x=1,
                        backgroundcolor=cconv.to_rgba("0.65", alpha=0.5),
                        weight="bold",
                    )
                    for line in enumerate(axes.get_yticklines()):
                        line[1].set_visible(False)
                    # pl.xticks([width], [''])
                    # pl.yticks([])
                    pl.xticks([])
                    pl.ylim(0, ylocs[-1] + height)
                    pl.xlim(0, 1)

n_times = 1
data2dsmoth_tmp = smooth_2d(flex.int(data2d), n_times).as_numpy_array()
data2dsmoth = numpy.float64(data2dsmoth_tmp)


n_times = 5
data2dsmoth_2t_tmp = smooth_2d(flex.int(data2d), n_times).as_numpy_array()
data2dsmoth_2t = numpy.float64(data2dsmoth_2t_tmp)


#n = write_2d(flex.double(data2dsmoth))

print "Plotting data2dsmoth"
plt.imshow(data2dsmoth, interpolation = "nearest", cmap = pylab.gray())
plt.show()


line = numpy.copy(data2d[230, :])
pylab.subplot2grid((3, 3), (0, 0), colspan = 3)
pylab.plot(line)

line1 = numpy.copy(data2dsmoth[230, :])
pylab.subplot2grid((3, 3), (1, 0), colspan = 3)
pylab.plot(line1)

line2 = numpy.copy(data2dsmoth_2t[230, :])
pylab.subplot2grid((3, 3), (2, 0), colspan = 3)
pylab.plot(line2)
Exemple #54
0
def C99(masksize=3, startind=1, show_plot=False, sdscale=1.2):
    logger.debug("C99")
    if self.vecs == None:
        logger.error("No vector input")
        raise SystemExit(1)

        # nsents = numpy.unique(self.vecs.indices).shape[0]
    nsents = self.nsents  # numpy.unique(self.vecs.indices).shape[0]
    logger.debug("nsents: %d %d" % (nsents, self.nsents))

    ## Similarity matrix: sentence id 1 -> vdist[0,]
    logger.debug("get pairwise cosine distances")
    logger.debug(self.vecs.shape)

    vdist_cond = pdist(self.vecs.toarray()[startind:], "cosine")  ## in condensed format
    vdist = csc_matrix(squareform(vdist_cond))
    logger.debug(vdist.shape)

    ## Ranking: An elements rank is the number of neighbours
    ## with lower similarity scores in the similarity matrix
    rankmat = numpy.zeros(vdist.shape)
    # logger.debug(rankmat)

    csize = int((masksize - 1) / 2)
    logger.debug("csize: %d ", csize)
    logger.debug("nfeats: %d ", self.nfeats)
    logger.debug("masksize: %d ", masksize)

    rankmat = generic_filter(
        numpy.nan_to_num(vdist.toarray()),
        self.maskrank,
        footprint=numpy.ones((masksize, masksize)),
        mode="constant",
        cval=-1.0,
        extra_keywords={"masksize": masksize, "csize": csize},
    )

    # logger.debug(rankmat)
    # logger.debug(vdist.shape)
    # logger.debug(rankmat.shape)

    if show_plot:
        plt.subplot(2, 1, 1)
        plt.imshow(1 - vdist.toarray(), cmap=plt.gray())
        plt.subplot(2, 1, 2)
        plt.imshow(rankmat, cmap=plt.gray())
        plt.show()

        ## Clustering as described in Choi's paper
    smat = numpy.zeros(rankmat.shape)
    # logger.debug(smat.shape[0])
    n = smat.shape[0]
    for i in range(n):
        smat[i, i] = rankmat[i, i]

    for i in range(n - 1):
        smat[i + 1, i] = 2 * rankmat[i + 1, i] + smat[i, i] + smat[i + 1, i + 1]
        smat[i, i + 1] = smat[i + 1, i]

    for j in range(2, n - 1):
        for i in range(n - j):
            smat[i + j, i] = 2 * rankmat[i + j, i] + smat[i + j - 1, i] + smat[i + j, i + 1] - smat[i + j - 1, i + 1]
            smat[i, i + j] = smat[i + j, i]

            ##  Start doing splits
    currsplits = [(0, n - 1)]
    prev_D = smat[0, n - 1] / get_area((0, n - 1))

    Ds = []
    diff_Ds = []
    splits = {}
    prev_D = smat[i, n - 1] / get_area((i, n - 1))
    # logger.debug("prev D: %f", prev_D)

    for i in range(n):
        curr_D, currsplits = self.c99_add_boundary(smat=smat, splits=currsplits)
        Ds.append(curr_D)
        diff_D = curr_D - prev_D
        diff_Ds.append(diff_D)
        prev_D = curr_D
        splits[i] = currsplits

    if show_plot:
        plt.plot(Ds)
        plt.show()

    diff_Ds = numpy.array(diff_Ds)
    Ds = numpy.array(Ds)
    mean_diffD = numpy.mean(diff_Ds)
    sd_diffD = numpy.std(diff_Ds)
    logger.debug("D: mean %f, sd %f" % (mean_diffD, sd_diffD))

    threshhold = mean_diffD + (sdscale * sd_diffD)
    logger.debug("threshhold %f" % threshhold)

    pass_thresh = numpy.where(diff_Ds > threshhold)[0]

    if len(pass_thresh) == 0:  # or splits[pass_thresh[-1]] == []:
        logger.debug("-----> Nothing passes the threshold? Returning")
        return ([], [], vdist)
    else:
        logger.debug("splits")
        logger.debug(splits[pass_thresh[-1]])
        end_inds = [b + 1 for a, b in splits[pass_thresh[-1]]]
        start_ids = [a + 1 for a, b in splits[pass_thresh[-1]]]

    logger.debug("start_ids:")
    logger.debug(start_ids)
    logger.debug("end_ids:")
    logger.debug(end_inds)
    logger.debug("vdist")
    logger.debug(vdist)
    logger.debug("C99 returning normally")
    return end_inds, start_ids, vdist
Exemple #55
0
#-*- coding:utf-8 -*-
'''
Created on 2012-6-18

@author: liaoyuhua
'''
from PCV import tools as tls
from PIL import Image
import numpy as np
from matplotlib import pylab as ply
if __name__ == '__main__':
    imlist= tls.imtools.get_imlist(r"D:\Python_Computer_Vision\data\fontimages\a_thumbs")
    im  =   np.array(Image.open(imlist[0]))
    m,n =   im.shape[0:2]
    imnbr = len(imlist)
    
    immatrix=np.array([np.array(Image.open(im)).flatten() for im in imlist],'f')
    V,S,immean=tls.pca.pca(immatrix)
    
    ply.figure()
    ply.gray()
    ply.subplot(2,4,1)
    ply.imshow(immean.reshape(m,n))
    for i in range(7):
        ply.subplot(2,4,i+2)
        ply.imshow(V[i].reshape(m,n))
    ply.show()
    
Exemple #56
0
def main(argv):
  #if len(argv) < 4:
  #  print """Usage:
  #  """
  #  sys.exit(1)
  #nlayers = int(argv[1])

  # get number of layers
  f = open(FLAGS.dir+"weights/nlayers.txt")
  nlayers = int(f.readlines()[0])
  f.close()
  print str(nlayers) + " layer(s) detected."

  pylab.figure(figsize=(32, 24), dpi=320, facecolor='w', edgecolor='k')

  # Make a picture with the filters
  [n_inputs, n_neurons, weights] = visualizing.weights_filename_to_array(FLAGS.dir+"weights/W0.txt")

  image_side_length = int(pylab.sqrt(n_inputs))
  nsubplot = pylab.ceil(pylab.sqrt(n_neurons))
  for i in range(n_neurons):
    filter = pylab.resize(weights[i], [image_side_length, image_side_length])
    pylab.subplot(nsubplot, nsubplot, i+1)
    pylab.imshow(filter, interpolation='nearest')
    pylab.gray()

  pylab.savefig(FLAGS.dir + "filters" + ".png")
  pylab.clf()

  # Make a picture with the all weights
  nsubplot_vertical = nlayers+1
  nsubplot_horizontal = 4
  for i in range(nlayers):
    # V
    location = 1+(nlayers-i)*nsubplot_horizontal+0
    filename = FLAGS.dir+"weights/V" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal, location,
                       filename, True, "V"+str(i))

    # W
    location = 1+(nlayers-i)*nsubplot_horizontal+1
    filename = FLAGS.dir+"weights/W" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, False, "W"+str(i))

    # F
    location = 1+(nlayers-i)*nsubplot_horizontal+2
    filename = FLAGS.dir+"weights/F" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, False, "F"+str(i))

    # G
    location = 1+(nlayers-i)*nsubplot_horizontal+3
    filename = FLAGS.dir+"weights/G" + str(i) + ".txt"
    visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                   location, filename, True, "G"+str(i))

  # Last layer
  location = 1+1
  filename = FLAGS.dir+"weights/W" + str(nlayers) + ".txt"
  visualizing.plot_weight_matrix(nsubplot_vertical, nsubplot_horizontal,
                                 location, filename, False, "W"+str(nlayers))

  pylab.savefig(FLAGS.dir + "weights" + ".png")

  # Make pictures with examples and representations
  visualizing.visualize_representations(FLAGS.dir, nlayers)
Exemple #57
0
def plot(input_path,file_name,output_path):
#data = np.fromfile('t3/reconstruction_sarlo.rec',dtype='float32',sep='') # modify this to read the file 
    data = np.fromfile(input_path+'/'+file_name,dtype='float32',sep='') 
    data = data.reshape([array_size_z,array_size_y,array_size_x]) 

# apply a sobel file
    data = nd.generic_gradient_magnitude(data, nd.sobel) # apply a 3-D sobel filter


# plot 1 and title
    fig1 = plt.figure()
    fig1.suptitle(file_name)

# turn into gray figure
    plt.gray()

    subfig1 = fig1.add_subplot(2,2,1)
    subfig1.imshow(data[:,:,100])

    subfig2 = fig1.add_subplot(2,2,2)
    subfig2.imshow(data[:,:,300])

    subfig3 = fig1.add_subplot(2,2,3)
    subfig3.imshow(data[:,:,500])

    subfig4 = fig1.add_subplot(2,2,4)
    subfig4.imshow(data[:,:,700])

# save image to the output    
    plt.savefig(output_path+'/'+'sobel_X_'+file_name+'.png', bbox_inches=0)


# plot 3 and title
    fig3 = plt.figure()
    fig3.suptitle(file_name)

    subfig7 = fig3.add_subplot(3,1,1)
    subfig7.imshow(data[100,:,:])

    subfig8 = fig3.add_subplot(3,1,2)
    subfig8.imshow(data[200,:,:])

    subfig9 = fig3.add_subplot(3,1,3)
    subfig9.imshow(data[300,:,:])

# save image to the output    
    plt.savefig(output_path+'/'+'sobel_Z_'+file_name+'.png', bbox_inches=0)

# plot 2 and title
    fig2 = plt.figure()
    fig2.suptitle(file_name)
    
    subfig5 = fig2.add_subplot(2,1,1)
    subfig5.imshow(data[:,100,:])
    #subfig5.set_title('100')

    subfig6 = fig2.add_subplot(2,1,2)
    subfig6.imshow(data[:,200,:])
   # subfig6.set_title('200')

# save image to the output    
    plt.savefig(output_path+'/'+'sobel_Y_'+file_name+'.png', bbox_inches=0)
    
    # show the fig2 for reference
    fig2.show()