Skip to content

Instantly share code, notes, and snippets.

@saas-coder
Created February 11, 2023 16:01
Show Gist options
  • Select an option

  • Save saas-coder/5ead8ecf49e258e4b0190af8aa048881 to your computer and use it in GitHub Desktop.

Select an option

Save saas-coder/5ead8ecf49e258e4b0190af8aa048881 to your computer and use it in GitHub Desktop.
import librosa
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
def plot_spectrogram(sound, sr):
S = librosa.feature.melspectrogram(sound, sr=sr)
log_S = librosa.power_to_db(S, ref=np.max)
plt.figure(figsize=(12, 4))
librosa.display.specshow(log_S, sr=sr, x_axis='time', y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.title('Mel-frequency spectrogram')
plt.tight_layout()
plt.show()
def predict_car_idling(sound, sr):
S = librosa.feature.melspectrogram(sound, sr=sr)
S = np.expand_dims(S, axis=-1)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(128, 128, 1)),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(2, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
prediction = model.predict(S)
idling = np.argmax(prediction)
if idling == 0:
return "Car is idling"
else:
return "Car is not idling"
if __name__ == "__main__":
sound, sr = librosa.load("car_sound.wav")
plot_spectrogram(sound, sr)
result = predict_car_idling(sound, sr)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment