Esempio n. 1
0
def get_sweep(wfall):
    zoom = 1
    while zoom == 1:
        pl.imshow(wfall, aspect=0.1, cmap='Greys')
        pl.colorbar()
        pl.xlabel('Bins')
        pl.ylabel('Time')
        click = input('Ready to click ? :')
        if click == 'y':
            pl.title('Click on peak for t=0')
            t0 = pl.ginput(1)
            pl.close()
            break
        else:
            continue
    while zoom == 1:
        pl.imshow(wfall, aspect=0.1, cmap='Greys')
        pl.xlabel('Bins')
        pl.ylabel('Time')
        click = input('Ready to click ? :')
        if click == 'y':
            pl.title('Click on peak for t=1')
            t1 = pl.ginput(1)
            pl.close()
            break
        else:
            continue
    sweep = np.int(np.rint(t0[0][0]) - np.rint(t1[0][0]))
    return sweep
Esempio n. 2
0
def getClickedPointsByImage(filename,nPoints):
    im = np.array(Image.open(filename))
    plt.imshow(im)
    print 'Please click ' + str(nPoints) + 'points'
    x = plt.ginput(nPoints,-1)
    plt.show()
    return x
def find_gates(mag1, mag2, param):
    col = mag1 - mag2

    lines = open(param, 'r').readlines()
    colmin, colmax = map(float, lines[4].split()[3:-1])
    mag1min, mag1max = map(float, lines[5].split()[:-1])
    #mag2min, mag2max = map(float, lines[5].split()[:-1])
    # click around
    fig, ax = plt.subplots()
    ax.plot(col, mag2, ',', color='k', alpha=0.2)
    ax.set_ylim(mag1max, mag1min)
    ax.set_xlim(colmin, colmax)

    ok = 1
    while ok == 1:
        print 'click '
        pts = np.asarray(plt.ginput(n=4, timeout=-1))
        exclude_gate = '1 {} 0 \n'.format(' '.join(['%.4f' % p for p in pts.flatten()]))
        pts = np.append(pts, pts[0]).reshape(5,2)
        ax.plot(pts[:,0], pts[:,1], color='r', lw=3, alpha=0.3)
        plt.draw()
        ok = move_on(0)
    lines[7] = exclude_gate
    # not so simple ... need them to be parallelograms.
    # PASS!

    # write new param file with exclude/include gate
    os.system('mv {0} {0}_bkup'.format(param))
    with open(param, 'w') as outp:
        [outp.write(l) for l in lines]
    print('wrote %s' % param)
Esempio n. 4
0
def get_Period(dds_t, tsamp):
    N = np.int(nearest_power_of_2(dds_t.size))
    print('Padding ', dds_t.size, 'length array with ', N-dds_t.size, 'zeros.')
    DDS_T = np.abs(ft.rfft(dds_t-dds_t.mean(), N))
    nu = ft.rfftfreq(N, tsamp)
    zoom = 1
    while zoom == 1:
        pl.plot(nu, DDS_T)
        pl.xlabel('Frequency [Hz]')
        pl.ylabel('Flux')
        click = input('Ready to click ? :')
        if click == 'y':
            pl.title('Click on peak for F0')
            F0 = pl.ginput(1)
            zoom = 0
            break
        else:
            continue
            
    F0 = F0[0][0]
    P0 = 1.0 / F0
    pl.close()
    
    pl.plot(nu, DDS_T)
    pl.xlim(0.0, 12.5*F0)
    pl.xlabel('Frequency [Hz]')
    pl.ylabel('Flux')
    pl.title('First 12 harmonics')
    pl.savefig('First-12-harmonics.eps')
    pl.savefig('First-12-harmonics.png')
    return P0, F0
Esempio n. 5
0
def pick_particles(segmentation):
    """
    Allow user to locate a particle in a segmented image interactively.

    Args
    ----------
    segmentation : Numpy array
        Segmented label image

    Returns
    ----------
    particles : int
        Value associated with the chosen particle

    """
    numpoints = segmentation.max()
    # warnings.filterwarnings('ignore')
    plt.figure(frameon=False)
    plt.imshow(segmentation, cmap='nipy_spectral')
    plt.title('Choose particles ...')
    coords = np.array(plt.ginput(numpoints, timeout=0, show_clicks=True))
    plt.close()

    particles = np.zeros_like(segmentation)
    for i, _ in enumerate(coords):
        val = segmentation[np.int32(coords[i][1]), np.int32(coords[i][0])]
        particles[segmentation == val] = val
    return particles
Esempio n. 6
0
def remove_particles(segmentation):
    """
    Remove particles from segmentation via user interaction.

    Args
    ----------
    segmentation : Numpy array
        Segmented label image

    Returns
    ----------
    segmentation : Numpy array
        Segmented label image after particle removal
    removed_any : bool
        True if any particles were removed.  Otherwise, False
    n_removed : int
        Number of particles removed from image

    """
    numpoints = segmentation.max()
    removed_any = False
    plt.figure(frameon=False)
    plt.imshow(segmentation, cmap='nipy_spectral')
    plt.title('Choose particles to remove...')
    coords = np.array(plt.ginput(numpoints, timeout=0, show_clicks=True))
    plt.close()
    n_removed = len(coords)
    if n_removed > 0:
        removed_any = True
    for i, _ in enumerate(coords):
        val = segmentation[np.int32(coords[i][1]), np.int32(coords[i][0])]
        segmentation[segmentation == val] = 0
    return segmentation, removed_any, n_removed
Esempio n. 7
0
def interaction():
    """
    Interaction with plots
    """
    print("Please click 3 points")
    x = plt.ginput(3)
    print("you clicked: ", x)
Esempio n. 8
0
def find_gates(mag1, mag2, param):
    """Click 4 points to make an exclude gate -- does not work in calcsfh!"""
    print('not supported')
    sys.exit()
    col = mag1 - mag2

    lines = open(param, 'r').readlines()
    colmin, colmax = map(float, lines[4].split()[3:-1])
    mag1min, mag1max = map(float, lines[5].split()[:-1])
    # mag2min, mag2max = map(float, lines[5].split()[:-1])
    # click around
    _, ax = plt.subplots()
    ax.plot(col, mag2, ',', color='k', alpha=0.2)
    ax.set_ylim(mag1max, mag1min)
    ax.set_xlim(colmin, colmax)

    okay = 1
    while okay != 0:
        print('click ')
        pts = np.asarray(plt.ginput(n=4, timeout=-1))
        exclude_gate = '1 {} 0 \n'.format(' '.join(
            ['%.4f' % p for p in pts.flatten()]))
        pts = np.append(pts, pts[0]).reshape(5, 2)
        ax.plot(pts[:, 0], pts[:, 1], color='r', lw=3, alpha=0.3)
        plt.draw()
        okay = move_on(0)
    lines[7] = exclude_gate
    # not so simple ... need them to be parallelograms.
    # PASS!

    # write new param file with exclude/include gate
    os.system('mv {0} {0}_bkup'.format(param))
    with open(param, 'w') as outp:
        _ = [outp.write(l) for l in lines]
    print('wrote %s' % param)
Esempio n. 9
0
 def get_cursor_id(self, x, y):
     c = zip(*(pylab.ginput(n=0, mouse_add=1, mouse_pop=2, mouse_stop=3)))
     lonpt, latpt = self(c[0], c[1], inverse=True)
     for enum in enumerate(zip(*(lonpt, latpt))):
         dst = calcul_distance(enum[1][1], enum[1][0], x, y)
         if enum[0] == 0: i = [np.argmin(dst).tolist()]
         else: i.append(np.argmin(dst))
     return i
Esempio n. 10
0
def screen_cut_and_get_point():
    screen_img = screen_capture()
    pylab.figure(1, tight_layout=True)
    pylab.axis('off')
    pylab.imshow(screen_img)
    mng = pylab.get_current_fig_manager()
    mng.window.showMaximized()
    mng.set_window_title('请用鼠标点击希望模拟鼠标点击的区域')
    point = pylab.ginput(1)[0]
    pylab.close()
    return point
Esempio n. 11
0
def main():
    # paths: change to folder selection
    imageFolder = sys.argv[1]
    imageFile = sys.argv[2]

    imagePath = imageFolder + imageFile

    original = cv.LoadImageM(imagePath)

    img = cv.LoadImageM(imagePath, cv.CV_LOAD_IMAGE_GRAYSCALE)
    eig_image = cv.CreateMat(img.rows, img.cols, cv.CV_32FC1)
    temp_image = cv.CreateMat(img.rows, img.cols, cv.CV_32FC1)
    tracker_coords = []
    for (x, y) in cv.GoodFeaturesToTrack(img, eig_image, temp_image, 2000, 0.001, 5.0, useHarris=True):
        tracker_coords.append([x, y])

    tracker_coords = np.array(tracker_coords)

    # crop image
    while True:
        plt.cla()
        plt.imshow(original)
        plt.plot(tracker_coords[:, 0], tracker_coords[:, 1], "ro", markersize=3)
        a = ginput(2)
        xmin = min([a[0][0], a[1][0]])
        xmax = max([a[0][0], a[1][0]])
        ymin = min([a[0][1], a[1][1]])
        ymax = max([a[0][1], a[1][1]])
        plt.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], "-bo")
        plt.draw()
        if tkMessageBox.askyesno("Save Grid", "Keep this selection?"):
            break

    # filter out points
    output_trackers = []
    for point in tracker_coords:
        if (point[0] > xmin and point[0] < xmax and point[1] > ymin and point[1] < ymax).all():
            output_trackers.append(point)

    output_trackers = np.array(output_trackers)

    # save data as grid
    np.savetxt(imageFolder + "grid_x.dat", output_trackers[:, 0])
    np.savetxt(imageFolder + "grid_y.dat", output_trackers[:, 1])

    print a
    plt.show()
Esempio n. 12
0
 def get_cursor(self, *args):
     c = zip(*(pylab.ginput(n=0, mouse_add=1, mouse_pop=2, mouse_stop=3)))
     lonpt, latpt = self(c[0], c[1], inverse=True)
     for enum in enumerate(zip(*(lonpt, latpt))):
         dst = calcul_distance(enum[1][1], enum[1][0], args[0], args[1])
         i = np.argmin(dst)
         xdum = args[0][i]
         ydum = args[1][i]
         if len(args) == 3: zdum = args[2][i]
         if enum[0] == 0:
             xout = xdum
             yout = ydum
             if len(args) == 3: zout = zdum
         else:
             xout = np.append(xout, xdum)
             yout = np.append(yout, ydum)
             if len(args) == 3: zout = np.append(zout, zdum)
     if len(args) == 3: return xout, yout, zout
     else: return xout, yout
def find_gates(target):
    import glob
    here = os.getcwd()
    os.chdir(target)
    # read match file for mag1, mag2
    phot = glob.glob1('.', '*match')
    params = glob.glob1('.', '*param')
    for i, param in enumerate(params):
        # read param file
        mag1, mag2 = np.genfromtxt(phot[i], unpack=True)
        col = mag1 - mag2

        lines = open(param, 'r').readlines()
        colmin, colmax = map(float, lines[4].split()[3:-1])
        mag1min, mag1max = map(float, lines[5].split()[:-1])
        #mag2min, mag2max = map(float, lines[5].split()[:-1])
        # click around
        fig, ax = plt.subplots()
        ax.plot(col, mag2, ',', color='k', alpha=0.2)
        ax.set_ylim(mag1max, mag1min)
        ax.set_xlim(colmin, colmax)
    
        ok = 1
        while ok == 1:
            print 'click '
            pts = np.asarray(plt.ginput(n=4, timeout=-1))
            exclude_gate = '1 {} 0 \n'.format(' '.join(['%.4f' % p for p in pts.flatten()]))
            pts = np.append(pts, pts[0]).reshape(5,2)
            ax.plot(pts[:,0], pts[:,1], color='r', lw=3, alpha=0.3)
            plt.draw()
            ok = move_on(0)
        lines[7] = exclude_gate
        # not so simple ... need them to be parallelograms.
        # PASS!
        
        # write new param file with exclude/include gate
        os.system('mv {0} {0}_bkup'.format(param))
        with open(param, 'w') as outp:
            [outp.write(l) for l in lines]
        print('wrote %s' % param)
    
    os.chdir(here)
Esempio n. 14
0
def select_gate(wfall):
    g_on = [0, 0]
    profile = wfall.mean(axis=0)
    pl.plot(profile)
    zoom = 1
    while zoom == 1:
        pl.plot(profile,'kx', lw=1.0)
        pl.xlabel('Bin #')
        pl.ylabel('Flux')
        click = input('Ready to click ? :')
        if click == 'y':
            pl.title('Select gate for dynamic spectrum')
            gate = pl.ginput(2)
            zoom = 0
            break
        else:
            continue
            
    g_on[0] = np.int(np.floor(gate[0][0]))
    g_on[1] = np.int(np.ceil(gate[1][0]))

    return g_on
Esempio n. 15
0
def main():
    # paths: change to folder selection
    imageFolder = sys.argv[1]
    imageFile = sys.argv[2]
    imagePath = imageFolder + imageFile

    original = cv.LoadImageM(imagePath)

    tracker_coords = []

    tracker_coords = np.array(tracker_coords)

    nr_points = int(sys.argv[3])

    plt.imshow(original)
    tracker_coords = ginput(nr_points)
    tracker_coords = np.array(tracker_coords)
    plt.plot(tracker_coords[:,0], tracker_coords[:,1],'ro',markersize=3)

    # save data as grid
    np.savetxt(imageFolder + 'grid_x.dat',tracker_coords[:,0])
    np.savetxt(imageFolder + 'grid_y.dat',tracker_coords[:,1])

    plt.show()
Esempio n. 16
0
def online_orica_spike_sorting(recording,
                               n_comp='all',
                               pca_window=0,
                               ica_window=0,
                               skew_window=5,
                               step=1,
                               skew_thresh=0.5,
                               online=False,
                               detect=True,
                               calibPCA=True,
                               ff='cooling',
                               lambda_val=0.995,
                               dtype='int16',
                               verbose=True,
                               detect_thresh=10,
                               white_mode='pca',
                               pca_block=2000,
                               ica_block=800):
    import matplotlib.pylab as plt

    if not isinstance(recording, BaseRecording):
        raise Exception("Input a RecordingExtractor object!")

    if n_comp == 'all':
        n_comp = recording.get_num_channels()
    fs = recording.get_sampling_frequency()

    traces = recording.get_traces().astype(dtype).T

    t_init = time.time()

    ori = orica.onlineORICAss(traces,
                              fs=fs,
                              onlineWhitening=online,
                              calibratePCA=calibPCA,
                              ndim=n_comp,
                              forgetfac=ff,
                              lambda_0=lambda_val,
                              numpass=1,
                              step_size=step,
                              skew_window=skew_window,
                              pca_window=pca_window,
                              ica_window=ica_window,
                              verbose=True,
                              detect_trheshold=detect_thresh,
                              onlineDetection=False,
                              white_mode=white_mode,
                              pca_block=pca_block,
                              ica_block=ica_block)
    if verbose:
        t_orica_online = time.time() - t_init
        print('Online ORICA completed in: ', t_orica_online)

    last_idxs = find_consistent_sorces(ori.source_idx, thresh=0.5)
    # last_idxs = ori.all_sources
    last_idxs = last_idxs[np.argsort(
        np.abs(stats.skew(ori.y[last_idxs], axis=1)))[::-1]]
    n_id = len(last_idxs)

    y_on_selected = ori.y_on[last_idxs]
    y_on = np.array([
        -np.sign(sk) * s
        for (sk, s) in zip(stats.skew(y_on_selected, axis=1), y_on_selected)
    ])

    if verbose:
        print('Rough spike detection to choose thresholds')
    t_start = 0 * pq.s
    t_stop = recording.get_num_frames() / float(fs) * pq.s
    detected_spikes = detect_and_align(y_on,
                                       fs,
                                       traces,
                                       t_start=t_start,
                                       t_stop=t_stop,
                                       n_std=5,
                                       upsample=1)

    # Manual thresholding
    thresholds = []
    for i, st in enumerate(detected_spikes):
        fig = plt.figure(figsize=(10, 10))
        # only plot 10% of the spikes
        perm = np.random.permutation(len(st))
        nperm = int(0.2 * len(st))
        plt.plot(st.annotations['ica_wf'][perm[:nperm]].T, lw=0.1, color='g')
        plt.title('IC  ' + str(i + 1))
        coord = plt.ginput()
        th = coord[0][1]
        plt.close(fig)
        thresholds.append(th)

    ## User defined thresholds and detection
    if verbose:
        print('Detecting spikes based on user-defined thresholds')
    spikes = threshold_spike_sorting(y_on, thresholds)

    # Convert spikes to neo
    spike_trains = []
    for i, k in enumerate(sorted(spikes.keys())):
        times = spikes[k]
        tt = np.array(times) / float(fs)
        # st = neo.SpikeTrain(times=tt, t_start=(pca_window + ica_window) * pq.s, t_stop=t_stop)
        st = neo.SpikeTrain(times=tt * pq.s, t_start=t_start, t_stop=t_stop)
        st.annotate(ica_source=last_idxs[i])
        spike_trains.append(st)

    sst, independent_spike_idx, dup = reject_duplicate_spiketrains(
        spike_trains)

    if verbose:
        print('Number of spiky sources: ', len(spike_trains))
        print('Number of spike trains after duplicate rejection: ', len(sst))

    ica_spike_sources_idx = last_idxs[independent_spike_idx]
    ica_spike_sources = ori.y[ica_spike_sources_idx]
    A_spike_sources = ori.mixing[-1, ica_spike_sources_idx]
    W_spike_sources = ori.unmixing[-1, ica_spike_sources_idx]

    if verbose:
        print('Elapsed time: ', time.time() - t_init)

    sorting = ss.set_times_labels(sst, fs)

    return sorting  # , ica_spike_sources
import numpy as np
import Image
import matplotlib.pylab as plt
from im2array import *


im = Image.open('cam1.10000')

imnp = image2array(im)
plt.figure()
plt.imshow(imnp,cmap = plt.cm.gray)

# now press 2 corners: top-left, right-bottom
x = plt.ginput(2)
# parsing
a,b=x[0]; c,d=x[1]
box1 = (a,b,c,d)

# now press again 2 corners: top-left, right-bottom
x = plt.ginput(2)
# parsing
a,b=x[0]; c,d=x[1]
box2 = (a,b,c,d)

# crop using PIL
ball1 = im.crop(box1)
ball2 = im.crop(box2)

# resize to get integer sizes for sure

ball1 = ball1.resize((int(ball1.size[0]),int(ball1.size[1])))
def find_match_limits(phot, phot_ext, comp1=99., comp2=None, color_only=False,
                      xlim=None, ylim=None):
    """
    click color limits on a cmd and mag1 mag2 limits on a plot of mag1 vs mag2
    """
    mag1 = phot['mag1_%s' % phot_ext]
    mag2 = phot['mag2_%s' % phot_ext]
    col = mag1 - mag2

    fig, ax = plt.subplots()
    ax.plot(col, mag2, 'o', color='k', ms=3, alpha=0.3, mec='none')
    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)
    else:
        ax.set_ylim(ax.get_ylim()[::-1])
    
    if comp2 is not None:
        ax.hlines(comp2, *ax.get_xlim())
    else:
        comp2 = 99.

    ok = 1
    while ok == 1:
        print 'click on color min then color max'
        pts = plt.ginput(2, timeout=-1)
        colmin, colmax = [pts[i][0] for i in range(2)]
        ax.vlines(colmin, *ax.get_ylim())
        ax.vlines(colmax, *ax.get_ylim())
        plt.draw()
        ok = move_on(0)

    plt.close()

    inds, = np.nonzero((col < colmax) & (col > colmin))
    data = (colmin, colmax)
    if not color_only:
        fig, ax = plt.subplots()
        ax.plot(mag1, mag2, '.', color='k')
        ok = 1
        while ok == 1:
            print 'click the bright mag value of mag1 and mag2, click a second time to finish'
            pts = plt.ginput(2, timeout=-1)
            mag1max, mag2max = pts[0]
            ax.plot(mag1max, mag2max, 'o', color='r')
            plt.draw()
            ok = move_on(ok)

        plt.close()

        inds, = np.nonzero((mag1 < comp1) & (mag1 > mag1max) &
                           (mag2 < comp2) & (mag2 > mag2max) &
                           (col < colmax) & (col > colmin))

    fig, ax = plt.subplots()
    ax.plot(col, mag2, '.', color='k')
    ax.plot(col[inds], mag2[inds], '.', color='r')
    ax.set_ylim(ax.get_ylim()[::-1])
    ax.hlines(comp2, *ax.get_xlim(), lw=2)
    ax.vlines(colmin, *ax.get_ylim(), lw=2)
    ax.vlines(colmax, *ax.get_ylim(), lw=2)
    if not color_only:
        ax.hlines(mag2max, *ax.get_xlim(), lw=2)
        data = (colmin, colmax, mag1max, mag2max)
    
    plt.draw()

    return data
def find_match_limits(mag1, mag2, comp1=90., comp2=90., color_only=False,
                      xlim=None, ylim=None):
    """
    click color limits on a cmd and mag1 mag2 limits on a plot of mag1 vs mag2
    """
    col = mag1 - mag2

    fig, ax = plt.subplots()
    ax.plot(col, mag2, 'o', color='k', ms=3, alpha=0.3, mec='none')
    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)
    else:
        ax.set_ylim(ax.get_ylim()[::-1])

    if comp1 < 90.:
        ax.hlines(comp2, *ax.get_xlim())

    ok = 1
    while ok == 1:
        print 'click color extrema'
        pts = plt.ginput(2, timeout=-1)
        colmin, colmax = [pts[i][0] for i in range(2)]
        if colmin > colmax:
            colmin, colmax = colmax, colmin
        ax.vlines(colmin, *ax.get_ylim())
        ax.vlines(colmax, *ax.get_ylim())
        plt.draw()
        ok = move_on(0)

    plt.close()

    inds, = np.nonzero((col < colmax) & (col > colmin))
    data = (colmin, colmax)
    if not color_only:
        fig, ax = plt.subplots()
        ax.plot(mag1, mag2, '.', color='k')
        ok = 1
        while ok == 1:
            print 'click mag extrema'
            pts = plt.ginput(2, timeout=-1)
            mag1max, mag2max = pts[0]
            mag1min, mag2min = pts[1]
            if mag1min > mag1max:
                mag1min, mag1max = mag1max, mag1min
            if mag2min > mag2max:
                mag2min, mag2max = mag2max, mag2min

            ax.plot(mag1max, mag2max, 'o', color='r')
            ax.plot(mag1min, mag2min, 'o', color='r')
            plt.draw()
            ok = move_on(ok)

        plt.close()

        inds, = np.nonzero((mag1 < mag1min) & (mag1 > mag1max) &
                           (mag2 < mag2min) & (mag2 > mag2max) &
                           (col < colmax) & (col > colmin))

    fig, ax = plt.subplots()
    ax.plot(col, mag2, '.', color='k')
    ax.plot(col[inds], mag2[inds], '.', color='r')
    ax.set_ylim(ax.get_ylim()[::-1])
    if comp2 < 90.:
        ax.hlines(comp2, *ax.get_xlim(), lw=2)
    ax.vlines(colmin, *ax.get_ylim(), lw=2)
    ax.vlines(colmax, *ax.get_ylim(), lw=2)
    if not color_only:
        ax.hlines(mag2max, *ax.get_xlim(), lw=2)
        data = (colmin, colmax, mag1min, mag1max, mag2min, mag2max)

    plt.draw()

    print data
    return data
print 'reading', ImageToLoad

# Read the image and convert it to grayscale rightaway
ImageRGB = plt.imread(ImageToLoad)
Image = rgb2gray(ImageRGB)

ImageWidth = Image.shape[0]
ImageHeight = Image.shape[1]
print 'The image we loaded is', ImageWidth, 'by', ImageHeight, \
    'pixels big. That is', round(ImageWidth * ImageHeight / 1e6, 3), 'MPx.'

plt.subplot(221)
plt.imshow(ImageRGB, origin='lower')
plt.title('Pick point for drawing\n horizontal and vertical profile')
if SelectStartPointManually:
    PickPoint = plt.ginput(1)
else:
    if Camera == 'iPhone':
        PickPoint = [[1500, 1000]]
    elif Camera[:6] == 'tiscam':
        # Select middle of image...
        PickPoint = [[ImageHeight / 2, ImageWidth / 2]]
    elif Camera == 'Elphel':
        PickPoint = [[ImageHeight / 2, ImageWidth / 2]]
plt.title('Original image')
Horizon = int(PickPoint[0][1])
Vertigo = int(PickPoint[0][0])
if SelectStartPointManually:
    print 'You selected horizontal line', Horizon, 'and vertical line', Vertigo
else:
    print 'I selected horizontal line', Horizon, 'and vertical line', Vertigo
Esempio n. 21
0
import numpy as np
import Image
import matplotlib.pylab as plt
from im2array import *

im = Image.open('cam1.10000')

imnp = image2array(im)
plt.figure()
plt.imshow(imnp, cmap=plt.cm.gray)

# now press 2 corners: top-left, right-bottom
x = plt.ginput(2)
# parsing
a, b = x[0]
c, d = x[1]
box1 = (a, b, c, d)

# now press again 2 corners: top-left, right-bottom
x = plt.ginput(2)
# parsing
a, b = x[0]
c, d = x[1]
box2 = (a, b, c, d)

# crop using PIL
ball1 = im.crop(box1)
ball2 = im.crop(box2)

# resize to get integer sizes for sure
Esempio n. 22
0
    # nonlinear
    print('getting filenames...')
    abs_exper = sorted(glob(basepath + 'abs*'))
    relu_exper = sorted(glob(basepath + 'relu*'))
    select_exper = sorted(glob(basepath + 'select-*'))
    select_max_exper = sorted(glob(basepath + 'select_max*'))

    print('loading data...')
    abs_data = load_experiment_data(abs_exper)
    relu_data = load_experiment_data(relu_exper)
    select_data = load_experiment_data(select_exper)
    select_max_data = load_experiment_data(select_max_exper)

    print('displying data...')
    display_griddata([abs_data, relu_data, select_data, select_max_data],
                     savepath + 'nonlinearity')

    # aggregation
    avg_exper = sorted(glob(basepath + 'avg*'))
    max_norm_exper = sorted(glob(basepath + 'max_norm*'))
    max_exper = sorted(glob(basepath + 'max-*'))

    avg_data = load_experiment_data(avg_exper)
    max_norm_data = load_experiment_data(max_norm_exper)
    max_data = load_experiment_data(max_exper)

    display_griddata([avg_data, max_data, max_norm_data],
                     savepath + 'aggregation')

    plt.ginput()
Esempio n. 23
0
    balloon = dphi_norm
    attachment = dot(dphi, dg)
    dphi_t = smoothing + balloon + attachment
    phi = phi + dphi_t
    return phi


# np.set_printoptions(threshold=np.inf)
im = Image.open('Moon.jpg')
im2 = np.array(Image.open('background2.jpg'))
im = im.resize((im2.shape[1], im2.shape[0]))
im_copy = im.copy()
im1 = im_copy.resize((im2.shape[1] // 4, im2.shape[0] // 4))

plt.imshow(im1)
X = plt.ginput(4)
X = np.array(X)
plt.close()

a = np.max(X, axis=0)
b = np.min(X, axis=0)
contour = active_contour(np.array(im1.convert('L')), b, a, 100, 0.05)

mask = np.clip(contour, 0, 1)
mask1 = 1 - mask
mask1 = cv2.resize(mask1, (im2.shape[1], im2.shape[0]))
mask1 = np.dstack((mask1, mask1, mask1))

p1 = mask1 * im
p1 = p1.astype(np.uint8)
plt.figure()
Esempio n. 24
0
def study_dndz_interactive():
    x, z, type = match_wise_cosmos(quick=True)
    w1=x[:,0]
    w2=x[:,1]
    w3=x[:,2]
    w4=x[:,3]
    j=x[:,4]
    h=x[:,5]
    k=x[:,6]

    cA = w1
    cB = w2-w4-0.7*w1
    xlab = 'W1'
    ylab = 'W2-W4-0.7W1'
    fs = 16

    from matplotlib import rc
    rc('xtick', labelsize=17) 
    rc('ytick', labelsize=17) 
    fcolor='green'
    fcolor='blue'
    pl.figure(1, figsize=(12,8))
    pl.clf()
    pl.subplot(2,1,1)
    pl.plot(cA,cB,'k.')
    pl.xlabel(xlab,fontsize=fs);pl.ylabel(ylab,fontsize=fs)

    keep_going=True
    from matplotlib.pylab import ginput
    import cosmolopy as cp
    while keep_going:
        pt = ginput(2,timeout=100000)
        pl.clf()
        pl.subplot(2,1,1)
        pl.plot(cA,cB,'k.')
        pl.xlabel(xlab,fontsize=fs);pl.ylabel(ylab,fontsize=fs)
        if pt[0]==pt[1]:
            keep_going=False
        else:
            x0 = pt[0][0]
            y0 = pt[0][1]
            x1 = pt[1][0]
            y1 = pt[1][1]
            cA_min = np.min([x0,x1])
            cA_max = np.max([x0,x1])
            cB_min = np.min([y0,y1])
            cB_max = np.max([y0,y1])
            wh_cut = np.where((cA>=cA_min) & (cA<=cA_max) & (cB>=cB_min) & (cB<=cB_max) & (type==0))[0]
            n_cut = len(wh_cut)

            pl.subplot(2,1,1)
            pl.plot(cA[wh_cut], cB[wh_cut],'r.')
            pl.xlabel(xlab,fontsize=fs);pl.ylabel(ylab,fontsize=fs)
            meanz = np.mean(z[wh_cut])
            medz = np.median(z[wh_cut])
            pl.title('[%0.2f, %0.2f], [%0.2f, %0.2f], %i gals, <z>=%0.2f, |z|=%0.2f, sig=%0.2f'%(cA_min, cA_max, cB_min, cB_max, n_cut, meanz, medz,np.std(z[wh_cut])), fontsize=16)
#            pl.legend(['%0.2f, %0.2f'%(cA_min, cA_max), '%0.2f, %0.2f'%(cB_min, cB_max)], 'upper left')

            pl.subplot(2,1,2)
            zbins = np.linspace(0.1,2.0,15)
            n, bins, patches = pl.hist(z[wh_cut], zbins, normed=0, facecolor=fcolor, alpha=0.5)
            zcen = 0.5*(zbins[0:-1]+zbins[1:])
            rsound_com = 153.
            rsound_phs = rsound_com/(1.+zcen)
            dang = cp.distance.angular_diameter_distance(zcen,**cp.fidcosmo)
            ang_sound = rsound_phs/dang
            ang_sound /= np.median(ang_sound)
            pl.xlabel('Redshift (z)',fontsize=20)
            pl.ylabel('N',fontsize=20)
print 'reading', ImageToLoad

# Read the image and convert it to grayscale rightaway
ImageRGB = plt.imread(ImageToLoad)
Image = rgb2gray(ImageRGB)

ImageWidth = Image.shape[0]
ImageHeight = Image.shape[1]
print 'The image we loaded is', ImageWidth, 'by', ImageHeight, \
    'pixels big. That is', round(ImageWidth * ImageHeight / 1e6, 3), 'MPx.'

plt.subplot(221)
plt.imshow(ImageRGB, origin='lower')
plt.title('Pick point for drawing\n horizontal and vertical profile')
if SelectStartPointManually:
    PickPoint = plt.ginput(1)
else:
    if Camera == 'iPhone':
        PickPoint = [[1500, 1000]]
    elif Camera[:6] == 'tiscam':
        # Select middle of image...
        PickPoint = [[ImageHeight / 2, ImageWidth / 2]]
    elif Camera == 'Elphel':
        PickPoint = [[ImageHeight / 2, ImageWidth / 2]]
plt.title('Original image')
Horizon = int(PickPoint[0][1])
Vertigo = int(PickPoint[0][0])
if SelectStartPointManually:
    print 'You selected horizontal line', Horizon, 'and vertical line', Vertigo
else:
    print 'I selected horizontal line', Horizon, 'and vertical line', Vertigo
Esempio n. 26
0
# Load projection matrices for views p, q, r
P1 = data['P'][:, :, p]  # Reprojection matrix of view p
P2 = data['P'][:, :, q]  # Reprojection matrix of view q
P3 = data['P'][:, :, r]  # Reprojection matrix of view r
P = np.vstack([P1, P2, P3])  # Join all projection matrices

Ip = image_set.load_image(44, p)
Iq = image_set.load_image(44, q)
Ir = image_set.load_image(44, r)

# Plot lines and plot on figures
fig1, ax1 = plt.subplots(1, 1, subplot_kw=dict(title='Figure p'))
ax1.imshow(Ip, cmap='gray')
ax1.axis('off')
print('Click first and second points in Figure 1 ...')
mp = np.hstack([np.array(plt.ginput(2)), np.ones((2, 1))]).T  # Click
ax1.plot(mp[0, :], mp[1, :], 'ro')
ax1.plot(mp[0, :], mp[1, :], 'g', linewidth=1.0)
fig1.canvas.draw()

fig2, ax2 = plt.subplots(1, 1, subplot_kw=dict(title='Figure q'))
ax2.imshow(Iq, cmap='gray')
ax2.axis('off')
print('Click first and second points in Figure 2 ...')
mq = np.hstack([np.array(plt.ginput(2)), np.ones((2, 1))]).T  # Click
ax2.plot(mq[0, :], mq[1, :], 'ro')
ax2.plot(mq[0, :], mq[1, :], 'g', linewidth=1.0)
fig2.canvas.draw()

fig3, ax3 = plt.subplots(1, 1, subplot_kw=dict(title='Figure r'))
ax3.imshow(Ir, cmap='gray')
 
 #use filtered
 #d1=data1_filt[start_time_index:end_time_index]
 #d2=data2_filt[start_time_index:end_time_index]
 if plotshots:
     
     plt.plot(np.array(timeB_us),data1mod_norm)
     plt.plot(np.array(timeB_us),data2mod_norm)
     plt.title(tde_pair[0]+tde_pair[1]+' Shot '+str(shot))
     plt.xlim(0.0,40.0)
     plt.ylim(0,0.3)
     
     # Bind the button_press_event with the onclick() method
     fig.canvas.mpl_connect('button_press_event', onclick)
     plt.show()    
     plt.ginput(10,timeout=0)
     plt.clf()
     
     plt.plot(tau,corr)
     plt.title(tde_pair[0]+tde_pair[1]+' Shot '+str(shot))
     fig.canvas.mpl_connect('button_press_event', onclick)
     plt.show()    
     plt.ginput(20,timeout=0)
     plt.clf()
     #savedirectory='C:\\Users\\dschaffner\\Dropbox\\Data\\BMPL\\BMX\\2022\\01122022\\QuickPlots\\timeseries\\probepairs\\'+tde_pair[0]+tde_pair[1]+'\\mod\\'
     #savefilename=tde_pair[0]+tde_pair[1]+'_shot_'+str(shot+1).zfill(2)+'mod.png'
     #savefile = savedirectory+savefilename
     #plt.savefig(savefile,dpi=300,facecolor='w',edgecolor='k')
     #plt.clf()
 #use unfiltered
 #d1=data1_norm[start_time_index:end_time_index]
Esempio n. 28
0
Pq = data['P'][:, :, q]  # Projection matrix of view q

F = estimate_fundamental_matrix(Pp, Pq, method='pseudo')

colors = 'bgrcmykw'  # Colors for each point-line pair

fig1, ax1 = plt.subplots(1, 1)
fig1.suptitle('Figure p')
ax1.imshow(Ip, cmap='gray')
ax1.axis('off')

fig2, ax2 = plt.subplots(1,
                         1,
                         subplot_kw=dict(xlim=(0, Ip.shape[1]),
                                         ylim=(Iq.shape[0], 1)))
fig2.suptitle('Figure q')
ax2.imshow(Iq, cmap='gray')
ax2.axis('off')
fig2.show()

for i in range(8):
    plt.figure(fig1.number)  # Focus on fig1 and get the mouse locations
    m = np.hstack([np.array(plt.ginput(1)), np.ones((1, 1))]).T  # Click
    ax1.plot(m[0, 0], m[1, 0],
             f'{colors[i]}*')  # Plot lines and plot on figures
    fig1.canvas.draw()
    ax2 = plot_epipolar_line(F, m, line_color=colors[i], ax=ax2)
    fig2.canvas.draw()

plt.show()
Esempio n. 29
0
def select_outlets(dem,
                   fd,
                   prefix,
                   hs=None,
                   outlet_filename='outlets.p',
                   color='r'):
    if hs is None:
        hs = d.Hillshade(elevation=dem, azimuth=320, inclination=20)

    plot_dem(dem, hs)

    keep_going = True

    while keep_going:
        zoom_ok = False
        print(
            '\nZoom or pan to view, \npress spacebar when ready to select point upstream of outlet:\n'
        )
        while not zoom_ok:
            zoom_ok = plt.waitforbuttonpress()
        print('\nClick on point upstream of outlet.')
        xy = plt.ginput(1)[0]
        xy_path = fd.search_down_flow_direction_from_xy_location(xy)
        plt.plot(xy)
        plt.plot(xy_path)
        xy_path_plot = list(zip(*xy_path))
        path = plt.plot(xy_path_plot[0], xy_path_plot[1], color + '-')
        print('\nClick on the outlet location.')
        xy = plt.ginput(1)[0]

        min_distance = 1E12

        for loc in xy_path:

            if (np.sqrt(
                    np.power(loc[0] - xy[0], 2) + np.power(loc[1] - xy[1], 2))
                    < min_distance) or min_distance == 1E12:
                outlet_loc = loc
                min_distance = np.sqrt(
                    np.power(loc[0] - xy[0], 2) + np.power(loc[1] - xy[1], 2))

        plt.figure(1)
        plt.plot(outlet_loc[0], outlet_loc[1], color + 'o')
        path.pop(0).remove()

        outlet_prefix = raw_input(
            'Type a name for this outlet (leaving this blank will prevent outlet from being saved and will complete the selection process: '
        )

        if outlet_prefix != '':
            import os.path
            if os.path.isfile(outlet_filename):
                outlets = p.load(open(outlet_filename, 'rb'))
            else:
                outlets = dict()

            this_tile = outlets.get(prefix, dict())
            this_tile[outlet_prefix] = outlet_loc

            outlets[prefix] = this_tile

            p.dump(outlets, open(outlet_filename, 'wb'))
        else:
            keep_going = False
Esempio n. 30
0
def find_match_limits(mag1,
                      mag2,
                      comp1=90.,
                      comp2=90.,
                      color_only=False,
                      xlim=None,
                      ylim=None):
    """
    click color limits on a cmd and mag1 mag2 limits on a plot of mag1 vs mag2
    """
    col = mag1 - mag2

    _, ax = plt.subplots()
    ax.plot(col, mag2, 'o', color='k', ms=3, alpha=0.3, mec='none')
    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)
    else:
        ax.set_ylim(ax.get_ylim()[::-1])

    if comp1 < 90.:
        ax.hlines(comp2, *ax.get_xlim())

    okay = 1
    while okay == 1:
        print('click color extrema')
        pts = plt.ginput(2, timeout=-1)
        colmin, colmax = [pts[i][0] for i in range(2)]
        if colmin > colmax:
            colmin, colmax = colmax, colmin
        ax.vlines(colmin, *ax.get_ylim())
        ax.vlines(colmax, *ax.get_ylim())
        plt.draw()
        okay = move_on(0)

    plt.close()

    inds, = np.nonzero((col < colmax) & (col > colmin))
    data = (colmin, colmax)
    if not color_only:
        _, ax = plt.subplots()
        ax.plot(mag1, mag2, '.', color='k')
        okay = 1
        while okay == 1:
            print('click mag extrema')
            pts = plt.ginput(2, timeout=-1)
            mag1max, mag2max = pts[0]
            mag1min, mag2min = pts[1]
            if mag1min > mag1max:
                mag1min, mag1max = mag1max, mag1min
            if mag2min > mag2max:
                mag2min, mag2max = mag2max, mag2min

            ax.plot(mag1max, mag2max, 'o', color='r')
            ax.plot(mag1min, mag2min, 'o', color='r')
            plt.draw()
            okay = move_on(okay)

        plt.close()

        inds, = np.nonzero((mag1 < mag1min) & (mag1 > mag1max)
                           & (mag2 < mag2min) & (mag2 > mag2max)
                           & (col < colmax) & (col > colmin))

    _, ax = plt.subplots()
    ax.plot(col, mag2, '.', color='k')
    ax.plot(col[inds], mag2[inds], '.', color='r')
    ax.set_ylim(ax.get_ylim()[::-1])
    if comp2 < 90.:
        ax.hlines(comp2, *ax.get_xlim(), lw=2)
    ax.vlines(colmin, *ax.get_ylim(), lw=2)
    ax.vlines(colmax, *ax.get_ylim(), lw=2)
    if not color_only:
        ax.hlines(mag2max, *ax.get_xlim(), lw=2)
        data = (colmin, colmax, mag1min, mag1max, mag2min, mag2max)

    plt.draw()

    print(data)
    return data
Esempio n. 31
0

# Do ROI if desired
plt.figure(1)
plt.imshow(Image)
plt.title('Original')
if options.ROI:
    # make the ROI-Coordinates into a double tuple, so we can use less code
    # afterwards
    options.ROI = ((int(options.ROI.split(',')[0]),
                    int(options.ROI.split(',')[1])),
                   (int(options.ROI.split(',')[2]),
                    int(options.ROI.split(',')[3])))
else:
    plt.title('Please select two corners of the ROI. Top left, bottom right')
    options.ROI = plt.ginput(2)
    # swap ROI coordinates if necessary (if user clicked right/left instead of
    # left/right)
    if options.ROI[0][0] > options.ROI[1][0]:
        plt.title('Select top left, then bottom right!')
        options.ROI = plt.ginput(2)
        if options.ROI[0][0] > options.ROI[1][0]:
            plt.title('TOP LEFT, BOTTOM RIGHT!')
            options.ROI = plt.ginput(2)

if options.ROI[0][0] > 0:
    plt.subplot(211)
    plt.imshow(Image)
    plt.title('Original')
    plt.hlines(options.ROI[0][1], options.ROI[0][0], options.ROI[1][0], 'r',
               linewidth=3)