text_plain_output_5.png text_plain_output_15.png text_plain_output_9.png text_plain_output_4.png text_plain_output_13.png text_plain_output_14.png text_plain_output_10.png text_plain_output_6.png text_plain_output_3.png text_plain_output_7.png text_plain_output_16.png text_plain_output_8.png text_plain_output_2.png text_plain_output_1.png text_plain_output_11.png text_plain_output_12.png
import cv2

import librosa

import matplotlib.pyplot as plt

import numpy as np

import os

data_dir = '/kaggle/input/audio-mnist/data'
paths = []
labels = []
t = 0
for dirname, _, filenames in os.walk(data_dir):
    if t < 20:
        t += 1
        for filename in filenames:
            if filename[-4:] == '.wav':
                paths += [os.path.join(dirname, filename)]
                labels += [dirname.split('/')[-1]]

for i in range(len(paths)):
    if i % 100 == 0:
        print('i=', i)
    path = paths[i]
    label = path.split('/')[-2]
    file = path.split('/')[-1][0:-4]
    try:
        y, sr = librosa.load(path)
        mel_spectrogram = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)
        log_mel_spectrogram = librosa.power_to_db(mel_spectrogram, ref=np.max)
        img = log_mel_spectrogram
        img = cv2.resize(np.array(img), dsize=(128, 128))
        X = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        X = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
        plt.imshow(X)
        plt.axis('off')
        plt.savefig('./mel/' + label + '_' + file + '.png', bbox_inches='tight', pad_inches=0)
        plt.close
    except:
        print('except', label, file)
        continue