示例#1
0
def average(*images):
    """Perform an averaging over the set of images
    count = len(images)
    for image in images:
        cv.addWeighted(average, 1, image, 1/count, 0, average)
    """
    if not len(images):
        return None

    fpath = images[0]
    first = Img(fpath)
    sz = first.size
    sizetup = sz.to_tuple()
    moving_average = cv.CreateImage(sizetup, 32, 1)
    result = cv.CreateImage(sizetup, 8, 1)
    count = 1
    result = first.cv_rep()
    for path in images:
        img = Img(path)
        rep = img.resize(sz)
        cv.RunningAvg(rep, moving_average, 1. / float(count), None)
        count += 1
    cv.ConvertScaleAbs(moving_average, result)
    out = new_name(fpath, 'average')
    cv.SaveImage(out, result)
    sys.stdout.write('%s\n' % out)
    return result
示例#2
0
    def guardar(self, nombre=None, ubicacion=None, extension='jpg'):
        '''Guarda el sonograma en 'ubicacion/nombre.extension'. Si no se le da nombre
        o ubicación, utiliza el del archivo anterior. Notar que nunca reemplazará dicho 
        archivo.'''

        #Chequeo valores y fijo defaults
        extensiones_validas = ('jpg', 'jpeg', 'png')
        if extension.lower() not in extensiones_validas:
            raise ValueError(
                'Extension debe ser una de {}'.format(extensiones_validas))

        u, n = os.path.split(self.nombre)
        ubicacion = ubicacion or u
        nombre = nombre or os.path.splitext(n)[0]

        #Ploteo
        fig, ax = plt.subplots()
        ax.pcolormesh(self.tiempos,
                      self.frecuencias,
                      self.sono,
                      rasterized=True,
                      cmap=plt.get_cmap('Greys'))
        ax.set_ylim(self.lims)
        ax.axis('off')
        fig.subplots_adjust(bottom=0, top=1, left=0,
                            right=1)  #para que no tenga bordes blancos

        #Guardo
        nombre = new_name(
            os.path.join(ubicacion, '.'.join((nombre, extension))))
        fig.savefig(nombre, dpi=100)
        plt.close(fig)

        print('Saved: {}'.format(nombre))
示例#3
0
文件: draw.py 项目: jiapei100/lmb
def draw_rect(img, rect_tup):
    """Draws a rectangle on an image, causes a side effect of  writing it to
    disk
    """
    img.draw(rect_tup)
    name = new_name(img.src)
    img.save(name)
    return name
示例#4
0
 def will_begin(self):
     # utils.mount_device(self.src)
     utils.mount_device(self.destination)
     # self.from_path = self.src['MOUNTPOINT']
     # os.chdir(self.from_path)
     name = utils.new_name()
     self.to_path = os.path.join(self.destination['MOUNTPOINT'],
                                 name + Operation.Operation.EXTENSION)
示例#5
0
def main():
    stations_df = get_stations_df_from_ftp()

    stations_df.rename(
        columns={old: new_name(old)
                 for old in stations_df.columns},
        inplace=True)

    updated = datetime.now()

    stations_df['updated'] = updated

    try:
        stations_df.to_sql('stations', con=engine)
    except ValueError:
        print('Table already exists, skiping!!!')
示例#6
0
def crop(path, shape, x, y, w, h):
    """Crop image with rectangle

    :param path: an image path
    :param shape: some shape type
    :param x: rect x origin
    :param y: rect y origin
    :param w: rect w size
    :param h: rect h size
    """
    shape = (x, y, w, h)
    img = Img(path)
    cropped = img.crop(shape)
    out = new_name(path, 'crop')
    cropped.save(out)
    sys.stdout.write('%s\n' % out)
示例#7
0
cant_sintesis = 1  #cuantos cantos voy a sintetizar
nombre_base = 'zorzal'  #nombre de los sonogramas
path_sono = os.path.join('nuevos', 'sonogramas')
path_audio = os.path.join('nuevos', 'audios')

import numpy as np
from numpy.random import normal

from scipy.io.wavfile import write
from scipy import signal

import matplotlib.pyplot as plt
from utils import new_name

creo_nombre = lambda path, base, formato: new_name(
    os.path.join(path, base + formato))

# --------------------
# Parámetros generales
# --------------------
global estimulo1
global destimulodt1

tiempo_total = 1.94

gamma = 24000
escala = 1.6  #factor de escala para pasar de chingolo a zorzal
uoch, uolb, uolg, rb, rdis = (
    350 / 5.0
) * 1e8, 1e-4, 1 / 20., 5e6, 2.4e5  # 2.4e5 , y con 350/3.0, la frec de la oec en 4000 Hz
fsamp, L = 882000.0, 0.025
示例#8
0
    # Carpeta donde guarda las imagenes de los filtros
    # save_dir = make_dirs_noreplace(os.path.join(
    #         'filtros', os.path.splitext(nombre_modelo)[0]))
    save_dir = os.path.join(carpeta, 'filtros')
    os.makedirs(save_dir)

    # Itero sobre todos los filtros de las capas convolutivas
    for capa_ind, nombre in enumerate(nombres):
        print('Corriendo capa ' + nombre)

        # Cantidad de filtros en esta capa
        cant_filtros = modelo.layers[capa_ind].output_shape[
            3]  #cant de filtros
        # Una grilla donde meto las imagenes de cada filtro
        g = Grid(cant_filtros, fill_with=np.nan, trasponer=True)

        # Proceso los filtros y los meto en la grilla
        for filtro_ind in range(cant_filtros):
            channel_filter = generate_pattern(nombre, filtro_ind, modelo)
            channel_filter = np.squeeze(channel_filter)

            # channel_filter es la imagen en cuestión
            g.insert_image(channel_filter)

        # plt.imshow(g.grid)
        g.show()
        nombre = new_name(
            os.path.join(save_dir, 'filtros_{}.jpg'.format(nombre)))
        plt.savefig(nombre, bbox='tight', dpi=400)
        plt.close()
示例#9
0
    img = input_img_data[0]
    return bitificar8(img, 0.1)


# La capa mirar y el índice del filtro en la capa:
layer, index = 2, 3
nombre = modelo.layers[layer].name
este_filtro = generate_pattern(nombre, index, modelo, iteraciones=100)
este_filtro = np.squeeze(
    este_filtro)  #porque hay dimensiones extra que no me sirven para plotear

#print(este_filtro.shape)

#muestro el filtro
plt.imshow(este_filtro)  #cmap=plt.get_cmap('Greys'))
plt.axis('off')
nombre = new_name(
    os.path.join('filtros', 'un_filtro_capa{}_ind{}.jpg'.format(layer, index)))
plt.savefig(nombre,
            dpi=50,
            facecolor='w',
            edgecolor='w',
            orientation='portrait',
            papertype=None,
            format=None,
            transparent=False,
            bbox_inches=None,
            pad_inches=0.1,
            frameon=None)
#    plt.show()
plt.close()
示例#10
0
BATCH_SIZE = 32

MODO = 'pad'
#MODELO = 'peque' # 'peque','peque_conectada', 'media', 'grande', 'profunda', 'mas_profunda', 'asimetrica'

BASE_DIR = 'nuevos', 'dnn'
train_dir = os.path.join(*BASE_DIR, 'train')
val_dir = os.path.join(*BASE_DIR, 'validate')
test_dir = os.path.join(*BASE_DIR, 'test')
#ori_dir = os.path.join(*BASE_DIR, 'originales')

for MODELO in switcher:
    
    print('\n DOING NOW \t ', MODELO, '\n')
    nombre_guardado = '_'.join(['modelos/aug/aug', MODO, MODELO])
    nombre_guardado = new_name(nombre_guardado)
    os.makedirs(nombre_guardado)
    
    model = switcher[MODELO](im_size)
    
    #%% Compilo y armo generadores
    
    
    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])
    
    # Uso un generator para train y uno para test por si decido usar augmentation
    train_datagen = ImageDataGenerator(rescale=1./255,
                                       width_shift_range=(10, 30), #+/-20px
                                       height_shift_range=50, #+/-25px
示例#11
0
        #actualizo valores
        fil1[0]  = v[1] + back1[-1]
        back1[0] = -0.01 * fil1[-1]
        fil1[1:] = fil1[:-1] #desplazo todo 1 hacia el final
        back1[1:] = back1[:-1] #desplazo todo 1 hacia el final
          
        v4.append(v[4])
    
    
    sonido = np.array(v4) * amplitudes
    sonido *= 1000
    sonido += 20 * normal(0, .007, len(sonido))
    
    f, t, Sxx = signal.spectrogram(sonido,882000,window=('gaussian',20*128),
                                   nperseg=10*1024,noverlap=18*512,scaling='spectrum')
    
    fig, ax = plt.subplots()
    ax.pcolormesh(t,f,np.log10(Sxx),rasterized=True,cmap=plt.get_cmap('Greys'))
    ax.set_ylim(10,10000)
    ax.axis('off')
    fig.subplots_adjust(bottom = 0, top = 1, left = 0, right = 1) #para que no tenga bordes blancos
    
    nombre = new_name(os.path.join(path_sono, nombre_base + '.jpeg'))
    fig.savefig(nombre, dpi=100)
    plt.close()
    
    print('listo {} de {}!'.format(i, cant_sintesis))
    print('\a') #sonido al final de la integración
    
        
示例#12
0
文件: dnn.py 项目: mwappner/Tesis
#capas convolucionales
model = models.Sequential()
model.add(layers.Conv2D(4, (3, 3), activation='relu', input_shape=im_shape))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(8, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(8, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(16, (3, 3), activation='relu'))

#capas densas
model.add(layers.Flatten())
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(cantidades.shape[-1],
                       activation='softmax'))  #multicategoría

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10, batch_size=100)

#%% Testeo
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('test accuracy: ', test_acc)

#%% Guardo modelo
nuevo_nombre = os.path.join('modelos', os.path.splitext(nombre)[0] + '.h6')
nuevo_nombre = new_name(nuevo_nombre)
model.save(nuevo_nombre)
示例#13
0
imagen_nombres = contenidos(ori_dir_bent)
imagenes = 1, 3, 9, 23, 24  #benteveo
carpeta_de_guardado_base = 'ori_bent'  #benteveo
################################

for i in imagenes:
    print('Corriendo', i)
    imagen_nombre = imagen_nombres[i]

    carpeta_de_guardado = '_'.join([
        carpeta_de_guardado_base,
        str(i),
        os.path.basename(imagen_nombre).split('-')[0][:-1]
    ])
    carpeta_de_guardado = new_name(
        os.path.join(modelos[este_modelo], carpeta_de_guardado))
    os.makedirs(carpeta_de_guardado)

    una_imagen = cargar_imagen(imagen_nombre)

    ### Creo un modelo para mirar activaciones ###

    #Este modelo toma como input una imagen y da como output lo que cada capa escupe
    #layer_outputs = [layer.output for layer in modelo.layers[:5]] #cargo las capas convolucionales
    layer_outputs = [
        layer.output for layer in modelo.layers if 'conv' in layer.name
    ]  #cargo las capas convolucionales
    activation_model = models.Model(inputs=modelo.input,
                                    outputs=layer_outputs)  #creo el modelo

    #miro alguna activación
示例#14
0
def main():
    flags = {
        "max_temp_flag": NVARCHAR(1),
        "min_temp_flag": NVARCHAR(1),
        "mean_temp_flag": NVARCHAR(1),
        "heat_deg_days_flag": NVARCHAR(1),
        "cool_deg_days_flag": NVARCHAR(1),
        "total_rain_flag": NVARCHAR(1),
        "total_snow_flag": NVARCHAR(1),
        "total_precip_flag": NVARCHAR(1),
        "snow_on_grnd_flag": NVARCHAR(1),
        "dir_of_max_gust_flag": NVARCHAR(1),
        "spd_of_max_gust_km_h": NVARCHAR(5),
        "spd_of_max_gust_flag": NVARCHAR(1),
    }

    # stations_df = get_stations_df_from_ftp()
    stations_df = get_stations_df_from_db()

    COL_INDEX = 0
    COL_STATION_ID = 1
    COL_FIRST_YEAR = 2
    COL_LAST_YEAR = 3

    stations_df.rename(
        columns={old: new_name(old)
                 for old in stations_df.columns},
        inplace=True)

    updated = datetime.now()
    max_days_before = timedelta(days=15)
    date_limit = updated - max_days_before

    # Get and import the current month. Also the month before(past 15 days)
    # when the current and the past month are different.
    params = sorted(
        set([(updated.year, updated.month),
             (date_limit.year, date_limit.month)]))

    filtered_df = stations_df.query('last_year>={}'.format(date_limit.year))
    # To limit the first five observations for test, uncomment the next line and
    # comment the following one.
    # for row in filtered_df[["station_id","first_year","last_year"]][:5].itertuples():
    for row in filtered_df[["station_id", "first_year",
                            "last_year"]].itertuples():
        for param in params:
            observation_df = get_daily_data(row[COL_STATION_ID],
                                            year=param[0],
                                            month=param[1])

            observation_df.rename(
                columns={old: new_name(old)
                         for old in observation_df.columns},
                inplace=True)

            observation_df['station_id'] = row[COL_STATION_ID]

            observation_df['updated'] = updated

            observation_df.to_sql('observations',
                                  engine,
                                  dtype=flags,
                                  if_exists='append')