Пример #1
0
def create_mask(dataset, batch_mask, dict_dir):

    mask_exists = [
        extract_ids(f) for f in os.listdir(dict_dir[dataset]['Mask_Path'])
    ]
    global coco

    coco = COCO(dict_dir[dataset]['Ann_Small'])

    image_ids = [
        id_ for id_ in load_ann_ids(dataset, dict_dir)
        if id_ not in mask_exists
    ]

    for img_ in image_ids[0:batch_mask]:

        annotations = annotation_image(img_)
        mask = coco.annToMask(annotations[0])

        for i in range(len(annotations)):
            mask += coco.annToMask(annotations[i])

        mask = mask.reshape((300, 300))
        file_name = str(img_).zfill(12) + str('.jpg')
        print('File created:', file_name)

        mask[mask != 0] = 1

        plt.viridis()
        plt.axis('off')
        plt.imshow(mask)
        plt.savefig(dict_dir[dataset]['Mask_Path'] + file_name,
                    bbox_inches='tight',
                    pad_inches=0)
Пример #2
0
def generate(observation, processing_name, toa_name):
    import matplotlib.pyplot as plt
    plt.viridis()
    if not os.path.exists(join(observation, processing_name)):
        meta = pickle.load(open(join(observation,"meta.pickle"),"rb"))
        spec = processing_specs[processing_name]
        kwargs = spec["generic"].copy()
        k = meta["tel"], meta["band"]
        if k not in spec:
            raise NoSpecError(
                "No processing spec for %s in %s" % (k, processing_name))
        kwargs.update(spec[k])
        pipe.process_observation(observation, processing_name, **kwargs)
    if not os.path.exists(join(observation, processing_name, toa_name)):
        meta = pickle.load(open(join(
            observation,processing_name,"process.pickle"),"rb"))
        spec = toa_specs[toa_name]
        kwargs = spec["generic"].copy()
        k = meta["tel"], meta["band"]
        if k not in spec:
            raise NoSpecError(
                "No TOA spec for %s in %s" % (k, toa_name))
        kwargs.update(spec[k])
        pipe.make_toas(observation, processing_name, toa_name, **kwargs)
	plt.close('all')
Пример #3
0
def plot_cam(geom, geom2d, geom1d, image, image2d, image1d):
    plt.viridis()
    plt.figure(figsize=(12, 3))
    ax = plt.subplot(1, 3, 1)
    CameraDisplay(geom, image=image)
    plt.subplot(1, 3, 2, sharex=ax, sharey=ax)
    CameraDisplay(geom2d, image=image2d)
    plt.subplot(1, 3, 3, sharex=ax, sharey=ax)
    CameraDisplay(geom1d, image=image1d)
Пример #4
0
def plot_zeropoint(pars):
    """ Plot 2d histogram.

    Pars will be a dictionary containing:
        data, figure_id, vmax, title_str, xp,yp, searchrad
    """
    from matplotlib import pyplot as plt

    xp = pars['xp']
    yp = pars['yp']
    searchrad = int(pars['searchrad'] + 0.5)

    plt.figure(num=pars['figure_id'])
    plt.clf()

    if pars['interactive']:
        plt.ion()
    else:
        plt.ioff()

    plt.imshow(pars['data'],
               vmin=0,
               vmax=pars['vmax'],
               interpolation='nearest')
    plt.viridis()
    plt.colorbar()
    plt.title(pars['title_str'])
    plt.plot(xp + searchrad,
             yp + searchrad,
             color='red',
             marker='+',
             markersize=24)
    plt.plot(searchrad, searchrad, color='yellow', marker='+', markersize=120)
    plt.text(searchrad,
             searchrad,
             "Offset=0,0",
             verticalalignment='bottom',
             color='yellow')
    plt.xlabel("Offset in X (pixels)")
    plt.ylabel("Offset in Y (pixels)")
    if pars['interactive']:
        plt.show()

    if pars['plotname']:
        suffix = pars['plotname'][-4:]
        output = pars['plotname']
        if '.' not in suffix:
            output += '.png'
            format = 'png'
        else:
            if suffix[1:] in ['png', 'pdf', 'ps', 'eps', 'svg']:
                format = suffix[1:]
        plt.savefig(output, format=format)
Пример #5
0
def plot_zeropoint(pars):
    """ Plot 2d histogram.

    Pars will be a dictionary containing:
        data, figure_id, vmax, title_str, xp,yp, searchrad
    """
    from matplotlib import pyplot as plt

    xp = pars['xp']
    yp = pars['yp']
    searchrad = int(pars['searchrad'] + 0.5)

    plt.figure(num=pars['figure_id'])
    plt.clf()

    if pars['interactive']:
        plt.ion()
    else:
        plt.ioff()

    plt.imshow(pars['data'], vmin=0, vmax=pars['vmax'],
               interpolation='nearest')
    plt.viridis()
    plt.colorbar()
    plt.title(pars['title_str'])
    plt.plot(xp + searchrad, yp + searchrad, color='red', marker='+',
             markersize=24)
    plt.plot(searchrad, searchrad, color='yellow', marker='+', markersize=120)
    plt.text(searchrad, searchrad, "Offset=0,0", verticalalignment='bottom',
             color='yellow')
    plt.xlabel("Offset in X (pixels)")
    plt.ylabel("Offset in Y (pixels)")
    if pars['interactive']:
        plt.show()

    if pars['plotname']:
        suffix = pars['plotname'][-4:]
        output = pars['plotname']
        if '.' not in suffix:
            output += '.png'
            format = 'png'
        else:
            if suffix[1:] in ['png', 'pdf', 'ps', 'eps', 'svg']:
                format = suffix[1:]
        plt.savefig(output, format=format)
 def bubbles_prmtr_by_prmtr(self, title, second_prmtr):
     self.conf_table = self.conf_table.dropna(
         subset=[second_prmtr, self.name])
     first_prmtr_column = self.confirmed_planets_table_with_prmtr[
         second_prmtr]
     second_prmtr_column = self.confirmed_planets_table_with_prmtr[
         self.name]
     plt.scatter(second_prmtr_column,
                 first_prmtr_column,
                 s=first_prmtr_column * 30,
                 c=first_prmtr_column,
                 alpha=0.5)
     sec_index = columns.index(second_prmtr)
     plt.xlabel('{}'.format(self.rus_name))
     plt.xticks(rotation=75)
     plt.ylabel('{}'.format(rus_columns[sec_index]))
     plt.title('{}'.format(title))
     plt.viridis()
     plt.show()
Пример #7
0
def run_stats(a, e, showplot=True):
    """produce simulation statistics and graphs for (n_trials)"""

    # list of the total steps taken for each tiral
    steps_per_trial = [len(rewards) for _, rewards in a.rewards_dict.iteritems()]

    df_rows = ['steps to dest.', 'deadline']
    df = pd.DataFrame([steps_per_trial, a.deadlines], index=df_rows)
    df = df.T

    dest_reached_before_deadline = str(sum(df['steps to dest.'] < df['deadline']))
    title_str = 'LearningAgent reached dest. before deadline: ' + dest_reached_before_deadline + \
                ' out of ' + str(len(steps_per_trial)) + ' trials'

    # set matplotlib parameters
    rc('axes', linewidth=2)
    rc('font', weight='bold')

    if showplot:
        # fig 1:  plot cumulated rewards
        plt.figure()
        for trial_no, rewards in a.rewards_dict.iteritems():
            cum_rewards = np.cumsum(rewards)
            plt.plot(cum_rewards, label=('trial ' + trial_no), linewidth=2)
            plt.xlabel('Step', fontweight='bold')
            plt.title("Cumulated rewards for separate trials", fontweight='bold')
            plt.legend(loc='lower right')
        plt.viridis()

        # fig 2: steps to dest. vs deadline
        df.plot(kind='bar')
        plt.ylim(0, df.values.max() + 5)
        plt.title(title_str, fontweight='bold')
        plt.xlabel('Trial No.', fontweight='bold')
        plt.ylabel('Steps taken to destination', fontweight='bold')

    # pd.set_option('precision', 1)
    # print(df.describe())
    # print('Hard time limit: %d' % e.hard_time_limit)

    print(title_str)

    return dest_reached_before_deadline
Пример #8
0
def _plot_nut(t, nut):
    if nut is None:
        return
    print('Plotting nut ... ', end='')
    sys.stdout.flush()
    x = nut[:, 0]
    y = nut[:, 1]
    nut = nut[:, 3]
    plt.figure()
    plt.viridis()
    plt.tricontourf(x, y, nut / 15.11e-6, 64)
    plt.gca().set_aspect('equal')
    plt.colorbar(orientation='horizontal')
    plt.xlabel('x, m')
    plt.ylabel('y, m')
    plt.title(r'$\nu_t/\nu,\ t = {}\ s$'.format(t))
    print('Done.')
    sys.stdout.flush()
    plt.savefig('nut.png', bbox_inches='tight', bbox_padding=0.5, dpi=150)
Пример #9
0
def animate(i):
    data = pd.read_csv(filename)

    # print(data)
    grid_data = data.loc[data['topic']=='Inverter/GridWatts']
    pv_data = data.loc[data['topic']=='Inverter/PvWattsTotal']
    load_data = data.loc[data['topic']=='Inverter/LoadWatts']
    battery_data = data.loc[data['topic']=='Inverter/BatteryWatts']
	# print(grid_data[['epochTime', 'value']])

    # x = data['x_value']
    # y1 = data['total_1']
    # y2 = data['total_2']

    plt.viridis()
    plt.cla()
    ax = plt.gca()

    grid_data_x = grid_data['epochTime']

    ax.plot(grid_data_x, grid_data['value'], 'k', label='GridWatts')
    ax.plot(pv_data['epochTime'], pv_data['value'], label='PVWatts')
    ax.plot(load_data['epochTime'], load_data['value'], label='LoadWatts')
    ax.plot(battery_data['epochTime'], battery_data['value'], label='BatteryWatts')

    ax.legend(loc='best')
    plt.tight_layout()
    plt.gcf().autofmt_xdate()

    # plt.gca().xaxis.set_major_locator(mtick.FixedLocator(grid_data_x))
    plt.gca().xaxis.set_major_formatter(
    mtick.FuncFormatter(lambda pos,_: time.strftime("%H:%M:%S",time.localtime(pos)))
    )

    
    ax.text(0.1, 0.1,'Records: %d' % len(pv_data),
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)
    if saveplot == True:
        plt.gcf().set_size_inches(16,9)
        plt.savefig(filename + ".png", dpi=100)
Пример #10
0
def _plot_velocity(t, vel):
    if vel is None:
        return
    print('Plotting velocity ... ', end='')
    sys.stdout.flush()
    x = vel[:, 0]
    y = vel[:, 1]
    Ux = vel[:, 3]
    Uy = vel[:, 4]
    Umag = np.sqrt(Ux * Ux + Uy * Uy)
    plt.figure()
    plt.viridis()
    plt.tricontourf(x, y, Umag, 64)
    plt.gca().set_aspect('equal')
    plt.colorbar(orientation='horizontal')
    plt.xlabel('x, m')
    plt.ylabel('y, m')
    plt.title('Velocity magnitude, t = {} s'.format(t))
    print('Done.')
    sys.stdout.flush()
    plt.savefig('velocity.png', bbox_inches='tight', bbox_padding=0.5, dpi=150)
Пример #11
0
def support(data):
    """
    Plot the support densities for a parcel.
    :param data: support densities for a parcel, as a 3D array
    """
    density = numpy.ma.masked_where(data < 1e-5, data)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    X, Y, Z = numpy.mgrid[:density.shape[0], :density.shape[1], :density.
                          shape[2]]
    img = ax.scatter(X, Y, Z, c=density.ravel(), cmap=plt.viridis())
    fig.colorbar(img)
    plt.show()
Пример #12
0
def excalibur(true, preds, title=None, suptitle=None):
    sns.set_style('darkgrid')
    fig = plt.figure(figsize=(10, 7), dpi=100, facecolor='w', edgecolor='k')
    # o = np.argsort(true.flatten())
    # points = zip(true[o], preds[o])

    # print(1)
    plt.xlim([min(true), max(true)])
    plt.ylim([min(true), max(true)])
    # print(2)

    # plot_true = np.array([true[i] for i in range(len(true)) if min(true) < preds[i] and max(true) > preds[i]])
    # plot_preds = np.array([preds[i] for i in range(len(preds)) if min(true) < preds[i] and max(true) > preds[i]])

    plot_mask = np.logical_and(min(true) < preds, max(true) > preds)
    plot_true = true[plot_mask]
    plot_preds = preds[plot_mask]

    # print(3)
    # print("ABOUT TO POLYFIT")
    z = np.polyfit(plot_true.flatten(), plot_preds.flatten(), 1)
    p = np.poly1d(z)
    plt.plot(plot_true, p(plot_true), "r--")
    # print(4)

    colors = MinMaxScaler().fit_transform(
        np.power(np.abs(true - preds).reshape((len(true), 1)), 0.4)).flatten()
    # print(5)
    plt.scatter(true, preds, s=0.25, c=colors)
    plt.xlabel('True Value')
    plt.ylabel('Predicted Value')
    if suptitle is not None:
        plt.suptitle(suptitle)
    if title is not None:
        plt.title(title)
    plt.viridis()
    plt.show()
Пример #13
0
 def plot_classes(self, three_d=False):
     ''' input 3d plot or 2d plot'''
     x = self.labeld_data[:, 0]
     y = self.labeld_data[:, 1]
     z = self.labeld_data[:, 2]
     labels = self.labeld_data[:, -1]
     if three_d:
         fig = plt.figure(figsize=(10, 8))
         ax = fig.add_subplot(111, projection='3d')
         img = ax.scatter(x, y, z, c=labels, cmap=plt.viridis())
         fig.colorbar(img)
         plt.show()
     else:
         img = plt.figure(figsize=(9, 6))
         plt.scatter(x, y, c=labels, cmap='rainbow')  #plot data
         plt.show()
Пример #14
0
def visualize_data(sp500_df: pd.DataFrame) -> None:
    sp500_df_corr = sp500_df.corr()
    data: np.ndarray = sp500_df_corr.values
    fig: plt.Figure = plt.figure()
    ax: plt.Axes = fig.add_subplot(1, 1, 1)

    heatmap = ax.pcolor(data, cmap=plt.viridis())
    fig.colorbar(heatmap)
    ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
    ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
    ax.invert_yaxis()
    ax.xaxis.tick_top()

    column_labels = sp500_df_corr.columns
    row_labels = sp500_df_corr.index

    ax.set_xticklabels(column_labels)
    ax.set_yticklabels(row_labels)
    plt.xticks(rotation=90)
    heatmap.set_clim(-1, 1)
    plt.tight_layout()
    plt.show()
Пример #15
0

reconstructed_xaxis = []
reconstructed_yaxis = []
reconstructed_change = []

for i in range(195):
    for j in range(121):
        reconstructed_yaxis.append(j)
        reconstructed_xaxis.append(i)
        distance = []
        for k in range(len(data)):
            dist_xy = dist([i, j], [reference_xaxis[k], reference_yaxis[k]])
            distance.append([dist_xy, k])
        distance.sort(key=lambda x: x[0])
        distance_list = distance[:int(userinput)]
        average = 0
        for l in range(len(distance_list)):
            lowest_k = distance_list[l][1]
            average += reference_change[lowest_k]
        average /= int(userinput)
        reconstructed_change.append(average)
#print(reconstructed_yaxis)

#mplot.scatter(reference_xaxis, reference_yaxis, c = reference_change)
mplot.scatter(reconstructed_xaxis, reconstructed_yaxis, c=reconstructed_change)
mplot.viridis()
#mplot.scatter(xaxis, yaxis, c = "Black")
mplot.plot(xaxis, yaxis, c="Black")
mplot.show()
Пример #16
0
    zi2 = RegularGridInterpolator((x, y), z.T, method='nearest')((xi, yi))
    assert np.allclose(zi1, zi2)

    f = lambda x, y: x * y
    mid = lambda x: (x[1:] + x[:-1]) / 2.
    x = np.linspace(0, 2, 10)
    y = np.linspace(0, 2, 15)
    x_, y_ = mid(x), mid(y)
    z = f(*np.meshgrid(x_, y_))

    # Example 2
    xi = np.linspace(0, 2, 40)
    yi = np.linspace(0, 2, 60)
    xi_, yi_ = mid(xi), mid(yi)

    zi1 = EqualGridInterpolator((x_, y_), z.T, order=3)(np.meshgrid(xi_, yi_))
    zi2 = EqualGridInterpolator((x_, y_), z.T)(np.meshgrid(xi_, yi_))
    zi3 = EqualGridInterpolator((x_, y_), z.T, padding='nearest')(np.meshgrid(xi_, yi_))

    plt.figure(figsize=(9, 9))
    plt.viridis()
    plt.subplot(221)
    plt.pcolormesh(x, y, z)
    plt.subplot(222)
    plt.pcolormesh(xi, yi, np.ma.array(zi1, mask=np.isnan(zi1)))
    plt.subplot(223)
    plt.pcolormesh(xi, yi, np.ma.array(zi2, mask=np.isnan(zi2)))
    plt.subplot(224)
    plt.pcolormesh(xi, yi, zi3)
    plt.show()
Пример #17
0
# Separando a label das features
X = df.values[:, :-1]
y = df.values[:, -1]

# Estratificação de dados e divisão de teste e treino
X_train, X_test, y_train, y_test = train_test_split(X,
                                                    y,
                                                    test_size=0.9,
                                                    stratify=y,
                                                    random_state=42)

# Projeção no grafico de 4 dimensões (cor é a 4º Dimensão apresentada)
# -------Execute ao proximas 4 linhas juntas-------#
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
img = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=X[:, 3], cmap=plt.viridis())
fig.colorbar(img)
# -------------------------------------------------#

# MODELO CLASSIFICADOR
# A acuracia vai varias de qual o melhor dependendo da quantidade de vizinhos
# analisada.

#--modelo sem scale
# --kernel serve para classificar com multiclass
model = SVC(random_state=1, kernel='poly')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Acerto sem scale: ", acc * 100, '%')
Пример #18
0
def bayes():
    #se carga el dataset
    dataset = pd.read_csv("Dataset_Bayes.csv")

    #Se imprime la cantidad de usuarios que ganaron y perdieron
    print(dataset.groupby('Gano').size())

    #Imprime grafica de barras  Gano vs Variables
    dataset.drop(['Gano'], axis=1).hist()
    plt.show()

    #se elimina userId, completer son irrelevantes para aplicar el metodo
    dataset_limpio = dataset.drop(['userId', 'completer'], axis=1)
    dataset_limpio.describe()

    # se limpia el dataset de valores NaN, Inf
    dataset_limpio = limpiar_dataset_Para_Bayes(dataset_limpio)

    #se elimna y obtiene la variable Gano con el fin de poder buscar las 5 mejores variables que pueden determinar si Gano o perdio
    a = dataset_limpio.drop(['Gano'], axis=1)
    b = dataset_limpio['Gano']
    best = SelectKBest(k=5)
    a_new = best.fit_transform(a, b)
    a_new.shape
    selected = best.get_support(indices=True)
    print("Mejores 5 variables")
    print(a.columns[selected])

    #Imprime grafica de correlación de pearson con respecto a las 5 mejores variables
    used_features = a.columns[selected]
    colormap = plt.viridis()
    plt.figure(figsize=(12, 12))
    plt.title('Coeficiente de correlación de Pearson', y=1.05, size=15)
    sns.heatmap(dataset_limpio[used_features].astype(float).corr(),
                linewidths=0.1,
                vmax=1.0,
                square=True,
                cmap=colormap,
                linecolor='white',
                annot=True)
    plt.show()

    #se dividen los datos de entrada en 'entrenamiento' y 'pruebas'
    a_entrenamiento, a_pruebas = train_test_split(dataset_limpio,
                                                  test_size=0.2,
                                                  random_state=6)
    b_entrenamiento = a_entrenamiento["Gano"]
    b_pruebas = a_pruebas["Gano"]

    gnb = GaussianNB()
    gnb.fit(a_entrenamiento[used_features].values, b_entrenamiento)
    y_pred = gnb.predict(a_pruebas[used_features])

    print('Precisión en el set de Entrenamiento: {:.2f}'.format(
        gnb.score(a_entrenamiento[used_features], b_entrenamiento)))
    print('Precisión en el set de Pruebas: {:.2f}'.format(
        gnb.score(a_pruebas[used_features], b_pruebas)))

    #cinco mejores variables
    #'SRL', 'Atry to lecture', 'num_events', 'grade', 'cluster'
    #tomamos datos del dataset donde un usuario perdio y gano (0,1) con relacion a las 5 mejores variables
    print(
        gnb.predict([[1.666666667, 0, 2, 5.999999866, 0],
                     [2.041666667, 150, 151, 62.00000048, 1]]))
Пример #19
0
    max_iter=100,  # Quantidade de interações maxima.
    random_state=1,  # Semente randomica.
    n_jobs=2)  # Quantidae de theads.
k_means.fit(X)  #------------------ Treinamento do modelo.
y_pred = k_means.predict(X)  #----- Predição.

# accuracy
acc = accuracy_score(y, y_pred)
print('Acertos: ', acc * 100)

# Visualização
# 01 - Visualizando X e y em 3D
fig = plt.figure()
ax = fig.add_subplot(221, projection='3d')

img = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.viridis())
fig.colorbar(img)

# 02 - Visualizando X e y_pred em 3D
fig = plt.figure()
ax = fig.add_subplot(222, projection='3d')

img = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y_pred, cmap=plt.viridis())
fig.colorbar(img)

# 03 - Visualizando X e y
plt.subplot(221), plt.scatter(X[:, 0], X[:, 1], c=y)
plt.title('01 - X[:,0] e X[:,1] com y')
plt.subplot(222), plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.title('01 - X[:,0] e X[:,1] com y_pred')
Пример #20
0
    def HoughLine(self):
        A = cv2.imread(self.imgpath)
        w = A.shape[0]
        h = A.shape[1]
        plt.figure(figsize=(4, 3), dpi=120, facecolor='white')
        plt.imshow(cv2.cvtColor(A, cv2.COLOR_BGR2RGB))
        plt.show()

        ## Crop image to snooker table boundaries
        hsv = cv2.cvtColor(A, cv2.COLOR_BGR2HSV)
        H = hsv[:, :, 0].astype(np.float)
        # isolate green
        H = np.zeros((w, h))
        H[np.logical_and(hsv[:, :, 0] > 20, hsv[:, :, 0] < 90)] = 1
        plt.imshow(H)
        plt.viridis()
        plt.colorbar()
        plt.show()

        kernel = np.ones((31, 31), np.uint8)
        erosion = cv2.erode(H, kernel, iterations=1)

        plt.imshow(erosion)
        plt.viridis()
        plt.colorbar()
        plt.show()

        dilation = cv2.dilate(erosion, kernel, iterations=1)

        plt.imshow(dilation)
        plt.viridis()
        plt.colorbar()
        plt.show()

        W = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
        Gx = cv2.filter2D(dilation, -1, W, cv2.BORDER_REPLICATE)
        Gy = cv2.filter2D(dilation, -1, W.T, cv2.BORDER_REPLICATE)
        G = np.abs(Gx) + np.abs(Gy)
        G = G.astype('uint8')
        plt.imshow(G)
        plt.show()

        #  Standard Hough Line Transform
        lines = cv2.HoughLines(G, 1, np.pi / 180, 300)

        new_lines = [list(lines[0][0])]
        for [[rho, theta]] in lines:
            insert = True
            for [new_rho, _] in new_lines:
                if abs(new_rho - rho) < 10:
                    insert = False
                    break
            if insert:
                new_lines.append([rho, theta])

        def intersection_pts(l1, l2):
            [rho1, theta1] = l1
            [rho2, theta2] = l2
            A = np.array([[math.cos(theta1),
                           math.sin(theta1)],
                          [math.cos(theta2),
                           math.sin(theta2)]])
            b = np.array([rho1, rho2]).T
            X = np.linalg.solve(A, b)
            return X

        points = []

        # Show results
        plt.imshow(A)
        for i in range(4):
            x = intersection_pts(new_lines[i], new_lines[(i + 1) % 4])
            points.append(list(x))
            plt.plot(x[0], x[1], color='red', marker='o', markersize=12)
        plt.show()

        points = np.array(points, dtype=np.int32)

        mask = np.zeros(A.shape[:2], dtype=np.uint8)
        cv2.fillPoly(mask, pts=[points], color=255)

        plt.imshow(mask)
        plt.show()

        cv2.imwrite('src/WSC_mask.png', mask)
        return np.hstack((points, np.ones((4, 1), dtype=np.int32)))
Пример #21
0
        grid[i], set_MSE = evaluateScenes(sceneSet, weight[i], sceneSetLoss); 
    return weight, grid; 

def saveBadScene(scene, weight):
    gt, formula = loadScene(scene); 
    Dd = denoise_tv_chambolle(formula, weight, multichannel=False)
    vmin, vmax = np.min(gt), np.max(gt); 
    plt.figure(figsize=(14,3)); 
    plt.subplot(131); plt.imshow(formula, interpolation='nearest', vmin=vmin, vmax=vmax); plt.title("Baseline"); plt.colorbar(); plt.axis('off'); 
    plt.subplot(132); plt.imshow(Dd, interpolation='nearest', vmin=vmin, vmax=vmax); plt.title("Total Variation"); plt.colorbar(); plt.axis('off'); 
    plt.subplot(133); plt.imshow(gt, interpolation='nearest', vmin=vmin, vmax=vmax); plt.title("Ground Truth %s"%scene); plt.axis('off'); plt.colorbar(); 
    plt.savefig('%s_TV_bad.png'%scene, bbox_inches='tight')



plt.viridis(); 
allScenes = getAllScenes(); 
valScenes = getScenes("Validation")
testScenes = getScenes("Test")
#valLoss = storeLoss(valScenes)
#testLoss = storeLoss(testScenes)

#weights, grid = totVarApplication(0.1, 0.2, 0.05, valScenes, valLoss); 
saveScene("bathroom_29", 0.15)
#saveBadScene("bathroom_29", 2.4)


#plt.plot(weights, grid, label="Total Variation"); plt.xlabel("TV weight"); plt.ylabel("TV loss"); plt.show(); 

#losses = storeLoss(allScenes) 
# Previous result
Пример #22
0
filename = "laser_tracks.npy"
tracks = np.load(filename)
residuals = np.array([[0], [0], [0]])

for track in tracks:
    res = calc_residual(track)
    residuals = np.append(residuals, res, axis=1)

residuals = np.delete(residuals, 0, 1)

z = residuals[0]
x = residuals[1]
res = residuals[2]
grid_z, grid_x = np.mgrid[0:1057:8, 0:257:8]

grid_z2 = griddata((z, x), res, (grid_z, grid_x), method='nearest')
#print grid_z2.T
print np.max(grid_z2)

v = np.linspace(0, 40, 9)
CS = plt.contourf(grid_z, grid_x, grid_z2, v, cmap=plt.viridis())

plt.colorbar(CS, label="Distrortion [cm]")

plt.scatter(z, x, alpha=.01, s=2)

plt.xlim([0, 1036])
plt.ylim([0, 250])
plt.xlabel("z [cm]")
plt.ylabel("x (drift) [cm]")
plt.show()
Пример #23
0
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import scipy
import scipy.stats as stats
from glob import glob
from pprint import pprint as pp
from synaptogenesis.function_definitions import *
from analysis_functions_definitions import *
from argparser import *
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib as mlib

import warnings
warnings.filterwarnings("ignore", category=UserWarning)

# ensure we use viridis as the default cmap
plt.viridis()

# ensure we use the same rc parameters for all matplotlib outputs
mlib.rcParams.update({'font.size': 24})
mlib.rcParams.update({'errorbar.capsize': 5})
mlib.rcParams.update({'figure.autolayout': True})

root_stats = args.root_stats
root_syn = args.root_syn
fig_folder = args.fig_folder
# check if the figures folder exist
if not os.path.isdir(fig_folder) and not os.path.exists(fig_folder):
    os.mkdir(fig_folder)

paths = []
for file in args.path:
Пример #24
0
import matplotlib.pyplot as plt

fig = plt.figure()
ax2 = fig.add_subplot(111, projection='3d')

x1 = df.ix[0:, 'x1']
x2 = df.ix[0:, 'x2']
x3 = df.ix[0:, 'x3']
y = df.ix[0:, 'y']

if sys.argv[1:] == ['winter']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.winter())
elif sys.argv[1:] == ['cool']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.cool())
elif sys.argv[1:] == ['viridis']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.viridis())
elif sys.argv[1:] == ['plasma']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.plasma())
elif sys.argv[1:] == ['inferno']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.inferno())
elif sys.argv[1:] == ['jet']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.jet())
elif sys.argv[1:] == ['gist_ncar']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.gist_ncar())
elif sys.argv[1:] == ['rainbow']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.nipy_spectral())
else:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.nipy_spectral())

fig.colorbar(p)