Beispiel #1
0
            def plot(df,
                     t,
                     kappas,
                     width=map_base.shape[1],
                     height=map_base.shape[0],
                     crop=False,
                     is_gt=False):

                fig, ax = plt.subplots(1,
                                       1,
                                       figsize=np.array(
                                           (width, height)) / float(dpi),
                                       dpi=dpi)

                ax.imshow(map_base, cmap='gray', vmin=0, vmax=255)

                # rgb = list(map(hsv_to_rgb, [(f_star, kappa * 0.5, 0.5) for (f_star, kappa) in zip(df.f_star, minmax_normalization(df.kappa))]))
                rgb = list(
                    map(hsv_to_rgb, [(t, 0.5 + kappa * 0.5, 0.8)
                                     for (t, kappa) in zip(t, kappas)]))
                # print (rgb)
                sc = ax.scatter(
                    df.x, df.y, c=rgb, s=8, marker="x", linewidths=1
                )  # , vmin=0, vmax=1) # , cmap=cmap) # cmap = "hsv") #

                if crop:
                    plt.axis([
                        np.min(df.x) - 100,
                        np.max(df.x) + 100,
                        np.max(df.y) + 100,
                        np.min(df.y) - 100
                    ])
                plt.hsv()
                # sc._A = np.array([])

                # plt.colorbar(sc)
                mappable = plt.cm.ScalarMappable(norm=Normalize(0,
                                                                1,
                                                                clip=False),
                                                 cmap=cmap)
                mappable.set_array([])

                if is_gt:
                    plt.title("Ground Truth: user %02d" % (id))
                else:
                    plt.title("%s: user %02d" % (kernel, id))

                # create an axes on the right side of ax. The width of cax will be 5%
                # of ax and the padding between cax and ax will be fixed at 0.05 inch.
                divider = make_axes_locatable(ax)
                cax = divider.append_axes("right", size="5%", pad=0.05)
                plt.colorbar(mappable, cax=cax)

                manager = plt.get_current_fig_manager()
                manager.window.showMaximized()
Beispiel #2
0
def plot2():

    this_dir = os.path.dirname(os.path.realpath(__file__))
    lena = Image.open(os.path.join(this_dir, 'lena.png'))
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0] / dpi, lena.size[1] / dpi
    fig = pp.figure(figsize=figsize)
    ax = pp.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    pp.imshow(lena, cmap='viridis', origin='lower')
    # Set the current color map to HSV.
    pp.hsv()
    pp.colorbar()
    return fig
Beispiel #3
0
def pca_on_bird():
    bird_image = image.imread(
        "ml_course_material/machine-learning-ex7/ex7/bird_small.png")
    plt.imshow(bird_image)
    plt.show(block=False)

    im_shape = bird_image.shape

    X = bird_image.reshape([im_shape[0] * im_shape[1], 3])

    k = 16

    (centroids,
     closest_centroids) = k_means.k_means(X,
                                          k_means.init_random_centroids(X, k))

    nr_samples = 1000
    rng = np.random.default_rng()
    random_indices = rng.integers(0, X.shape[0], nr_samples)

    colors = []
    X_rand = np.empty((nr_samples, X.shape[1]))
    for i in range(nr_samples):
        colors.append(closest_centroids[random_indices[i]])
        X_rand[i, :] = X[random_indices[i], :]

    plt.hsv()
    fig = plt.figure(3)
    ax = fig.gca(projection='3d')
    ax.scatter(X_rand[:, 0], X_rand[:, 1], X_rand[:, 2], c=colors)
    plt.show(block=False)

    X_norm = feature.FeatureNormalizer(X).normalized_x_m
    while True:
        try:
            (U, S) = pca.pca(X_norm)
            break
        except:
            pass

    Z = pca.project(X, U, 2)
    Z_rand = np.empty((nr_samples, Z.shape[1]))
    for i in range(nr_samples):
        Z_rand[i, :] = Z[random_indices[i], :]

    plt.figure(4)
    plt.scatter(Z_rand[:, 0], Z_rand[:, 1], c=colors)
    plt.show()
Beispiel #4
0
def image_plot():
    from matplotlib import rcParams
    try:
        import Image
    except ImportError:
        raise SystemExit('PIL must be installed to run this example')

    lena = Image.open('lena.png')
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0] / dpi, lena.size[1] / dpi
    pp.figure(figsize=figsize)
    ax = pp.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    pp.imshow(lena, origin='lower')
    # Set the current color map to HSV.
    pp.hsv()
    pp.colorbar()
    return 'An \\texttt{imshow} plot'
def plot2():
    from matplotlib import rcParams
    import matplotlib.pyplot as plt
    from PIL import Image
    import os

    this_dir = os.path.dirname(os.path.realpath(__file__))
    lena = Image.open(os.path.join(this_dir, 'lena.png'))
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0] / dpi, lena.size[1] / dpi
    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    plt.imshow(lena, cmap='viridis', origin='lower')
    # Set the current color map to HSV.
    plt.hsv()
    plt.colorbar()
    return fig
def image_plot():
    from matplotlib import rcParams
    try:
        import Image
    except ImportError:
        raise SystemExit('PIL must be installed to run this example')

    lena = Image.open('lena.png')
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0]/dpi, lena.size[1]/dpi
    pp.figure(figsize=figsize)
    ax = pp.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    pp.imshow(lena, origin='lower')
    # Set the current color map to HSV.
    pp.hsv()
    pp.colorbar()
    return 'An \\texttt{imshow} plot'
def plot_lower():
    from matplotlib import rcParams
    import matplotlib.image as mpimg
    import os

    this_dir = os.path.dirname(os.path.realpath(__file__))
    img = mpimg.imread(os.path.join(this_dir, "lena.png"))

    dpi = rcParams["figure.dpi"]
    figsize = img.shape[0] / dpi, img.shape[1] / dpi

    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    plt.imshow(img, cmap="viridis", origin="lower")
    # Set the current color map to HSV.
    plt.hsv()
    plt.colorbar()
    return fig
Beispiel #8
0
def plot():
    from matplotlib import rcParams
    import matplotlib.image as mpimg
    import os

    this_dir = os.path.dirname(os.path.realpath(__file__))
    img = mpimg.imread(os.path.join(this_dir, "lena.png"))

    dpi = rcParams["figure.dpi"]
    figsize = img.shape[0] / dpi, img.shape[1] / dpi

    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    plt.imshow(img, cmap="viridis", origin="lower")
    # Set the current color map to HSV.
    plt.hsv()
    plt.colorbar()
    return fig
Beispiel #9
0
def plot():
    from matplotlib import rcParams
    from matplotlib import pyplot as pp
    import os
    try:
        from PIL import Image
    except ImportError:
        raise RuntimeError('PIL must be installed to run this example')

    this_dir = os.path.dirname(os.path.realpath(__file__))
    lena = Image.open(os.path.join(this_dir, 'lena.png'))
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0]/dpi, lena.size[1]/dpi
    fig = pp.figure(figsize=figsize)
    ax = pp.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    pp.imshow(lena, origin='lower')
    # Set the current color map to HSV.
    pp.hsv()
    pp.colorbar()
    return fig
Beispiel #10
0
def plot():
    from matplotlib import rcParams
    from matplotlib import pyplot as pp
    import os
    try:
        from PIL import Image
    except ImportError:
        raise RuntimeError('PIL must be installed to run this example')

    this_dir = os.path.dirname(os.path.realpath(__file__))
    lena = Image.open(os.path.join(this_dir, 'lena.png'))
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0] / dpi, lena.size[1] / dpi
    fig = pp.figure(figsize=figsize)
    ax = pp.axes([0, 0, 1, 1], frameon=False)
    ax.set_axis_off()
    pp.imshow(lena, origin='lower')
    # Set the current color map to HSV.
    pp.hsv()
    pp.colorbar()
    return fig
 def plotTSNE(self, ax, tsneData, dataLabels, perplexity, theta=0.5):
     '''
     - plot and fencify
     '''
     lineWidth = 1.2
     tsneData = tsneData.astype('float64')
     tsneEmbedded = tsne(tsneData, perplexity=perplexity, theta=theta)
     plt.hsv()  # color model
     ax.scatter(tsneEmbedded[:, 0],
                tsneEmbedded[:, 1],
                s=45,
                c=dataLabels,
                edgecolors='w',
                linewidth=0.30,
                alpha=0.75)
     ax.spines['top'].set_visible(False)
     ax.spines['right'].set_visible(False)
     ax.spines['bottom'].set_visible(False)
     ax.spines['left'].set_visible(False)
     #ax.yaxis.set_ticks_position('left'); ax.xaxis.set_ticks_position('bottom')
     ax.tick_params(axis='x',
                    which='both',
                    bottom='off',
                    top='off',
                    labelbottom='off')
     ax.tick_params(axis='y',
                    which='both',
                    left='off',
                    right='off',
                    labelleft='off')
     xmin, xmax = ax.get_xlim()
     ax.axvline((xmax - np.abs(xmin)) / 2.0,
                color='black',
                linewidth=lineWidth)
     ymin, ymax = ax.get_ylim()
     ax.axhline((ymax - np.abs(ymin)) / 2.0,
                color='black',
                linewidth=lineWidth)
     plt.tight_layout()
     plt.show()
Beispiel #12
0
def visualize_vertex_field_old(verPred, segPred, keypointIdx=0):

    print('Visualizing Vertex Field.')

    verWeight = segPred.float().cpu().detach()
    verWeight = np.argmax(verWeight, axis=1)
    verWeight = verWeight[None, :, :, :]

    _, _, h, w = verWeight.detach().cpu().numpy().shape
    angle = np.zeros((h, w))
    pred = verPred.detach().cpu().numpy()

    for i in range(h):
        for j in range(w):
            x, y = pred[0, [2 * keypointIdx, 2 * keypointIdx + 1], i, j]
            angle[i, j] = np.arctan2(-y, x)
    angle = angle * verWeight.detach().cpu().numpy()[0, 0, :, :]
    plt.imshow(angle)
    plt.hsv()
    plt.show()

    print(' ')
Beispiel #13
0
def plot_poses(poses, conseq=True, wait=True, arrow_len=1):
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    fig = plt.figure()
    ax = Axes3D(fig)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    if conseq:
        plt.hsv()
        #ax.set_prop_cycle('color', map(lambda c: '%f' % c, np.linspace(.7, 0, len(poses))))
    for i, pose in enumerate(poses):
        if pose is not None:
            q = np.quaternion(*pose[3:])
            lat, lon, _ = q_to_ypr(q)
            v1 = spherical2cartesian(lat, lon, 1)*arrow_len
            v2 = (v1 + normalize_v(np.cross(np.cross(v1, np.array([0, 0, 1])), v1))*0.1*arrow_len)*0.85
            v2 = q_times_v(q, v2)
            ax.plot((pose[0], v1[0], v2[0]), (pose[1], v1[1], v2[1]), (pose[2], v1[2], v2[2]))

    while(wait and not plt.waitforbuttonpress()):
        pass
Beispiel #14
0
def visualize_vertex_field(verPred, mask, keypointIdx=0):
    print('Visualizing Vertex Field.')

    verWeight = mask.float().cpu()
    verWeight = verWeight[None, :, :, :]

    _, _, h, w = verWeight.numpy().shape
    angle = np.zeros((h, w))
    pred = verPred.cpu().numpy()

    # for i in range(h):
    #     for j in range(w):
    #         x,y = pred[0,[2*keypointIdx,2*keypointIdx+1],i,j]
    #         angle[i,j] = np.arctan2(-y,x)
    x, y = verPred.cpu().numpy()[0,
                                 [2 * keypointIdx, 2 * keypointIdx + 1], :, :]
    angle = np.arctan2(-y, x)
    angle = angle * verWeight.numpy()[0, 0, :, :]
    plt.imshow(angle)
    plt.hsv()
    plt.show()

    print(' ')
Beispiel #15
0
            # zu weit draussen, abbrechen und neu starten
            running = False
        elif world[x, y] == 1:
            # Angelagert!
            world[xalt, yalt] = 1
            # Radius anpassen
            R = max(R, center_dist(xalt, yalt) + 5)
            running = False
            attached = True

    return path, R, attached

# Ausgabe
##########################################

pyplot.hsv()
figure = pyplot.figure(figsize=(4,4))
figure.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)

graph = figure.add_subplot(111)

pfad, = graph.plot([],[], "r-")
kreis, = graph.plot([],[], "k:")

# Plot-Routine
##########################################

# Fuer die Farbe
cnt = 0.0

def animate():
def main():
    #  Make sure the matlab AES scripts are in the path
    # #
    #  Create two 128-bit plaintexts (exactly 16 byte)
    pt1 = []
    pt2 = []
    for b1 in bytes('Attack at 12:56!', 'utf-8'):
        pt1 += [b1]
    for b2 in bytes('Attack at 12:57!', 'utf-8'):
        pt2 += [b2]

    plaintext_1 = np.uint8(pt1)
    plaintext_1_1 = np.asmatrix(plaintext_1)
    plaintext_2 = np.uint8(pt2)
    plaintext_2_2 = np.asmatrix(plaintext_2)

    #  how many bits are different between the two?
    res = hamming_weight(np.bitwise_xor(plaintext_1_1, plaintext_2_2))
    print(res)
    # #
    #  Create a key
    key_bytes = []
    for byte in bytes('1234512345123456', 'utf-8'):
        key_bytes += [byte]

    key = np.uint8(key_bytes)
    key = np.asmatrix(key)

    ENCRYPT = 1
    DECRYPT = 0
    # #
    #  Encrypt the two plaintexts
    ciphertext_1 = aes_crypt_8bit(plaintext_1_1, key, ENCRYPT)
    ciphertext_2 = aes_crypt_8bit(plaintext_2_2, key, ENCRYPT)
    #  even though the plaintexts were very similar...
    print(plaintext_1)
    print(plaintext_2)
    #  ... the ciphertexts are very different
    print(ciphertext_1)
    print(ciphertext_2)
    # #
    #  how many bits are different between the two?
    print(hamming_weight(np.bitwise_xor(ciphertext_1, ciphertext_2)))

    # #
    #  Decrypt the two ciphertexts
    decrypted_1 = aes_crypt_8bit(ciphertext_1, key, DECRYPT)
    decrypted_2 = aes_crypt_8bit(ciphertext_2, key, DECRYPT)

    #  Did we get the plaintext again?
    print(plaintext_1)
    print(plaintext_2)
    print(decrypted_1)
    print(decrypted_2)
    print()
    # #
    #  Look at the internals of AES now
    [ciphertext_1, state_1, _,
     leak_1] = aes_crypt_8bit_and_leak(plaintext_1_1, key, ENCRYPT)
    [ciphertext_2, state_2, _,
     leak_2] = aes_crypt_8bit_and_leak(plaintext_2_2, key, ENCRYPT)

    #  Show an image showing the two leaks side by size
    plt.subplot(1, 3, 1)
    # plt.imshow(np.squeeze(leak_1), interpolation='nearest')
    plt.imshow(np.squeeze(state_1), interpolation='nearest')
    plt.hsv()
    plt.subplot(1, 3, 3)
    # plt.imshow(np.squeeze(leak_2), interpolation='nearest')
    plt.imshow(np.squeeze(state_2), interpolation='nearest')
    plt.hsv()
    plt.figure()
    # #
    #  Show the difference in the middle
    plt.subplot(1, 3, 2)
    # plt.imshow(np.squeeze(np.bitwise_xor(leak_1, leak_2)), interpolation='nearest')
    plt.imshow(np.squeeze(np.bitwise_xor(state_1, state_2)),
               interpolation='nearest')
    plt.hsv()
    plt.figure()
    # #
    #  plot the HW of the difference
    plt.subplot(1, 1, 1)
    # plt.bar(hamming_weight(np.bitwise_xor(leak_1, leak_2)))
    plt.bar(range(1, (np.shape(state_1)[0]) + 1),
            hamming_weight(np.bitwise_xor(state_1, state_2)))
    plt.show()
Beispiel #17
0
    from matplotlib import rcParams
    try:
        import Image
    except ImportError, exc:
        raise SystemExit('PIL must be installed to run this example')

    lena = Image.open('lena.png')
    dpi = rcParams['figure.dpi']
    figsize = lena.size[0]/dpi, lena.size[1]/dpi

    pp.figure( figsize=figsize )
    ax = pp.axes([0,0,1,1], frameon=False)
    ax.set_axis_off()
    im = pp.imshow(lena, origin='lower')
    # Set the current color map to HSV.
    pp.hsv()
    pp.colorbar()

    return 'An \\texttt{imshow} plot'
# =============================================================================
def noise():
    from numpy.random import randn

    # Make plot with vertical (default) colorbar
    fig = pp.figure()
    ax = fig.add_subplot(111)

    data = np.clip(randn(250, 250), -1, 1)

    cax = ax.imshow(data, interpolation='nearest')
    ax.set_title('Gaussian noise with vertical colorbar')
Beispiel #18
0
        segPred = segPred.cpu().detach().numpy()
        verPred = verPred.cpu().detach().numpy()

        t2 = time.time()
        thisClassMask = segpred_to_mask(segPred)
        classMask[iClass] = thisClassMask
        thisClassAngles = vertexfield_to_angles(verPred,
                                                thisClassMask,
                                                keypointIdx=iKeypoint)
        classAngles[iClass] = thisClassAngles
        print('Other shit time elapsed: {}'.format(time.time() - t2))

    # Create the seg and ver image
    print('......................')
    t3 = time.time()
    if classIdx is not None:
        segImg = Image.fromarray(classMask[iClass][0, :, :])
        segTargetPath = os.path.join(targetDir, 'seg',
                                     str(iImage).zfill(5) + '.png')
        segImg.save(segTargetPath)
        plt.imshow(classAngles[iClass])
        plt.hsv()
        verTargetPath = os.path.join(targetDir, 'ver',
                                     str(iImage).zfill(5) + '.png')
        plt.savefig(verTargetPath)
        plt.clf()

    print('Saving image time elapsed: {}'.format(time.time() - t3))

    print('Fininshed image {}/{}.'.format(iImage, nImages))
Beispiel #19
0
pfo = np.polyfit(ox, loy, polyorder)
ploy = np.polyval(pfo, ox)

fx, fy = bindata(reslist[1][0], reslist[1][1])
lfy = np.log(fy)
pff = np.polyfit(fx, lfy, polyorder)
plfy = np.polyval(pff, fx)

diffy = loy - lfy
pdiffterm = np.polyfit(ox, diffy, polyorder)
pdiffy = np.polyval(pdiffterm, ox)


plt.figure()
plt.clf()
plt.hsv()

ax1 = plt.axes([0.125,0.1,0.775,0.15])
plt.plot(ox, diffy, 'kx')
plt.plot(ox, pdiffy, 'k-')
aln = plt.axis()
plt.axis([al[0],al[1],aln[2],aln[3]])
plt.annotate('$A_1 = %e$\n$A_0 = %e$'%tuple(-pdiffterm), [0.9*(al[1]-al[0])+aln[0], 0.4*(aln[3]-aln[2])+aln[2]])
plt.ylabel('$\Delta \ln (A)$')
plt.xlabel('Offset (m)')

ax2 = plt.axes([0.125,0.3,0.775,0.6], sharex=ax1)
plt.hexbin(reslist[0][0], reslist[0][2], mincnt=threshcnt)
plt.plot(ox, loy, 'kx')
plt.plot(ox, ploy, 'k-')
plt.annotate('Field', [0.95*al[1], loy.mean()])