Example #1
0
def test_imsave():
    # The goal here is that the user can specify an output logical DPI
    # for the image, but this will not actually add any extra pixels
    # to the image, it will merely be used for metadata purposes.

    # So we do the traditional case (dpi == 1), and the new case (dpi
    # == 100) and read the resulting PNG files back in and make sure
    # the data is 100% identical.
    from numpy import random
    random.seed(1)
    data = random.rand(256, 128)

    buff_dpi1 = io.BytesIO()
    plt.imsave(buff_dpi1, data, dpi=1)

    buff_dpi100 = io.BytesIO()
    plt.imsave(buff_dpi100, data, dpi=100)

    buff_dpi1.seek(0)
    arr_dpi1 = plt.imread(buff_dpi1)

    buff_dpi100.seek(0)
    arr_dpi100 = plt.imread(buff_dpi100)

    assert arr_dpi1.shape == (256, 128, 4)
    assert arr_dpi100.shape == (256, 128, 4)

    assert_array_equal(arr_dpi1, arr_dpi100)
Example #2
0
 def _reset_fired(self):                                      #reset to original downloaded image (only if it downloaded)
     try:
         self.imArr = plt.imread(self.fName)
         self.imshow()
     except:
         self.imArr = plt.imread('_placeholder_.jpeg')
         self.imshow()
Example #3
0
File: a.py Project: RobieH/honours
def plotFFT():

    i=plt.imread('img1.png')
    i2=plt.imread('img2.png')
    #i=np.mean(i,2)

    '''Get fft and ifft'''
    FFT1=(np.fft.fftshift(np.fft.fft2(i)))
    IFFT1=np.real(np.fft.ifft2(np.fft.ifftshift(FFT1)))

    FFT2=(np.fft.fftshift(np.fft.fft2(i2)))
    IFFT2=np.real(np.fft.ifft2(np.fft.ifftshift(FFT2)))

    '''plot fft and ifft '''
    plt.subplot(1,2,1)
    plt.imshow(np.log(abs(FFT1))**2)
    plt.subplot(1,2,2)
    plt.imshow(IFFT1)
    plt.show()

    plt.subplot(1,2,1)
    plt.imshow(np.log(abs(FFT2))**2)
    plt.subplot(1,2,2)
    plt.imshow(IFFT2)
    plt.show()
Example #4
0
def match_plot(plotdata, outfile):
    """Plot list of motifs with database match and p-value
    "param plotdata: list of (motif, dbmotif, pval)
    """
    fig_h = 2
    fig_w = 7

    nrows = len(plotdata)
    ncols = 2
    fig = plt.figure(figsize=(fig_w, nrows * fig_h))

    for i, (motif, dbmotif, pval) in enumerate(plotdata):
        text = "Motif: %s\nBest match: %s\np-value: %0.2e" % (motif.id, dbmotif.id, pval)

        grid = ImageGrid(fig, (nrows, ncols, i * 2 + 1), nrows_ncols=(2, 1), axes_pad=0)

        for j in range(2):
            axes_off(grid[j])

        tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
        motif.to_img(tmp.name, format="PNG", height=6)
        grid[0].imshow(plt.imread(tmp.name), interpolation="none")
        tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
        dbmotif.to_img(tmp.name, format="PNG")
        grid[1].imshow(plt.imread(tmp.name), interpolation="none")

        ax = plt.subplot(nrows, ncols, i * 2 + 2)
        axes_off(ax)

        ax.text(0, 0.5, text, horizontalalignment="left", verticalalignment="center")

    plt.savefig(outfile, dpi=300, bbox_inches="tight")
    plt.close(fig)
def test_image_python_io():
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3])
    buffer = io.BytesIO()
    fig.savefig(buffer)
    buffer.seek(0)
    plt.imread(buffer)
Example #6
0
def loadslice(nuclei, litaf):		# loading two images
	nucleiarr = plt.imread(nuclei)
	litafarr = plt.imread(litaf)
	Wnucleiarr = nucleiarr[:, :, 0]	# selecting the white channel for the nuclei images
	Rlitafarr = litafarr[:,:,0]	# selecting the red channel for the litaf images
	RWarr = [Wnucleiarr, Rlitafarr]
	return(RWarr)
Example #7
0
def logo_im(fig):
    filename = "usgs-logo.png"
    if not os.path.exists(filename):
        if django.conf.settings.SITE_HOME:
            filename = os.path.join(django.conf.settings.SITE_HOME, "dj_eden_app", filename)

    try:
        img = imread(filename)
    except IOError:
        # silly windows...
        logo_path = django.conf.settings.SITE_HOME.replace('\\', '/').replace('eden_project', 'dj_eden_app')
        filename_win = os.path.join(logo_path, "usgs-logo.png").replace('\\', '/')
        img = imread(filename_win)

    # TODO use image dimension transform to get height in units
    shape = img.shape
    aspect = float(shape[0]) / shape[1]
    margin = 0.05

    # figure dimensions are 0..1
    im_height = (aspect * 1.0) + margin
    image_axes = axes([0.05, 1.0 - im_height, 0.9, im_height])
    image_axes.axis('off')

    imshow(img, aspect='equal', axes=image_axes, origin='upper')

    return image_axes
    def test_SaveImage( self ):
        """SaveImage pixels to file."""

        tempdir = mkdtemp()
        orig = join( pychrm_test_dir, 'lymphoma_eosin_channel_MCL_test_img_sj-05-3362-R2_001_E.tif' )

        # setting mean = 0 is flag to not use mean in ImageMatrix::OpenImage()
        downsample = 0
        bb = None
        mean = 0.0
        stddev = 0.0 
        try:
            origim = PyImageMatrix()
            if 1 != origim.OpenImage( orig, downsample, bb, mean, stddev ):
                self.fail( 'Could not build an ImageMatrix from ' + orig )

            copied_tiff = join( tempdir, 'TEST1.tif') 
            origim.SaveTiff( copied_tiff )
            
            orig_pixels = plt.imread( orig )
            copied_pixels = plt.imread( copied_tiff )

            assert_equal( orig_pixels, copied_pixels )

        finally:
            rmtree( tempdir )
def load_imgs(src_path, out_path):
    src_img = plt.imread(src_path)
    src_pyr = compute_gaussian_pyramid(src_img, min_size = 3)

    out_pyr = [[]]
    sas = [[]]
    scs = [[]]
    rss = [[]]
    ss = [[]]
    ims = [[]]

    for level in range(1, len(src_pyr)):
        with open(out_path + '%d_srcs.pickle' % level) as f:
            sa, sc, rstars, s, im = pickle.load(f)

        assert(len(sa) == len(sc) == len(rstars) == len(s) == len(im))

        sas.append(sa)
        scs.append(sc)
        rss.append(rstars)
        ss.append(s)
        ims.append(im)
        out_img = plt.imread(out_path + 'im_out_color_%d.jpg' % level)

        out_pyr.append(out_img)

    return src_pyr, out_pyr, sas, scs, rss, ss, ims
Example #10
0
def prep_image(img_path, nnet=nnet, local_img=True):
    ext = img_path.split('.')[-1]

    if local_img:
        im = plt.imread(img_path)
    else:
        im = plt.imread(io.BytesIO(urllib.urlopen(img_path).read()), ext)

    # Resize so smallest dim = 256, preserving aspect ratio
    h, w, _ = im.shape
    if h < w:
        im = skimage.transform.resize(im, (256, w*256/h), preserve_range=True)
    else:
        im = skimage.transform.resize(im, (h*256/w, 256), preserve_range=True)

    # Central crop to 224x224
    h, w, _ = im.shape
    im = im[h//2-112:h//2+112, w//2-112:w//2+112]

    rawim = np.copy(im).astype('uint8')

    # Shuffle axes to c01
    im = np.swapaxes(np.swapaxes(im, 1, 2), 0, 1)

    # Convert to BGR
    im = im[::-1, :, :]

    im = im - MEAN_IMAGE
    return rawim, floatX(im[np.newaxis])
Example #11
0
def display_bb(name, name2bb, lpix, rpix, ov1pix, ov2pix):
  plt.clf()
  try:
    image_folder_name = str('_'.join(name.split('_')[:-1])) + '/'
    imagename = str(driving_images_dir + image_folder_name + name + '.jpeg')
    im = plt.imread(imagename)
  except:
    imagename = '/scail/group/deeplearning/sail-deep-gpu/brodyh/labeled_driving_images/' + name + '.jpeg'
    im = plt.imread(imagename)

  implot = plt.imshow(im)
  plt.plot(lpix[0, :], lpix[1, :], color = 'b')
  plt.plot(rpix[0, :], rpix[1, :], color = 'b')

  for i in xrange(0, ov1pix.shape[1]):
    plt.plot([ov1pix[0, i], ov2pix[0, i]], [ov1pix[1, i], ov2pix[1, i]], color = 'r', linestyle = '-', linewidth = 1.0)

  for b in name2bb[name]['boxes']:
    if get_area(b) < 20: continue
    plot_box(b['xmin'], b['ymin'], b['xmax'], b['ymax'], 'g')
    if b['depth'] == 0:
      plt.text((b['xmin'] + b['xmax']) / 2, (b['ymax'] + b['ymin']) / 2, 'unknown', color = 'm')
    else:
      plt.text((b['xmin'] + b['xmax']) / 2, (b['ymax'] + b['ymin']) / 2 - 10, str(int(b['depth'])), color = 'm')

  plt.axis('off')
  plt.xlim([1920, 0])
  plt.ylim([1280, 0])
  plt.draw()
  plt.pause(1.5)
Example #12
0
    def imread(self, xy_range=None,
               f_data='daudi_PS_CD20_postwash.png',
               fold='../Lymphoma_optimal_Data_20161007/'):
        disp = self.disp

        # fold = '../Lymphoma_optimal_Data_20161007/'
        # Data = plt.imread(fold + 'daudi_PS_CD20_postwash.png')
        Data = plt.imread(fold + f_data)
        Ref = plt.imread(fold + 'reference_image.png')

        if xy_range is not None:
            # onvert a vector to four scalars
            minx, maxx, miny, maxy = xy_range
            Data = Data[miny:maxy, minx:maxx]
            Ref = Ref[miny:maxy, minx:maxx]

        bgData = np.mean(Data)
        bgRef = np.mean(Ref)
        NormFactor = bgRef / bgData
        if disp:
            print("NormFacter =", NormFactor)

        subNormAmp = np.sqrt(Data / Ref * NormFactor)

        if self.disp:
            print(Data.shape, Ref.shape, subNormAmp.shape)

        self.Data, self.Ref = Data, Ref
        self.subNormAmp = subNormAmp
Example #13
0
def animate_rickshaw(l,X):
	scaling_xfactor = 40
	scaling_yfactor = 10
	
	import os; print os.getcwd()
	rick = plt.imread("rickshaw.png")
	# print "rick.shape = ", rick.shape
	rick = rick.mean(axis=2)
	rick[np.where(rick<=.9)] = 0
	rick[np.where(rick>.9)] = 1
	rick2 = np.argwhere(rick==0)
	ricky = -rick2[:,0]
	rickx = rick2[:,1]
	ricky -= ricky.min()
	rickx -= rickx.mean()
	rickx += 30
	
	present = plt.imread("present.png")
	print "present.shape = ", present.shape
	present[np.where(present<=.5)] = 0
	present[np.where(present>.5)] = 1
	present2 = np.argwhere(present==0)
	presenty = -present2[:,0]
	presentx = present2[:,1]
	presentx -= presentx.mean()
	presenty -= presenty.mean()
	
	assumedl = scaling_yfactor*l
	
	position = X[:,0]
	angle = X[:,2]
	rickshaw_height = 75
	tf = len(position)
	xpos = (position-np.sin(angle))
	ypos = (rickshaw_height+l+1-np.cos(angle))

	fig = plt.figure()
	ax = plt.axes(xlim=(scaling_xfactor*position.min()-150, scaling_xfactor*position.max()+150), ylim=(0, 250+assumedl))
	line, = ax.plot([], [],lw=0.00001)
	line.set_marker('o')
	line.set_markersize(.5)
	presenty += ypos[0]-50
	
	def init():
		line.set_data([], [])
		return line,
		
	def animate(i):				   
		x = np.linspace(scaling_xfactor*xpos[i],scaling_xfactor*xpos[i]-scaling_xfactor*np.sin(angle[i]),200)
		y = np.linspace(rickshaw_height,rickshaw_height+scaling_yfactor*ypos[i]-70*scaling_yfactor,200)
		
		xr = np.concatenate((rickx+x[0], presentx+x[-1],x))
		yr = np.concatenate((ricky,presenty+y[-1],y))
		
		line.set_data(xr, yr)
		return line,

	anim = animation.FuncAnimation(fig, animate, init_func=init,
							   frames=tf, interval=350, blit=True)
	plt.show()
Example #14
0
    def __init__(self, photo_string, art_string, content=0.001, style=0.2e6, total_var=0.1e-7):
        # load network
        self.net = build_model()
        # load layers
        layers = ['conv4_2', 'conv1_1', 'conv2_1', 'conv3_1', 'conv4_1', 'conv5_1']
        layers = {k: self.net[k] for k in layers}
        self.layers = layers
        # load images
        im = plt.imread(art_string)
        self.art_raw, self.art = prep_image(im)
        im = plt.imread(photo_string)
        self.photo_raw, self.photo = prep_image(im)
        # precompute layer activations for photo and artwork
        input_im_theano = T.tensor4()
        self._outputs = lasagne.layers.get_output(layers.values(), input_im_theano)
        self.photo_features = {k: theano.shared(output.eval({input_im_theano: self.photo}))
                          for k, output in zip(layers.keys(), self._outputs)}
        self.art_features = {k: theano.shared(output.eval({input_im_theano: self.art}))
                        for k, output in zip(layers.keys(), self._outputs)}
        # Get expressions for layer activations for generated image
        self.generated_image = theano.shared(floatX(np.random.uniform(-128, 128, (1, 3, IMAGE_W, IMAGE_W))))

        gen_features = lasagne.layers.get_output(layers.values(), self.generated_image)
        gen_features = {k: v for k, v in zip(layers.keys(), gen_features)}
        self.gen_features = gen_features

        # set the weights of the regularizers
        self._content, self._style, self._total_var = content, style, total_var
Example #15
0
File: load.py Project: NelleV/SORBB
def get_image(image_name, test=False):
    """
    Return the image

    params
    ------
        image_name: string, name of the image

    returns
    -------
        image, calc: (ndarray, ndarray)
            returns a tuple of images, one being a sculpture, the other a mask
            Returns None, None if the mask doesn't exist
    """
    try:
        image = imread(os.path.join(data_all_path, image_name))[:-1][::-1]        
        calc = imread(os.path.join(
                            masks_all_path,
                            image_name[:-3] + 'png'))

    except IOError:
        print "IOError %s" % os.path.join(masks_train_path,
                                          image_name[:-3] + 'png')
        return None, None

    return image, calc
Example #16
0
def convert_single_file_from_ilastik( image_path, segmentation_path, out_path ):
    """Reads a file that was segmented with ilastik and turns it into a
    file as seedwater would create it.
    
    Parameters
    ----------
    
    image_path : string
        path to the image file
        
    segmentation_path : string
        path to the ilastik segmented image file

    out_path : string
        where the converted file should be stored
    """
    full_image = plt.imread(image_path)

    segmented_image = plt.imread(segmentation_path)

    seed_image = create_seeds_from_image(segmented_image)

    segmentation = create_segmentation_from_seeds( full_image, seed_image )
    
    cv2.imwrite(out_path, segmentation)
def main():
	plt.figure(0)
	plt.xlim(0,2416)
	plt.ylim(1678,0)
	im=plt.imread('../final_img.png')
	implot=plt.imshow(im)
	plt.axis('off')

	path_list=open(sys.argv[1],'r').read().splitlines()
	i=0
	# add '.txt' if needed
	for path in path_list:
		latlong=[[float(f) for f in line.split(',')[9:11]] for line in open(sys.argv[2]+path).read().splitlines()]
		
		# common plots for all the paths
		plt.figure(0)
		plot_given_plot(latlong,plt)
		
		# different plots for all the paths
		i=i+1
		plt.figure(i)
		plt.xlim(0,2416)
		plt.ylim(1678,0)
		im=plt.imread('../final_img.png')
		implot=plt.imshow(im)
		plt.axis('off')
		plot_given_plot(latlong,plt)
		plt.savefig(sys.argv[3]+str(i),ext='png',close=False,verbose=True,dpi=350,bbox_inches='tight',pad_inches=0)
	
	plt.figure(0)
	plt.savefig(sys.argv[3]+'all',ext='png',close=False,verbose=True,dpi=350,bbox_inches='tight',pad_inches=0)
Example #18
0
def run_kmeans_clustering(k,num_bands,cy3_file,cy5_file,outfile):
    cy3 = imread(cy3_file)
    cy5 = imread(cy5_file)
    labels = kmeans(cy3,k)
    Kidx, Clusters = choose_k(labels,cy3,num_bands)
    outfile = plotallimages(cy3,cy5,labels,Clusters,outfile)
    return outfile
Example #19
0
def init_map():
    
    global aspect, mapImg, maskImg, burrImg, burrIndx, imgXSize, imgYSize, imgZSize, xOff
    
    # Display Background Map
    burrImg = Image.open('BurroughsIndxNoBg.png')
    (imgYSize, imgXSize) = (burrImg.height, burrImg.width)
        
    burrIndx = np.array(burrImg.convert('P'))
    
    # Clean up partial-surface pixels
    for y in range(imgYSize):
        for x in range(imgXSize):
            if burrIndx[y,x] not in (0, 1, 2, 3, 4, 5):
                burrIndx[y,x] = 0
    
    
    aspect = float(imgXSize)/float(imgYSize)
    (xScale, yScale) = (imgXSize * aspect / imgXSize, 1.)
    xOff = (1. - xScale)/2.
    
    # Load Background Image
    backImg = plt.imread('UHF42EdMap.png')
    axes.ax.imshow(backImg, extent=[xOff, xOff+xScale, 0, yScale], alpha=1)
    
    # Display Boroughs Index Map
    axes.ax.imshow(burrImg, extent=[xOff, xOff+xScale, 0, yScale])
    
    # Load mask map
    maskImg = plt.imread('BurroughsMask.png')
def main():

    f_ultrasounds = [img for img in glob.glob("/home/r/NerveSegmentation/train/*.tif") if 'mask' not in img]
    # f_ultrasounds.sort()  
    f_masks       = [fimg_to_fmask(fimg) for fimg in f_ultrasounds]
    
    images_shown = 0 
	
    for f_ultrasound, f_mask in zip(f_ultrasounds, f_masks):

        img  = plt.imread(f_ultrasound)
        mask = plt.imread(f_mask)

        if mask_not_blank(mask):

            # plot_image(grays_to_RGB(img),  title=f_ultrasound)
            # plot_image(grays_to_RGB(mask), title=f_mask)

            f_combined = f_ultrasound + " & " + f_mask
            #img        = image_with_mask(img, mask)
            plot_image(image_with_mask(img, mask), title=f_combined)
            plot_image(img, title=f_combined)
            print('plotted:', f_combined)
            images_shown += 1

        if images_shown >= IMAGES_TO_SHOW:
            break

    df    = []
    MyImg = np.zeros([len(img), len(img[0])],dtype=np.uint8)
    f_ultrasounds = [img for img in glob.glob("/home/r/NerveSegmentation/test/*.tif")]
    for f_ultrasound in zip(f_ultrasounds):
        img  = plt.imread(f_ultrasound)
    	df.append(img)
Example #21
0
def test_imsave(fmt):
    if fmt in ["jpg", "jpeg", "tiff"]:
        pytest.importorskip("PIL")
    has_alpha = fmt not in ["jpg", "jpeg"]

    # The goal here is that the user can specify an output logical DPI
    # for the image, but this will not actually add any extra pixels
    # to the image, it will merely be used for metadata purposes.

    # So we do the traditional case (dpi == 1), and the new case (dpi
    # == 100) and read the resulting PNG files back in and make sure
    # the data is 100% identical.
    np.random.seed(1)
    # The height of 1856 pixels was selected because going through creating an
    # actual dpi=100 figure to save the image to a Pillow-provided format would
    # cause a rounding error resulting in a final image of shape 1855.
    data = np.random.rand(1856, 2)

    buff_dpi1 = io.BytesIO()
    plt.imsave(buff_dpi1, data, format=fmt, dpi=1)

    buff_dpi100 = io.BytesIO()
    plt.imsave(buff_dpi100, data, format=fmt, dpi=100)

    buff_dpi1.seek(0)
    arr_dpi1 = plt.imread(buff_dpi1, format=fmt)

    buff_dpi100.seek(0)
    arr_dpi100 = plt.imread(buff_dpi100, format=fmt)

    assert arr_dpi1.shape == (1856, 2, 3 + has_alpha)
    assert arr_dpi100.shape == (1856, 2, 3 + has_alpha)

    assert_array_equal(arr_dpi1, arr_dpi100)
Example #22
0
def test_load_from_url():
    path = Path(__file__).parent / "baseline_images/test_image/imshow.png"
    url = ('file:'
           + ('///' if sys.platform == 'win32' else '')
           + path.resolve().as_posix())
    plt.imread(url)
    plt.imread(urllib.request.urlopen(url))
    def xest_create_segmentation_from_seeds(self):
        "test whether we can create a segmentation from given seeds."

        first_image = plt.imread(path.join(dirname(__file__),
                                           'data/ilastik_data/CropStack20001_Simple Segmentation.tif'))

        seed_image = mesh.create_seeds_from_image( first_image )
        
        actual_image = plt.imread(path.join(dirname(__file__),
                                           'data/image_data/CropStack20001.tif'))
        
        segmented_image = mesh.create_segmentation_from_seeds( actual_image, seed_image )
        
        self.assertEqual( segmented_image.dtype, np.dtype('uint16') )
        
        plt.imsave( path.join(dirname(__file__), 
                    'output/testsegmentation.tif'), segmented_image )
        
        cv2.imwrite( path.join(dirname(__file__), 
                     'output/testsegmentationwithcv2.tif'), segmented_image )
        
        reloaded_image = cv2.imread( path.join(dirname(__file__), 
                         'output/testsegmentationwithcv2.tif'), flags = -1 )
        
        np.testing.assert_equal( segmented_image, reloaded_image )
Example #24
0
def plotPhoto():

    i = plt.imread("img1.png")
    i2 = plt.imread("img2.png")
    # i=np.mean(i,2)

    """Get fft and ifft"""
    FFT1 = np.fft.fftshift(np.fft.fft2(i))
    IFFT1 = np.real(np.fft.ifft2(np.fft.ifftshift(FFT1)))

    FFT2 = np.fft.fftshift(np.fft.fft2(i2))
    IFFT2 = np.real(np.fft.ifft2(np.fft.ifftshift(FFT2)))

    """plot fft and ifft """
    plt.subplot(1, 2, 1)
    plt.imshow(np.log(abs(FFT1)) ** 2)
    plt.subplot(1, 2, 2)
    plt.imshow(IFFT1)
    plt.show()

    plt.subplot(1, 2, 1)
    plt.imshow(np.log(abs(FFT2)) ** 2)
    plt.subplot(1, 2, 2)
    plt.imshow(IFFT2)
    plt.show()
def main():

    f_ultrasounds = [img for img in glob.glob("../input/train/*.tif") if 'mask' not in img]
    # f_ultrasounds.sort()  
    f_masks       = [fimg_to_fmask(fimg) for fimg in f_ultrasounds]
    
    images_shown = 0 

    for f_ultrasound, f_mask in zip(f_ultrasounds, f_masks):

        img  = plt.imread(f_ultrasound)
        mask = plt.imread(f_mask)

        if mask_not_blank(mask):

            # plot_image(grays_to_RGB(img),  title=f_ultrasound)
            # plot_image(grays_to_RGB(mask), title=f_mask)

            f_combined = f_ultrasound + " & " + f_mask 
            plot_image(image_with_mask(img, mask), title=f_combined)
            print('plotted:', f_combined)
            images_shown += 1

        if images_shown >= IMAGES_TO_SHOW:
            break
Example #26
0
def site_to_array(sitepath):
    '''Accepts absolute path to a single w1 image file (wavelength 1).
    Checks for additional channels and compiles all channels into a
    single three dimensional NumPy array.
    '''
    path, name = os.path.split(sitepath)
    
    w1check = re.search('w1', name)
    if(w1check):
        sarray = plt.imread(sitepath)

        files = os.listdir(path)
        w2check = name.replace('w1', 'w2')
        w3check = name.replace('w1', 'w3')
        w4check = name.replace('w1', 'w4')
        if(w2check in files):
            w2 = plt.imread(os.path.join(path, w2check))
            sarray = np.dstack((sarray, w2))

        if(w3check in files):
            w3 = plt.imread(os.path.join(path, w3check))
            sarray = np.dstack((sarray, w3))

        if(w4check in files):
            w4 = plt.imread(os.path.join(path, w4check))
            sarray = np.dstack((sarray, w4))

    return(sarray)
Example #27
0
def testCircleToCMonomodalSyNEM(lambdaParam, maxOuterIter):
    fname0='data/circle.png'
    #fname0='data/C_trans.png'
    fname1='data/C.png'
    nib_moving=plt.imread(fname0)
    nib_fixed=plt.imread(fname1)
    moving=nib_moving[:,:,0]
    fixed=nib_fixed[:,:,1]
    moving=(moving-moving.min())/(moving.max() - moving.min())
    fixed=(fixed-fixed.min())/(fixed.max() - fixed.min())
    level=3
    maskMoving=moving>0
    maskFixed=fixed>0
    movingPyramid=[img for img in rcommon.pyramid_gaussian_2D(moving, level, maskMoving)]
    fixedPyramid=[img for img in rcommon.pyramid_gaussian_2D(fixed, level, maskFixed)]
    rcommon.plotOverlaidPyramids(movingPyramid, fixedPyramid)
    displacementList=[]
    displacement, dinv=estimateMonomodalSyNField2DMultiScale(movingPyramid, fixedPyramid, lambdaParam, maxOuterIter, 0,displacementList)
    inverse=np.array(tf.invert_vector_field(displacement, 0.75, 300, 1e-7))
    residual, stats=tf.compose_vector_fields(displacement, inverse)
    residual=np.array(residual)
    warpPyramid=[rcommon.warpImage(movingPyramid[i], displacementList[i]) for i in range(level+1)]
    rcommon.plotOverlaidPyramids(warpPyramid, fixedPyramid)
    rcommon.overlayImages(warpPyramid[0], fixedPyramid[0])
    rcommon.plotDiffeomorphism(displacement, inverse, residual, '',7)
Example #28
0
File: ee.py Project: RobieH/honours
def main():
    '''Using numba to try and make this as fast as possible, still very slow. '''

    obj=plt.imread('jerichoObject.bmp')
    ref=plt.imread('jerichoRef.bmp')

    img=obj-ref

    K=np.empty(img.shape)+0j
    temp=np.empty(img.shape)+0j

    wavelength=405e-9
    k=2*np.pi/(wavelength)
    z=250e-6
    #z=13e-3-250e-6

    distX=6e-6
    distY=6e-6

    n=float(img.shape[0])
    m=float(img.shape[1])

    a = np.arange(0,n)
    b = np.arange(0,m)

    first=time.time()

    for i in xrange(K.shape[0]):
        for j in xrange(K.shape[1]):

            print(i,j)
            '''create an r vector '''
            r=(i*distX,j*distY,z)

            for x in xrange(img.shape[0]):
                for y in xrange(img.shape[1]):
                    '''create an ksi vector, then calculate
                       it's norm, and the dot product of r and ksi'''
                    ksi=(x*distX,y*distY,z)
                    ksiNorm=np.linalg.norm(ksi)
                    ksiDotR=float(np.dot(ksi,r))

                    '''calculate the integrand'''
                    temp[x,y]=img[x,y]*np.exp(1j*k*ksiDotR/ksiNorm)

            '''interpolate so that we can do the integral and take the integral'''
            temp2=rbs(a,b,temp.real)
            K[i,j]=temp2.integral(0,n,0,m)

            timeTook=time.time()-first

            print(timeTook)


    K.dump('K.dat')

    kInt=K.real*K.real+K.imag*K.imag

    plt.imshow(kInt,cmap=plt.cm.Greys_r)
Example #29
0
def main():

    obj=plt.imread('jerichoObject.bmp')
    ref=plt.imread('jerichoRef.bmp')

    holo=obj-ref

    Kreal=np.empty(holo.shape)+0j
    Kimag=np.empty(holo.shape)+0j
    temp=np.empty(holo.shape)+0j

    wavelength=405e-9
    k=2*np.pi/(wavelength)
    z=250e-6
    #z=13e-3-250e-6

    distX=6e-6
    distY=6e-6

    n=float(holo.shape[0])
    m=float(holo.shape[1])

    a = np.arange(0,n)
    b = np.arange(0,m)

    '''create all r vectors'''
    R = np.empty((holo.shape[0], holo.shape[1], 3))
    R[:,:,0] = np.repeat(np.arange(holo.shape[0]), holo.shape[1]).reshape(holo.shape) * distX
    R[:,:,1] = np.arange(holo.shape[1]) * distY
    R[:,:,2] = z

    '''create all ksi vectors'''
    KSI = np.empty((holo.shape[0], holo.shape[1], 3))
    KSI[:,:,0] = np.repeat(np.arange(holo.shape[0]), holo.shape[1]).reshape(holo.shape) * distX
    KSI[:,:,1] = np.arange(holo.shape[1]) * distY
    KSI[:,:,2] = z

    # vectorized 2-norm; see http://stackoverflow.com/a/7741976/4323
    KSInorm = np.sum(np.abs(KSI)**2,axis=-1)**(1./2)

    # loop over entire holo which is same shape as holo, rows first
    # this loop populates holo one pixel at a time (so can be parallelized)
    for x in xrange(holo.shape[0]):
        for y in xrange(holo.shape[1]):

            print(x, y)

            KSIdotR = np.dot(KSI, R[x,y])
            temp = holo * np.exp(1j * k * KSIdotR / KSInorm)

            '''interpolate so that we can do the integral and take the integral'''
            temp2 = rbs(a, b, temp.real)
            Kreal[x,y] = temp2.integral(0, n, 0, m)
            temp3 = rbs(a, b, temp.imag)
            Kimag[x,y] = temp3.integral(0, n, 0, m)


    Kreal.dump('Kreal.dat')
    Kimag.dump('Kimag.dat')
def testCircleToCMonomodalDiffeomorphic(lambdaParam):
    import numpy as np
    import tensorFieldUtils as tf
    import matplotlib.pyplot as plt
    import registrationCommon as rcommon
    fname0='data/circle.png'
    #fname0='data/C_trans.png'
    fname1='data/C.png'
    circleToCDisplacementName='circleToCDisplacement.npy'
    circleToCDisplacementInverseName='circleToCDisplacementInverse.npy'
    nib_moving=plt.imread(fname0)
    nib_fixed=plt.imread(fname1)
    moving=nib_moving[:,:,0]
    fixed=nib_fixed[:,:,1]
    moving=(moving-moving.min())/(moving.max() - moving.min())
    fixed=(fixed-fixed.min())/(fixed.max() - fixed.min())
    level=3
    maskMoving=moving>0
    maskFixed=fixed>0
    movingPyramid=[img for img in rcommon.pyramid_gaussian_2D(moving, level, np.ones_like(maskMoving))]
    fixedPyramid=[img for img in rcommon.pyramid_gaussian_2D(fixed, level, np.ones_like(maskFixed))]
    rcommon.plotOverlaidPyramids(movingPyramid, fixedPyramid)
    displacementList=[]
    maxOuterIter=[10,50,100,100,100,100,100,100,100]
    if(os.path.exists(circleToCDisplacementName)):
        displacement=np.load(circleToCDisplacementName)
        inverse=np.load(circleToCDisplacementInverseName)
    else:
        displacement, inverse=estimateMonomodalDiffeomorphicField2DMultiScale(movingPyramid, fixedPyramid, lambdaParam, maxOuterIter, 0,displacementList)
        np.save(circleToCDisplacementName, displacement)
        np.save(circleToCDisplacementInverseName, inverse)    
    X1,X0=np.mgrid[0:displacement.shape[0], 0:displacement.shape[1]]
    detJacobian=rcommon.computeJacobianField(displacement)
    plt.figure()
    plt.imshow(detJacobian)
    CS=plt.contour(X0,X1,detJacobian,levels=[0.0], colors='b')
    plt.clabel(CS, inline=1, fontsize=10)
    plt.title('det(J(displacement))')
    print 'J range:', '[', detJacobian.min(), detJacobian.max(),']'
    #directInverse=np.array(tf.invert_vector_field(displacement, 0.5, 1000, 1e-7))
    directInverse=np.array(tf.invert_vector_field_fixed_point(displacement, 100, 1e-7))
    detJacobianInverse=rcommon.computeJacobianField(directInverse)
    plt.figure()
    plt.imshow(detJacobianInverse)
    CS=plt.contour(X0,X1,detJacobianInverse, levels=[0.0],colors='w')
    plt.clabel(CS, inline=1, fontsize=10)
    plt.title('det(J(displacement^-1))')
    print 'J^-1 range:', '[', detJacobianInverse.min(), detJacobianInverse.max(),']'
    #directInverse=rcommon.invert_vector_field_fixed_point(displacement, 1000, 1e-7)
    residual, stats=tf.compose_vector_fields(displacement, inverse)
    residual=np.array(residual)
    directResidual,stats=tf.compose_vector_fields(displacement, directInverse)
    directResidual=np.array(directResidual)
#    warpPyramid=[rcommon.warpImage(movingPyramid[i], displacementList[i]) for i in range(level+1)]
#    rcommon.plotOverlaidPyramids(warpPyramid, fixedPyramid)
#    rcommon.overlayImages(warpPyramid[0], fixedPyramid[0])
    rcommon.plotDiffeomorphism(displacement, inverse, residual, 'inv-joint', 7)
    rcommon.plotDiffeomorphism(displacement, directInverse, directResidual, 'inv-direct', 7)
    tf.write_double_buffer(displacement.reshape(-1), 'displacement.bin')
import sys
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

# from PySide2 import *

img = plt.imread("imgs/dan.jpg")
plt.figure(1)
plt.imshow(img)
plt.show()
# cv.waitKey(0)

Example #32
0
    def display_caption(self, image_file=None, data_name=None):

        if data_name == 'ad_2016':
            test_data = self.test_data[self.test_data['image_names'].\
                                            str.contains('ad_2016')]
        elif data_name == 'iaprtc12':
            test_data = self.test_data[self.test_data['image_names'].\
                                            str.contains('iaprtc12')]
        else:
            test_data = self.test_data
        # print(test_data)

        if image_file == None:
            line = np.array(test_data.sample(1))
            # image_name = np.asarray(test_data.sample(1))[0][0]
            image_name = line[0][0]
            tweets = line[0][1]
        else:
            image_name = image_file
        tweets = [tweets]

        sequences = self.tokenizer.texts_to_sequences(tweets)
        tweet_vec = pad_sequences(sequences, maxlen=configs['tweet_max_len'])

        print(image_name)
        features = self.image_names_to_features[image_name][
            'image_features'][:]
        print(features.shape)
        text = np.zeros((1, self.MAX_TOKEN_LENGTH, self.VOCABULARY_SIZE))
        begin_token_id = self.word_to_id[self.BOS]
        text[0, 0, begin_token_id] = 1
        image_features = np.zeros((1, self.MAX_TOKEN_LENGTH, self.IMG_FEATS))
        image_features[0, 0, :] = features
        print(self.BOS)
        num = 0
        list_word_id = []
        for word_arg in range(self.MAX_TOKEN_LENGTH - 1):
            if (configs['include_tweet'] and configs['include_image']):
                predictions = self.model.predict(
                    [text, image_features, tweet_vec])
            elif (configs['include_tweet']):
                predictions = self.model.predict([text, tweet_vec])
            elif (configs['include_image']):
                predictions = self.model.predict([text, image_features])
            matrix = np.argsort(predictions[0, word_arg, :])
            word_id = 0
            # print(matrix)
            word_id = matrix[-1]
            for id in reversed(matrix):
                if id not in list_word_id:
                    # print(id)
                    target_word_id = id
                    list_word_id.append(id)
                    break
            # word_id = np.argmax(predictions[0, word_arg, :])
            # print(np.argmax(predictions[0, word_arg, :]))
            # list_wordid=list_wordid.append(word_id)
            next_word_arg = word_arg + 1
            text[0, next_word_arg, target_word_id] = 1
            # print(text)
            word = self.id_to_word[target_word_id]
            print(word, end=" ")
            num += 1
            if word == self.EOS:
                break
            elif (num == (configs['num_hashtags'])):
                break
        print()
        print(list_word_id)
        #images_path = '../dataset/images/'
        plt.imshow(plt.imread(self.images_path + image_name))
        plt.show()
Example #33
0
i = 0
for imgname in index_closed_list:
    imgname[imgname.rindex('/') + 1:imgname.rindex('.npy')]
    i = i + 1
    print('process img    ', i)
    print(imgname[imgname.rindex('/') + 1:imgname.rindex('_closed.npy')])
    for img_original_name in imgs_list:
        if imgname[imgname.rindex('/') +
                   1:imgname.rindex('_closed.npy')] == img_original_name[
                       img_original_name.rindex('/') +
                       1:img_original_name.rindex('.jpg')]:
            print('name matched')
            plt.figure(i)
            plt.subplot(1, 2, 1)
            epithelium = np.load(imgname)
            Original_img = plt.imread(img_original_name)
            #plt.imshow(epithelium,cmap='gray')
            Original_img_crop = Original_img[0:epithelium.shape[0],
                                             0:epithelium.shape[1]]
            plt.imshow(Original_img_crop)

            plt.subplot(1, 2, 2)
            #epithelium=np.load(imgname)
            #plt.imshow(epithelium,cmap='gray')
            #Original_img_crop=Original_img[0:epithelium.shape[0],0:epithelium.shape[1]]
            #Img_temp=np.zeros(Original_img_crop.shape)
            Img_temp = np.ones(Original_img_crop.shape)
            #plt.imshow(Img_temp)
            # if not uint8 color will change
            Img_temp_ = Img_temp.astype('uint8') * 255
            #plt.imshow(Img_temp_)
Example #34
0
sns.heatmap(calc_covariance)

"""time series"""
#labels = dates.strftime('%b %d')
plt.xticks(dates, labels, rotation=60)
#inset views
#after plotting a diagram, specify an axes
plt.axes([0.25,0.5,0.35,0.35])
#and do another plot

"""histogram equalization"""
# Generate a cumulative histogram
cdf, bins, patches = plt.hist(pixels, bins=256, range=(0,256), normed=True, cumulative=True)
new_pixels = np.interp(pixels, bins[:-1], cdf*255)
# Load the image into an array: image
image = plt.imread('640px-Unequalized_Hawkes_Bay_NZ.jpg')

# Flatten the image into 1 dimension: pixels
pixels = image.flatten()

# Generate a cumulative histogram
cdf, bins, patches = plt.hist(pixels, bins=256, range=(0,256), normed=True, cumulative=True)
new_pixels = np.interp(pixels, bins[:-1], cdf*255)

# Reshape new_pixels as a 2-D array: new_image
new_image = new_pixels.reshape(image.shape)

# Display the new image with 'gray' color map
plt.subplot(2,1,1)
plt.title('Equalized image')
plt.axis('off')
def xl_to_anno(path_xl, dicom_path, dest_dir, mode=True):
    ### path of png files corresponding to dicom
    ### path of excel file

    row_len = []
    with open(path_xl, 'r', newline='') as csvfile:
        spamwriter = csv.reader(csvfile,
                                delimiter=',',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)
        for row in spamwriter:
            #print(row)
            row_len.append(len(row))


    df = pd.read_csv(path_xl,header=0,\
                     usecols=np.arange(0,max(row_len)),\
                     names=np.arange(0,max(row_len)))

    new_dic = {}
    count = 0
    for k in df:
        if (k == 0):
            new_dic[count] = df[k]
            count += 1

        if (k == 7):
            new_dic[count] = df[k]
            count += 1
        if (k % 5 == 3 and k > 20):
            new_dic[count] = df[k]
            count += 1
        if (k % 5 == 4 and k > 20):
            new_dic[count] = df[k]
            count += 1

    new_dic = pd.DataFrame(new_dic)
    frame_num = 0
    if not os.path.isdir(dest_dir):
        os.makedirs(dest_dir)
    for dic_row in np.array(new_dic):
        #print(type(dic_row[0]))
        if (mode):
            #mode =
            # mode True == calcium score
            #frame_num = dic_row[0]+1
            frame_num = dic_row[0] + 1
            #frame_num = 4
            coords = [(min((dic_row[i]), 511), min((dic_row[i + 1]), 511))
                      for i in range(2, dic_row.shape[0] - 1, 2)
                      if not np.isnan(dic_row[i + 1])]
        else:
            # mode False == echo annotations
            frame_num = dic_row[0]
            coords = [(min((dic_row[i]), 511), min((dic_row[i + 1]), 511))
                      for i in range(2, dic_row.shape[0] - 1, 2)
                      if not np.isnan(dic_row[i])]

        #print(frame_num)

        roi_name = str(dic_row[1])
        #print(dic_row)
        #print(dic_row.shape)
        #print(type(dic_row))

        #         for i in range(1,dic_row.shape[0]-1):
        #             if not np.isnan(dic_row[i]):
        #                 print(dic_row[i])
        #print(coords)
        #break

        #print(coords)
        #print(coords)
        dcm_file = pydicom.dcmread(dicom_path)
        #print(coords)

        if not os.path.isfile(dest_dir + '/' + roi_name + '/' + 'IMG_' +
                              str(frame_num) + '.png'):
            #print(coords)
            output_mask = int_fn(coords, np.zeros((512, 512)))
        else:
            img_mask = plt.imread(dest_dir + '/' + roi_name + '/' + 'IMG_' +
                                  str(frame_num) + '.png')
            thresh = threshold_otsu(img_mask)
            binary = 255 * (img_mask > thresh).astype(np.int64)

            output_mask = int_fn(
                coords,
                plt.imread(dest_dir + '/' + roi_name + '/' + 'IMG_' +
                           str(frame_num) + '.png'))

            #plt.imshow(output_mask),plt.show()
            #plt.imshow(),plt.show()
        #print(output_mask.shape)
        if not os.path.isdir((dest_dir + '/' + roi_name)):
            os.makedirs(dest_dir + '/' + roi_name)

        scipy.misc.imsave(
            dest_dir + '/' + roi_name + '/' + 'IMG_' + str(frame_num) + '.png',
            output_mask)
    if ex == 1:
        i_b = re.sub('161020140001', '161018170001', i_b)
    if ex == 2:
        i_b = re.sub('161020170001', '161018200001', i_b)
    if ex == 3:
        i_b = re.sub('161020200001', '161018220001', i_b)
    # check if file exists:
    if os.path.isfile(i_b) == False:
        faults += 1
        continue

    # Zero Padding around the image
    # padding = 0
    padding = np.max([abs(xoffset), abs(yoffset)]) + cell_pad + kernelsize + 1

    mask_test = binaryMask(plt.imread(i_b[:-6] + "o1.TIF"),
                           padding,
                           kernelsize=0)
    mask = binaryMask(plt.imread(i[:-6] + "o1.TIF"), padding, kernelsize)
    cell_coords, discard_count, mask, new_xoffset, new_yoffset = detectBlobs(
        mask, mask_test, xoffset, yoffset, cell_pad, minimum_cellwidth**2,
        8000)
    if new_xoffset <= 20 and masks.index(i) % 100 == 0:
        xoffset += new_xoffset
        print "Setting new x ", xoffset
    if new_yoffset <= 20 and masks.index(i) % 100 == 0:
        yoffset += new_yoffset
        print "Setting new y ", yoffset
    # code.interact(local=dict(globals(), **locals()))

    # ch1 = plt.imread(i[:-6]+"d0.TIF")
import matplotlib.pyplot as plt
image = plt.imread("earth.jpg")
image = plt.imread("plates.png")
fig, ax = plt.subplots()

ax.imshow(image, extent = [-180,180,-90,90])

quakes = open("currentQuakes.txt", 'r')
quakes.readline()

lats = []
lons = []
cols = []


### ADD IN conditionals for colors based on mags
for quake in quakes:
	quake_data = quake.split(',')
	lat = float(quake_data[1])
	lon = float(quake_data[2])
	lats.append(lat)
	lons.append(lon)
	if float(quake_data[4]) < 3.5:
		cols.append([25/255,25/255,75/255])
	elif float(quake_data[4]) < 5.0:
		cols.append([0/255,0/255,250/255])
	else:
		cols.append([150/255,150/255,250/255])

#volcanoes = open("volcanoes.txt", 'r')
#volcanoes.readline()
# Заача: обучить формальный нейрон научить распозновать гласные и согласные буквы ( буквы представлены как картинки)
# 1 - гласная, 2 - согласная

import numpy as np
import matplotlib.pyplot as plt  # работает с изображениями
from scipy import ndimage
import os

y0 = np.array([1, 0, 1, 0, 0], dtype=int)
D = []

# считываем изображения из папки
for i in os.listdir(
        r'C:\Users\Лиза\Desktop\Python for Data Science\lab_2\img'):
    pic = np.dot(plt.imread(i)[..., :3], [1, 1, 1]).astype(int).flatten(
    )  # приводим в ч/б, преобразуем в int и переводим в вектор
    D += [pic]

w = np.zeros(25)  # веса

#константы обучения (методом подбора)
α = 0.2  # темп
β = -0.4  # коэф.торможения
σ = lambda x: 1 if x > 0 else 0  #активационная функция


# функция распознования
def f(x):
    s = β + np.sum(x @ w)
    return σ(s)
import matplotlib.pyplot as plt
import numpy as np
img1 = plt.imread("image.jpg")
img1.ndim
img1.shape
img2 = img1[1:575:2, 1:1024:2]
img2.ndim
img2.shape
plt.imshow(img2)
plt.show()
img3 = np.zeros(img2.shape[0:2])
img3.shape
img4 = np.zeros(img2.shape[0:2])
img4.shape
threshold = 120
for i in range(img2.shape[0]):
    for j in range(img2.shape[1]):
        n = img2[i,j,0]/3 + img2[i,j,1]/3 + img2[i,j,2]/3
        img3[i,j] = n
        if n > threshold:
            img4[i,j] = 255
        else:
            img4[i,j] = 0
plt.subplot(1,4,1), plt.imshow(img2)
plt.subplot(1,4,2), plt.imshow(img3, plt.cm.gray)
plt.subplot(1,4,3), plt.imshow(img4, plt.cm.gray)
plt.subplot(1,4,4), plt.imshow(img4, plt.cm.binary)
plt.show()
Example #40
0
 def load_mask(mask_file):
     img_mask = plt.imread(mask_file)
     if img_mask.ndim > 2:
         img_mask = img_mask[:, :, 0] // 255
     img_mask = np.float32(img_mask)
     return np.float32(img_mask)
Example #41
0
def angle_analysis(folder, output, n_max=None,save_plot=True, small_pressure = False, fontsize=7, name_of_resultfile='result_angles.xlsx', dt=None, angle_legend=False):
    """
    Evaluate angles over time for an spheroid (needs folder where 'reconstruct' function was used) and stores 
    the results in the output folder.
    - N_max may define the last image to evaluate 
    - Small_pressure true returns plots that are scaled to 100 Pa whereas false returns plots that are scaled up to 1000 Pa
    - Evaluated excel sheet with angle data is automatically searched in folder, if name differs from  'result_angles.xlsx' it can be specified using name_of_resultfile
    - dt is time between consecutive images in seconds; If given a timestamp will be displayed 
    - angle_legend will draw a legend with angles if active 
    """
    from datetime import timedelta
    
    # read in angle pressures
    angles  = pd.read_excel(folder + '//'+ name_of_resultfile)
    # read in plots
    plots = glob(folder+'//plot*.png')
    # make folder if not existing
    if not os.path.exists(output):
        os.makedirs(output)
    # list of evaluated angles
    angle_list = [a for a in range(-180, 180, 5)]
    # make figure
    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(9,5))
            
    #second plot with only the left plot
    fb,axb = plt.subplots( figsize=(3,3))  
    # for color norm
    max_pr = np.nanmax([np.max(np.array(angles[z])[:n_max]) for z in angle_list])  
    plt.style.use('dark_background')
    
    # make result dictionary
    res_angles = {'mean_pr_angles (Pa)': [], 'sd_pr_angles (Pa)': [], 'CoV': []}
    
    # loop over all timesteps
    for t in range(len(angles[0][:n_max])):                   
        pressures = []
        # go through different angles 
        for z in angle_list:        
             # append for each angle the pressure of the current timestep
             pressures.append(np.array(angles[z])[t])    
                
        # norm colors for each image individually    viridis/RdBu      
        colors = matplotlib.cm.get_cmap('viridis')(pressures / max_pr ) 
        colorcycle = 'darkred'
    
        # do some statistics
        mean = np.round(np.nanmean(pressures))
        sd = np.round(np.nanstd(pressures))
        CoV = np.round(sd/mean, 2)
        res_angles['mean_pr_angles (Pa)'].append(mean)
        res_angles['sd_pr_angles (Pa)'].append(sd)
        res_angles['CoV'].append(CoV)
        
  
        if save_plot:
            if angle_legend == True:
				# position of label text
                shift = 0.9
                posx_legend = [np.cos(i*np.pi/180) * shift for i in angle_list] 
                posy_legend = [np.sin(i*np.pi/180) * shift for i in angle_list] 
				# plot text
                [ax1.text(posx_legend[i],posy_legend[i], str(angle_list[i]), color='darkred', fontsize=4, horizontalalignment='center') for i in range(len(angle_list))] 
                [axb.text(posx_legend[i],posy_legend[i], str(angle_list[i]), color='darkred', fontsize=3.6, horizontalalignment='center') for i in range(len(angle_list))]   
						
 			#ax1.scatter(posx_legend,posy_legend, s=22, c=colors)
 			# Mode that shows and norms up to 1000 Pa
            if small_pressure == False:
			
				# now use 1000 as maximum
                x = [np.cos(i*np.pi/180) for i in angle_list] * (pressures / np.array([1000]*len(pressures)) ) 
                y = [np.sin(i*np.pi/180) for i in angle_list] * (pressures / np.array([1000] *len(pressures)) ) 
				# combined figure
				# plot circles
                circle_100pa = plt.Circle((0, 0), 100/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_250pa = plt.Circle((0, 0), 250/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_500pa = plt.Circle((0, 0), 500/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_750pa = plt.Circle((0, 0), 750/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                ax1.text(0.5, 0.57, '100 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.text(0.5, 0.65, '250 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.text(0.5, 0.77, '500 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.text(0.5, 0.9, '750 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.add_artist(circle_100pa)
                ax1.add_artist(circle_250pa)
                ax1.add_artist(circle_500pa)
                ax1.add_artist(circle_750pa)
                ax1.axis('equal')  
                ax1.scatter(x,y, s=22, c=colors)
                ax1.set_xlim([-1, 1])
                ax1.set_ylim([-1, 1])
                ax1.axis('off')
				# annotate CoV    
                ax1.text(0.01, 0.91,'Coefficient of Variation: '+str(CoV), 
				 horizontalalignment='center',
				 verticalalignment='center',
				 transform = ax1.transAxes, fontsize=9.2)  
				
				# annotate time if timestep is given
                if dt is not None:
                    ax1.text(0.03, 0.98,str(timedelta(seconds=t*dt)), 
                             horizontalalignment='center',
                             verticalalignment='center',
                             transform = ax1.transAxes, fontsize=12)  

					
				# show quiver plot on the right side
                plot = plt.imread(plots[t])
                ax2.imshow(plot)
                plt.axis('off')
                ax2.axis('off')
				# save figure
                f.savefig(output+'//plot_{}.png'.format(str(t).zfill(4)), dpi=200)
                ax1.cla()
                ax2.cla()
				# Single figure
				# plot circles
                circle_100pa = plt.Circle((0, 0), 100/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_250pa = plt.Circle((0, 0), 250/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_500pa = plt.Circle((0, 0), 500/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_750pa = plt.Circle((0, 0), 750/ 1000 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                axb.text(0.5, 0.57, '100 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.text(0.5, 0.65, '250 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.text(0.5, 0.77, '500 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.text(0.5, 0.9, '750 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.add_artist(circle_100pa)
                axb.add_artist(circle_250pa)
                axb.add_artist(circle_500pa)
                axb.add_artist(circle_750pa)   
                axb.axis('equal')  
                axb.scatter(x,y, s=22, c=colors)
                axb.set_xlim([-1, 1])
                axb.set_ylim([-1, 1])
                axb.axis('off')
                plt.savefig(output+'//single_{}.png'.format(str(t).zfill(4)), dpi=200)
                axb.cla()
                
                # that shows and norms up to 100 Pa
            if small_pressure == True:
				# now use 100 as maximum
                x = [np.cos(i*np.pi/180) for i in angle_list] * (pressures / np.array([100]*len(pressures)) ) 
                y = [np.sin(i*np.pi/180) for i in angle_list] * (pressures / np.array([100] *len(pressures)) ) 
				# combined figure
				# plot circles
                circle_a = plt.Circle((0, 0), 10/ 100 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_b = plt.Circle((0, 0), 25/ 100 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_c = plt.Circle((0, 0), 50/ 100 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                ax1.text(0.5, 0.57, '10 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.text(0.5, 0.65, '25 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.text(0.5, 0.77, '50 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes,fontsize=fontsize)
                ax1.add_artist(circle_a)
                ax1.add_artist(circle_b)
                ax1.add_artist(circle_c)
                ax1.axis('equal')  
                ax1.scatter(x,y, s=22, c=colors)
                ax1.set_xlim([-1, 1])
                ax1.set_ylim([-1, 1])
                ax1.axis('off')
				# annotate CoV    
                ax1.text(0.01, 0.91,'Coefficient of Variation: '+str(CoV), 
                         horizontalalignment='center',
                             verticalalignment='center',
                            transform = ax1.transAxes, fontsize=9.2)  
				
				# annotate time if timestep is given
                if dt is not None:
                    ax1.text(0.03, 0.98,str(timedelta(seconds=t*dt)), 
                             horizontalalignment='center',
                             verticalalignment='center',
                             transform = ax1.transAxes, fontsize=12)  
				# show quiver plot on the right side
                plot = plt.imread(plots[t])
                ax2.imshow(plot)
                plt.axis('off')
                ax2.axis('off')
				# save figure
                f.savefig(output+'//plot_{}.png'.format(str(t).zfill(4)), dpi=200)
                ax1.cla()
                ax2.cla()
				
				# single figure
				# plot circles       
                circle_a = plt.Circle((0, 0), 10/ 100 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_b = plt.Circle((0, 0), 25/ 100 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                circle_c = plt.Circle((0, 0), 50/ 100 , color=colorcycle, zorder=10, fill=False, linestyle='--')
				#circle_750pa = plt.Circle((0, 0), 100/ 300 , color=colorcycle, zorder=10, fill=False, linestyle='--')
                axb.text(0.5, 0.57, '10 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.text(0.5, 0.65, '25 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.text(0.5, 0.77, '50 Pa', color = colorcycle ,horizontalalignment='center', verticalalignment='center', transform=axb.transAxes,fontsize=fontsize)
                axb.add_artist(circle_a)
                axb.add_artist(circle_b)
                axb.add_artist(circle_c)
                axb.axis('equal')  
                axb.scatter(x,y, s=22, c=colors)
                axb.set_xlim([-1, 1])
                axb.set_ylim([-1, 1])
                axb.axis('off')
                plt.savefig(output+'//single_{}.png'.format(str(t).zfill(4)), dpi=200)
                axb.cla()


    # save excel file     
    ae = pd.DataFrame.from_dict(res_angles)
    ae.columns = ['mean_pr_angles (Pa)',
                  'sd_pr_angles (Pa)',
                  'CoV',]

    ae.to_excel(output+'/angles_eval.xlsx')

    return ae
Example #42
0
        f.close()
coords = (
    content[0:34]
)  #latitude and longitude coordinates are specified as the first to 35th elements of the data that was pulled from the .txt
float_lst = [float(x)
             for x in coords]  #mkae the list of strings a list of floats
lat = float_lst[::2]
long = float_lst[1::2]
lat_wet = [lat[i] for i in (0, 1, 2, 3, 6, 9, 10, 12, 13, 14)]
long_wet = [long[i] for i in (0, 1, 2, 3, 6, 9, 10, 12, 13, 14)]
lat_sat = [lat[i] for i in (4, 5, 11)]
long_sat = [long[i] for i in (4, 5, 11)]
lat_dry = [lat[i] for i in (7, 8)]
long_dry = [long[i] for i in (7, 8)]

im = plt.imread('/Users/EmilioMartinez/Desktop/IMG_4311.jpeg'
                )  #plot the image of the specific lawn the mower is on
implot = plt.imshow(im,
                    extent=[
                        3818.5145133870965, 3818.52688661290,
                        10444.618690714286, 10444.635209285714
                    ])  #set the image on the corners of the axes of the graph
wet = plt.scatter(lat_wet, long_wet, c='c', marker='o')
sat = plt.scatter(lat_sat, long_sat, c='m', marker='o')
dry = plt.scatter(lat_dry, long_dry, c='#EDB120', marker='o')
plt.legend((wet, sat, dry), ('Wet Area', 'Saturated Area', 'Dry Area'),
           scatterpoints=1,
           loc='upper center',
           bbox_to_anchor=(0.5, -0.01),
           ncol=3,
           fontsize=8)
plt.title('Moisture Reading of Lawn', loc='center')
Example #43
0
from sklearn.metrics import accuracy_score


radius = 5
n_points = 8
X=[]
y=[]

filelist=glob.glob('GTSRB_subset/class1/*.jpg')
filelist2=glob.glob('GTSRB_subset/class2/*.jpg')

class_folders=sorted(glob.glob('GTSRB_subset/*'))
for i , folder in enumerate(class_folders):
    names=glob.glob(folder+'/*')
    for name in names:
        image=image=plt.imread(name)
        localbp = local_binary_pattern(image, n_points,radius)
        histogram = np.histogram(localbp, bins=range(257))[0]
        X.append(histogram)
        y.append(i)
    

#skimage.feature.local_binary_pattern
## settings for LBP



#
#

 
Example #44
0
#!/usr/bin/env python -W ignore::DeprecationWarning
import numpy as np
import pickle 

from matplotlib import pyplot as plt
from pylab import *


### this will be replaced with the real test image ###
im_test = plt.imread('parking_test.png')
###


# This function MUST take locations (loc) and an image (im) 
# as input parameters and return the feature vector
def my_feature_vector(loc, im, size = 10):
  w = size
  # a patch of the size w cenetered at loc is extracted as a feature vector
  patch = im[loc[1]-w:loc[1]+w, loc[0]-w:loc[0]+w]
  p = np.array(patch).flatten()
  return p 
  

## 10 preview test locations
### these will be replaced with the real set of 100 test locations ###
test_locs_labs = np.load('test_locations_and_labels.np')

test_locs   = test_locs_labs[:,0:2]
test_labels = test_locs_labs[:,2]

X_test = []
Example #45
0
# Plotando a árvore
from sklearn import tree
from sklearn.tree import export_graphviz

export_graphviz(dt, out_file='arvore_cls.dot', 
                feature_names = X.columns,
                class_names = 'PARTO',
                rounded = True, proportion = False, 
                precision = 2, filled = True)

from subprocess import call
call(['dot', '-Tpng', 'arvore_cls.dot', '-o', 'arvore_cls.png', '-Gdpi=600'])

import matplotlib.pyplot as plt
plt.figure(figsize = (14, 18))
plt.imshow(plt.imread('arvore_cls.png'))
plt.axis('off');
plt.show();

# =============================================================================
# Estratégia 2 - Random Forest
# =============================================================================
from sklearn.ensemble import RandomForestClassifier

# Random Forest
rf = RandomForestClassifier(n_estimators=100,n_jobs=-1)
rf.fit(X_train, y_train)
ClassificationScore(y_test, rf.predict(X_test))

# Precisamos ajustar os hiperparâmetros
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
Example #46
0
def get_images(filenames):
    print('getting images')
    imgs = [plt.imread(fname)[..., :3] for fname in filenames]
    return np.array(imgs)/255
Example #47
0
import matplotlib.pyplot as pyplot
import matplotlib.image as mpimg
import numpy as np

img = pyplot.imread("roomba.jpg")
h, w = img.shape[0:2]
print("Height: %d, width: %d" % (h, w))
#img = img[:,:,2]    #r,g,b = 0, 1, 2
rimg = img
rimg = rimg / 255.0

difference = rimg - np.array([1.0, 0.0, 0.0])
distance = np.linalg.norm(difference, axis=2)
threshold = distance > 0.6

pyplot.imshow(rimg[:, :, 0] > threshold)

pyplot.show()
Example #48
0
def annotate(centroids,
             image,
             circle_size=None,
             color=None,
             invert=False,
             ax=None,
             split_category=None,
             split_thresh=None,
             imshow_style={},
             plot_style={}):
    """Mark identified features with white circles.

    Parameters
    ----------
    centroids : DataFrame including columns x and y
    image : image array (or string path to image file)
    circle_size : Deprecated.
        This will be removed in a future version of trackpy.
        Use `plot_style={'markersize': ...}` instead.
    color : single matplotlib color or a list of multiple colors
        default None
    invert : If you give a filepath as the image, specify whether to invert
        black and white. Default True.
    ax : matplotlib axes object, defaults to current axes
    split_category : string, parameter to use to split the data into sections
        default None
    split_thresh : single value or list of ints or floats to split
        particles into sections for plotting in multiple colors.
        List items should be ordered by increasing value.
        default None
    imshow_style : dictionary of keyword arguments passed through to
        the `Axes.imshow(...)` command the displays the image
    plot_style : dictionary of keyword arguments passed through to
        the `Axes.plot(...)` command that marks the features

    Returns
    -------
    Axes object
    
    See Also
    --------
    annotate3d : The 3D equivalent that returns a scrollable stack.
    """
    import matplotlib.pyplot as plt

    if image.ndim != 2 and not (image.ndim == 3 and image.shape[-1] in (3, 4)):
        raise ValueError("image has incorrect dimensions. Please input a 2D "
                         "grayscale or RGB(A) image. For 3D image annotation, "
                         "use annotate3d. Multichannel images can be "
                         "converted to RGB using pims.display.to_rgb.")

    if circle_size is not None:
        warnings.warn("circle_size will be removed in future version of "
                      "trackpy. Use plot_style={'markersize': ...} instead.")
        if 'marker_size' not in plot_style:
            plot_style['marker_size'] = np.sqrt(circle_size)  # area vs. dia.
        else:
            raise ValueError("passed in both 'marker_size' and 'circle_size'")

    _plot_style = dict(markersize=15,
                       markeredgewidth=2,
                       markerfacecolor='none',
                       markeredgecolor='r',
                       marker='o',
                       linestyle='none')
    _plot_style.update(**_normalize_kwargs(plot_style, 'line2d'))
    _imshow_style = dict(origin='lower',
                         interpolation='nearest',
                         cmap=plt.cm.gray)
    _imshow_style.update(imshow_style)

    # https://docs.python.org/2/library/itertools.html
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)

    if color is None:
        color = ['r']
    if isinstance(color, str):
        color = [color]
    if not isinstance(split_thresh, Iterable):
        split_thresh = [split_thresh]

    # The parameter image can be an image object or a filename.
    if isinstance(image, str):
        image = plt.imread(image)
    if invert:
        ax.imshow(1 - image, **_imshow_style)
    else:
        ax.imshow(image, **_imshow_style)
    ax.set_xlim(-0.5, image.shape[1] - 0.5)
    ax.set_ylim(-0.5, image.shape[0] - 0.5)

    if split_category is None:
        if np.size(color) > 1:
            raise ValueError("multiple colors specified, no split category "
                             "specified")
        _plot_style.update(markeredgecolor=color[0])
        ax.plot(centroids['x'], centroids['y'], **_plot_style)
    else:
        if len(color) != len(split_thresh) + 1:
            raise ValueError("number of colors must be number of thresholds "
                             "plus 1")
        low = centroids[split_category] < split_thresh[0]
        _plot_style.update(markeredgecolor=color[0])
        ax.plot(centroids['x'][low], centroids['y'][low], **_plot_style)

        for c, (bot, top) in zip(color[1:-1], pairwise(split_thresh)):
            indx = ((centroids[split_category] >= bot) &
                    (centroids[split_category] < top))
            _plot_style.update(markeredgecolor=c)
            ax.plot(centroids['x'][indx], centroids['y'][indx], **_plot_style)

        high = centroids[split_category] >= split_thresh[-1]
        _plot_style.update(markeredgecolor=color[-1])
        ax.plot(centroids['x'][high], centroids['y'][high], **_plot_style)
    return invert_yaxis(ax)
Example #49
0
    for pixel in pixels:
        total = 0
        for x in pixel:
            total += x
        total = int(total/3)
        pixels2.append((total, total, total))
    # takes the image and filters it based on input cutoff
    filtered_list = filter(cutoff, pixels2)



if __name__ == '__main__':
    image = 'filtered_only_corner.jpg'
    img = Image.open(image)
    pixels = list(img.getdata())
    pixels_array = py.imread(image)
    height, width, depth = pixels_array.shape
    get_filtered_array(140)
    corner_1_height, corner_1_width = mean_bright_pt(pixels_array, 0, int(height / 2), 0, int(width / 2))  # top left
    corner_2_height, corner_2_width = mean_bright_pt(pixels_array, 0, int(height / 2), int(width / 2) + 1, width)
    # top right
    corner_3_height, corner_3_width = mean_bright_pt(pixels_array, int(height / 2) + 1, height, 0, int(width / 2))
    # bottom left
    corner_4_height, corner_4_width = mean_bright_pt(pixels_array, int(height / 2) + 1, height, int(width / 2) + 1,
                                                     width)  # bottom right
    # found the four corners of the image
    row_1_y_fl = list(np.linspace(corner_1_height,corner_2_height,127))
    row_1_x_fl = list(np.linspace(corner_1_width,corner_2_width,127))
    # row is made by linear interpolation
    row_1_y = [int(y) for y in row_1_y_fl]
    row_1_x = [int(x) for x in row_1_x_fl]
'''
Visualize a model
Now that you've compiled the model, take a look a the result of your hard work! You can do this by looking at the model summary, as well as its plot.

The summary will tell you the names of the layers, as well as how many units they have and how many parameters are in the model.

The plot will show how the layers connect to each other.

Instructions
100 XP
Summarize the model.
Plot the model.
'''
SOLUTION

# Import the plotting function
from keras.utils import plot_model
import matplotlib.pyplot as plt

# Summarize the model
model.summary()

# Plot the model
plot_model(model, to_file='model.png')

# Display the image
data = plt.imread('model.png')
plt.imshow(data)
plt.show()
Example #51
0
 def draw_accident_on_map(self,location):
     img = plt.imread('covid.png')
     imagebox= OffsetImage(img,zoom=0.05)
     ab = AnnotationBbox(imagebox,location)
     self.canvas.axes.add_artist(ab)
     self.canvas.draw()
Example #52
0
    img[:, :, 0] += 103.939
    img[:, :, 1] += 116.779
    img[:, :, 2] += 123.68
    # BGR -> RGB
    img = img[:, :, ::-1]
    img = np.clip(img, 0, 255).astype("uint8")
    return img


# ########################## main ###########################

DATA_DIR = "data"

IMAGE_FILE = os.path.join(DATA_DIR, "cat.jpg")

img = plt.imread(IMAGE_FILE)
plt.imshow(img)
img_copy = img.copy()
print("Original image shape:", img.shape)
image_shape_widh = img.shape[0]
image_shape_height = img.shape[1]
p_img = preprocess(img_copy)
print("After preprocess:", p_img.shape)
d_img = deprocess(p_img)
print("After deprocess:", d_img.shape)
plt.imshow(d_img)
plt.show()

# load pretrained VGG-16
batch_shape = p_img.shape
dream = Input(batch_shape=batch_shape)
Example #53
0

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import torch
import torchvision
from torchvision import models
import torch.nn as nn 
import shutil
import matplotlib.pyplot as plt
# get_ipython().magic('matplotlib inline')



image = plt.imread('../data/classify-leaves/images/1.jpg')

plt.imshow(image)
print(image.shape)
plt.show()


data_dir = "..\\data\\classify-leaves"


batch_size = 128
valid_ratio = 0.1
transform_train = torchvision.transforms.Compose([
    torchvision.transforms.RandomHorizontalFlip(),
    torchvision.transforms.ToTensor()
])
Example #54
0
 def draw_car_on_map(self,location):
     img = plt.imread('karetka.png')
     imagebox= OffsetImage(img,zoom=0.02)
     ab = AnnotationBbox(imagebox,location)
     self.canvas.axes.add_artist(ab)
     self.canvas.draw()
Example #55
0
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
                origin='lower', extent=[-3, 3, -3, 3],
                vmax=abs(Z).max(), vmin=-abs(Z).max())

plt.show()


###############################################################################
# It is also possible to show images of pictures.

# A sample image
with cbook.get_sample_data('ada.png') as image_file:
    image = plt.imread(image_file)

fig, ax = plt.subplots()
ax.imshow(image)
ax.axis('off')  # clear x- and y-axes


# And another image

w, h = 512, 512

with cbook.get_sample_data('ct.raw.gz', asfileobj=True) as datafile:
    s = datafile.read()
A = np.fromstring(s, np.uint16).astype(float).reshape((w, h))
A /= A.max()
Example #56
0
                                                       i - 2])

    def showImage(self):
        plt.imshow(self.img)
        plt.show()

    def getImage(self):
        return self.img


if __name__ == '__main__':
    import time
    img_name = input("Please name the image file: ")
    v_seams = int(input("Vertical seams to remove: "))
    h_seams = int(input("Horizontal seams to remove: "))
    img = plt.imread(img_name)
    if "png" in img_name:
        img = np.array(img * 255, dtype='uint8')
    sc = SeamCarver(img)
    a = time.time()
    for i in range(v_seams):
        sc.removeSeam()
    img = sc.getImage()
    sc = SeamCarver(np.transpose(img, (1, 0, 2)))
    for i in range(h_seams):
        sc.removeSeam()
    print("Elapsed time: {}".format((time.time() - a) / 60))
    #sc.showImage()
    img = sc.getImage()
    img = np.transpose(img, (1, 0, 2))
    plt.imshow(img)
Example #57
0
def get_points(im, N):
    plt.figure()
    plt.imshow(im)
    plt.title(f'get points')
    p = plt.ginput(N, timeout=0)
    return p


#%%

if __name__ == '__main__':

    plt.close('all')

    im1 = plt.imread('data/incline_L.png')
    im2 = plt.imread('data/incline_R.png')

    N = 5

    p1, p2 = getPoints_seq(im1, im2, N)
    p1, p2 = np.array(p1), np.array(p2)
    H = compute_H(p1, p2)

    p3 = np.array(get_points(im2, 10))

    plt.figure()
    plt.imshow(im2)
    plt.scatter(p3[:, 0], p3[:, 1])

    p1_cmp_nrm = poject(p3, H)
Example #58
0
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches
import sys
from matplotlib import cm

# erstes Argument ist Dateipfad eingabebild, muss aber im gleichen ordner liegen
image_url = sys.argv[1]
image = plt.imread(image_url)[:, :, 0]

height = image.shape[0]
width = image.shape[1]

#plt.figure("Red channel", figsize=(10,7))
# plt.imshow(image, cmap='gray')
# plt.show()

# FFT zur Auswahl Sattelit
fourier = np.fft.fftshift(np.fft.fft2(image))
magnitude_spectrum = np.log(np.abs(fourier + 1e-9))

plt.imshow(magnitude_spectrum)
plt.show()

# jetzt wirds hässlich

rect_center_x = int(input('X-Koordinate: '))

rect_center_y = int(input('Y-Koordinate: '))

rect_center_radius = 80
Example #59
0
from matplotlib import pyplot as plt

fig = plt.figure(figsize=(6, 2))

for i, filename in enumerate([
        'expected-legend_auto2.png', 'legend_auto2.png',
        'failed-diff-legend_auto2.png'
]):
    ax = fig.add_subplot(1, 3, i + 1)
    im = plt.imread(filename)
    ax.imshow(im)
    ax.set_xticks([])
    ax.set_yticks([])

fig.savefig('regression.pdf', dpi=600, bbox_inches='tight')
@author: trang.le
"""
# transforming png files [height,width,channel] to h5 format [channel,stack,height,weight]
import os
import h5py
import numpy as np
import matplotlib.pyplot as plt
import Segmentation_pipeline_helper

imageinput = "~/U2OS_noccd/PNG"
imageoutput = "~/U2OS_noccd/h5"

if not os.path.exists(imageoutput):
    os.makedirs(imageoutput)
    
l = find(imageinput,prefix=None, suffix=".png",recursive=False)
savepath=[]
for filepath in l:
    filepath=filepath.replace('.png','.h5')
    filepath=filepath.replace('PNG','h5')
    savepath.append(filepath)
    
for index,imgpath in enumerate(l):
    im = plt.imread(imgpath)
    x= np.transpose(im,(2,0,1))
    x= np.expand_dims(x, axis=1)
    h = h5py.File(savepath[index],"w")
    h.create_dataset('image',data=x)
    h.close