Skip to content

Instantly share code, notes, and snippets.

@Dbhardwaj99
Created August 13, 2024 04:30
Show Gist options
  • Save Dbhardwaj99/21a83b259e220fdd672e531526961196 to your computer and use it in GitHub Desktop.
Save Dbhardwaj99/21a83b259e220fdd672e531526961196 to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
import numpy as np
def apply_frequency_mask(spectrogram, num_masks=1, mask_width=10):
"""
Apply frequency masking to the input spectrogram.
Parameters:
spectrogram (numpy array): 2D array representing the audio spectrogram.
num_masks (int): Number of frequency masks to apply.
mask_width (int): Width of the frequency mask.
Returns:
numpy array: Spectrogram with frequency masks applied.
"""
masked_spectrogram = np.copy(spectrogram)
num_frequencies = masked_spectrogram.shape[1]
for _ in range(num_masks):
f_start = np.random.randint(0, num_frequencies - mask_width)
masked_spectrogram[:, f_start:f_start + mask_width] = 0
return masked_spectrogram
def apply_temporal_mask(spectrogram, num_masks=1, mask_duration=10):
"""
Apply temporal masking to the input spectrogram.
Parameters:
spectrogram (numpy array): 2D array representing the audio spectrogram.
num_masks (int): Number of temporal masks to apply.
mask_duration (int): Duration of the temporal mask.
Returns:
numpy array: Spectrogram with temporal masks applied.
"""
masked_spectrogram = np.copy(spectrogram)
num_time_steps = masked_spectrogram.shape[0]
for _ in range(num_masks):
t_start = np.random.randint(0, num_time_steps - mask_duration)
masked_spectrogram[t_start:t_start + mask_duration, :] = 0
return masked_spectrogram
# Example usage
if __name__ == "__main__":
# Generating a random spectrogram for demonstration purposes
spectrogram = np.random.random((100, 80))
# Applying frequency masking
freq_masked_spectrogram = apply_frequency_mask(spectrogram, num_masks=2, mask_width=15)
# Applying temporal masking
temp_masked_spectrogram = apply_temporal_mask(spectrogram, num_masks=2, mask_duration=20)
# Plotting the results
plt.figure(figsize=(10, 6))
plt.subplot(1, 3, 1)
plt.title("Original Spectrogram")
plt.imshow(spectrogram, aspect='auto', origin='lower')
plt.colorbar()
plt.subplot(1, 3, 2)
plt.title("Frequency Masked")
plt.imshow(freq_masked_spectrogram, aspect='auto', origin='lower')
plt.colorbar()
plt.subplot(1, 3, 3)
plt.title("Temporal Masked")
plt.imshow(temp_masked_spectrogram, aspect='auto', origin='lower')
plt.colorbar()
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment