Skip to content

Instantly share code, notes, and snippets.

@dschwertfeger
Created March 19, 2020 05:05
Show Gist options
  • Save dschwertfeger/f9746bc62871c736e47d5ec3ff4230f7 to your computer and use it in GitHub Desktop.
Save dschwertfeger/f9746bc62871c736e47d5ec3ff4230f7 to your computer and use it in GitHub Desktop.
Convert a power-spectrogram to decibel units in TensorFlow
def power_to_db(S, amin=1e-16, top_db=80.0):
"""Convert a power-spectrogram (magnitude squared) to decibel (dB) units.
Computes the scaling ``10 * log10(S / max(S))`` in a numerically
stable way.
Based on:
https://librosa.github.io/librosa/generated/librosa.core.power_to_db.html
"""
def _tf_log10(x):
numerator = tf.math.log(x)
denominator = tf.math.log(tf.constant(10, dtype=numerator.dtype))
return numerator / denominator
# Scale magnitude relative to maximum value in S. Zeros in the output
# correspond to positions where S == ref.
ref = tf.reduce_max(S)
log_spec = 10.0 * _tf_log10(tf.maximum(amin, S))
log_spec -= 10.0 * _tf_log10(tf.maximum(amin, ref))
log_spec = tf.maximum(log_spec, tf.reduce_max(log_spec) - top_db)
return log_spec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment