{"cells":[{"metadata":{},"cell_type":"markdown","source":"This Notebook is copied from https://www.kaggle.com/thailssonclementino/melspectrograms-with-librosa\n\nI just translated the text with google translator."},{"metadata":{},"cell_type":"markdown","source":"Esse notebook foi feito para gerar mel-espectrogramas usando a biblioteca librosa.\n\n[English translation]\nThis notebook was made to generate mel spectrograms using the librosa library.\n"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#Importando biblioteca utilizadas.\n#important libraries\nimport librosa as librosa\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport librosa.display\nimport warnings\nimport cv2\nimport timeit\nimport pandas as pd\n\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"A função abaixo recebe um mel-espectrograma gerado pelo librosa e retorna uma array que representa uma imagem. Será usado mais abaixo.\n\n[English translation]The function below receives a mel-spectrogram generated by librosa and returns an array representing an image. It will be used below."},{"metadata":{"trusted":true},"cell_type":"code","source":"def mono_to_color(X: np.ndarray,\n                  mean=None,\n                  std=None,\n                  norm_max=None,\n                  norm_min=None,\n                  eps=1e-6):\n    \"\"\"\n    Code from https://www.kaggle.com/daisukelab/creating-fat2019-preprocessed-data\n    \"\"\"\n    # Stack X as [X,X,X]\n    #X = np.stack([X, X, X], axis=-1)\n\n    # Standardize\n    mean = mean or X.mean()\n    X = X - mean\n    std = std or X.std()\n    Xstd = X / (std + eps)\n    _min, _max = Xstd.min(), Xstd.max()\n    norm_max = norm_max or _max\n    norm_min = norm_min or _min\n    if (_max - _min) > eps:\n        # Normalize to [0, 255]\n        V = Xstd\n        V[V < norm_min] = norm_min\n        V[V > norm_max] = norm_max\n        V = 255 * (V - norm_min) / (norm_max - norm_min)\n        V = V.astype(np.uint8)\n    else:\n        # Just zero\n        V = np.zeros_like(Xstd, dtype=np.uint8)\n    return V","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"O código em baixo é uma maneira mais rápida de carregar os audios com o librosa\n\nThe code below is a faster way to load audios with librosa"},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_clip_sr(path,offset=0,duration=None):\n    clip, sr_native = librosa.core.audio.__audioread_load(path, offset=offset, duration=duration, dtype=np.float32)\n    clip = librosa.to_mono(clip)\n    sr = 22050\n    if sr_native > 0:\n        clip = librosa.resample(clip, sr_native, sr, res_type='kaiser_fast')\n    return clip, sr","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Abaixo estou iterando por todos as linhas presentes no arquivo train.csv e extraindo os mel-espectrogramas e gerando imagens para os 5s iniciais de cada audios pertencente a primeira espécie.\n\nBelow I am iterating through all the lines present in the train.csv file and extracting the mel spectrograms and generating images for the initial 5s of each audios belonging to the first species.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Definindo os caminhos dos audios e abrindo o arquivo csv\n#Defining the audio paths and opening the csv file\nPATH_TRAIN = \"../input/birdsong-recognition/train_audio/\"\ntrain_info = pd.read_csv('../input/birdsong-recognition/train.csv')\n\n#Declarando variavel para contar o tempo\n#Declaring variable to count time\n\nstart = timeit.default_timer()\n\ncnt = 0 \n\n#Iterando pelas linhas do arquivo csv\n#Iterating through the lines of the csv file\n\nfor index, row in train_info.iterrows():\n\n    #Saindo do loop se a espécie não for a primeira(aldfly)\n    #Leaving the loop if the species is not the first (aldfly)\n    \n    ebird_code = row['ebird_code']\n    if(ebird_code != 'aldfly'):\n        break   \n    \n    #Verificando a duração dos audios\n    #Checking the duration of audios\n    duration = row['duration']\n    if(duration < 5):\n        continue\n        \n    #Montando o caminho do audio    \n    #Setting the audio path\n    \n    full_path = PATH_TRAIN + ebird_code +'/' + row['filename']\n    \n    #Carregando os 5s iniciais do aúdio\n    #Loading the initial 5s of the audio\n    y,sr =  get_clip_sr(full_path,0,5);\n    \n    #Transformando em mel-spectrograma\n    #Turning into mel spectrogram\n    \n    S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=310,fmin=160,fmax=10300)\n    S_dB = librosa.power_to_db(S, ref=np.max)\n    \n    #Ajustando imagem\n    #Adjusting image\n    \n    im = mono_to_color(S_dB);\n    im = cv2.resize(im, (224,224))\n    im = cv2.flip(im, 0)\n    \n    #Escrevendo imagem\n    #Writing image\n    cv2.imwrite('{}.png'.format(str(cnt)),im)\n    cnt += 1\n\n#contador final do tempo\n#end time counter\nstop = timeit.default_timer()\n\nprint('Time: ', stop - start) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Exemplo de visualização das imagens geradas.\n\n\nExample of visualization of the generated images."},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.image as mpimg\nimg = mpimg.imread('./0.png')\nimgplot = plt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}