Python 特徴抽出 API
libsonare Python パッケージの特徴抽出のリファレンスです。スペクトログラム、スペクトル、ピッチ、チューニング、定 Q 変換、クロマ、分解、オンセット強度、ラウドネスの各特徴を扱います。Audio と解析関数は Python 解析 API、これらの特徴からの再構成は Python 信号・変換 API にあります。インストール、クイックスタート、その他の API ファミリーは Python API の索引ページを参照してください。
特徴抽出
from libsonare import Audio
audio = Audio.from_file("music.mp3")
# スペクトログラム特徴
stft_result = audio.stft(n_fft=2048, hop_length=512)
mel = audio.mel_spectrogram(n_fft=2048, hop_length=512, n_mels=128)
mfcc = audio.mfcc(n_fft=2048, hop_length=512, n_mels=128, n_mfcc=20)
chroma = audio.chroma(n_fft=2048, hop_length=512)
# スペクトル特徴
centroid = audio.spectral_centroid()
bandwidth = audio.spectral_bandwidth()
rolloff = audio.spectral_rolloff(roll_percent=0.85)
flatness = audio.spectral_flatness()
zcr = audio.zero_crossing_rate()
rms = audio.rms_energy()
# ピッチ検出
pitch_yin = audio.pitch_yin(f0_min_hz=65.0, f0_max_hz=2093.0)
pitch_pyin = audio.pitch_pyin(f0_min_hz=65.0, f0_max_hz=2093.0)
print(f"中央値 F0: {pitch_pyin.median_f0:.1f} Hz")特徴抽出関数
# Compute the short-time Fourier transform.
def stft(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
*,
db: bool = False,
phase: bool = False,
) -> StftResult: ...
# Compute a Mel spectrogram.
def mel_spectrogram(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
fmin_hz: float = 0.0,
fmax_hz: float | None = None,
htk: bool = False,
) -> MelSpectrogramResult: ...
# Return the mel filterbank as a float32 array of shape ``(n_mels, n_fft // 2 + 1)``.
def mel_filterbank(
sample_rate: int,
n_fft: int,
*,
n_mels: int = 128,
fmin_hz: float = 0.0,
fmax_hz: float | None = None,
htk: bool = False,
norm: MelNorm = 'slaney',
) -> np.ndarray: ...
# Return ``n_mels`` float32 frequencies in Hz equally spaced on the mel scale.
def mel_frequencies(
n_mels: int = 128,
fmin: float = 0.0,
fmax: float = 11025.0,
htk: bool = False,
) -> np.ndarray: ...
# Compute Mel-frequency cepstral coefficients.
def mfcc(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_mfcc: int = 20,
fmin: float = 0.0,
fmax: float | None = None,
htk: bool = False,
lifter: float = 0.0,
) -> MfccResult: ...
# Compute STFT chroma features (librosa.feature.chroma_stft).
def chroma(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
) -> ChromaResult: ...
# Compute the spectral centroid per frame.
def spectral_centroid(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Compute the spectral bandwidth per frame.
def spectral_bandwidth(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
p: float = 2.0,
) -> np.ndarray: ...
# Compute the spectral rolloff per frame.
def spectral_rolloff(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
roll_percent: float = 0.85,
) -> np.ndarray: ...
# Compute the spectral flatness per frame.
def spectral_flatness(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Compute spectral contrast (librosa.feature.spectral_contrast).
def spectral_contrast(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
n_bands: int = 6,
fmin: float = 200.0,
quantile: float = 0.02,
) -> np.ndarray: ...
# Fit polynomial coefficients per frame (librosa.feature.poly_features).
def poly_features(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
order: int = 1,
) -> np.ndarray: ...
# Compute the zero-crossing rate per frame.
def zero_crossing_rate(
samples: Sequence[float] | list[float],
sr: int = 22050,
frame_length: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Return zero-crossing sample indices (librosa.zero_crossings).
def zero_crossings(
samples: Sequence[float] | list[float],
threshold: float = 1e-10,
ref_magnitude: bool = False,
pad: bool = True,
zero_pos: bool = True,
) -> np.ndarray: ...
# Compute per-channel min/max waveform buckets from interleaved audio.
def waveform_peaks(
samples: Sequence[float] | list[float],
num_channels: int,
*,
samples_per_bucket: int = 512,
) -> WaveformPeaksReport: ...
# Compute waveform peak buckets for several zoom levels.
def waveform_peak_pyramid(
samples: Sequence[float] | list[float],
num_channels: int,
*,
samples_per_bucket_levels: Sequence[int] = (512, 1024, 2048, 4096),
) -> list[WaveformPeaksReport]: ...
# Compute the RMS energy per frame.
def rms_energy(
samples: Sequence[float] | list[float],
sample_rate: int,
frame_length: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Estimate fundamental frequency using the YIN algorithm.
def pitch_yin(
samples: Sequence[float] | list[float],
sample_rate: int,
frame_length: int = 2048,
hop_length: int = 512,
f0_min_hz: float = 65.0,
f0_max_hz: float = 2093.0,
threshold: float = 0.1,
) -> PitchResult: ...
# Estimate fundamental frequency using the pYIN algorithm.
def pitch_pyin(
samples: Sequence[float] | list[float],
sample_rate: int,
frame_length: int = 2048,
hop_length: int = 512,
f0_min_hz: float = 65.0,
f0_max_hz: float = 2093.0,
threshold: float = 0.1,
fill_na: bool = False,
) -> PitchResult: ...
# Per-octave tuning offset from detected pitches (librosa.pitch_tuning).
def pitch_tuning(
frequencies: Sequence[float] | list[float],
resolution: float = 0.01,
bins_per_octave: int = 12,
) -> float: ...
# Global tuning offset of an audio signal (librosa.estimate_tuning).
def estimate_tuning(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
resolution: float = 0.01,
bins_per_octave: int = 12,
) -> float: ...
# Reference frequency of an A4 raised by ``tuning_cents`` cents.
def tuning_to_reference_hz(tuning_cents: float, a4_hz: float = 440.0) -> float: ...
# Tuning, in cents, of a recording whose A4 sits at ``reference_hz``.
def reference_hz_to_tuning(reference_hz: float, a4_hz: float = 440.0) -> float: ...
# Compute the Constant-Q Transform magnitude.
def cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute the Variable-Q Transform magnitude (``gamma`` controls Q).
def vqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
gamma: float | None = None,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute the hybrid CQT magnitude; arguments as :func:`cqt`.
def hybrid_cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute the pseudo-CQT magnitude approximation; arguments as :func:`cqt`.
def pseudo_cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute bass-focused chroma features.
def bass_chroma(
samples: Sequence[float] | list[float],
sample_rate: int,
hop_length: int = 512,
n_chroma: int = 12,
) -> ChromaResult: ...
# Compute CENS chroma features.
def chroma_cens(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
n_chroma: int = 12,
bins_per_octave: int = 36,
) -> ChromaResult: ...
# Compute a constant-Q chromagram (librosa.feature.chroma_cqt).
def chroma_cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
n_chroma: int = 12,
bins_per_octave: int = 36,
) -> ChromaResult: ...
# Compute NNLS chroma.
def nnls_chroma(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
enable_stft_blend: bool = True,
stft_blend_weight: float = 0.55,
stft_blend_n_fft: int = 4096,
hop_length: int = 512,
) -> np.ndarray: ...
# Non-negative matrix factorisation (librosa.decompose.decompose).
def decompose(
s: Sequence[float] | list[float],
n_features: int,
n_frames: int,
n_components: int,
n_iter: int | None = None,
beta: float = 2.0,
init: NmfInit | None = None,
) -> DecomposeResult: ...
# NMF separation that carries the original phase, so components are listenable.
def decompose_stems(
samples: Sequence[float] | list[float],
sample_rate: int,
n_components: int | None = None,
n_fft: int | None = None,
hop_length: int | None = None,
n_iter: int | None = None,
beta: float | None = None,
init: NmfInit | None = None,
mask_power: float | None = None,
) -> DecomposeStemsResult: ...
# N-channel form of :func:`decompose_stems`: one NMF model, one soft mask.
def decompose_stems_linked(
channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
sample_rate: int,
n_components: int | None = None,
n_fft: int | None = None,
hop_length: int | None = None,
n_iter: int | None = None,
beta: float | None = None,
init: NmfInit | None = None,
mask_power: float | None = None,
) -> DecomposeStemsLinkedResult: ...
# Nearest-neighbour spectrogram filter (librosa.decompose.nn_filter).
def nn_filter(
s: Sequence[float] | list[float],
n_features: int,
n_frames: int,
aggregate: NnFilterAggregate | None = None,
k: int | None = None,
width: int | None = None,
) -> np.ndarray: ...
# Compute multi-band onset strength as a float32 array of shape ``(n_bands, n_frames)``.
def onset_strength_multi(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_bands: int = 3,
) -> np.ndarray: ...
# Compute the onset strength envelope (librosa.onset.onset_strength).
def onset_strength(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
) -> np.ndarray: ...
# Compute integrated/momentary/short-term LUFS and loudness range.
def lufs(samples: Sequence[float] | list[float], sample_rate: int) -> LufsResult: ...
# ITU-R BS.1770-4 multi-channel LUFS over an interleaved buffer.
def lufs_interleaved(
samples: Sequence[float] | list[float],
num_channels: int,
sample_rate: int,
) -> LufsResult: ...
# Momentary and short-term LUFS series for an interleaved multi-channel buffer.
def lufs_series_interleaved(
samples: Sequence[float] | list[float],
num_channels: int,
sample_rate: int,
) -> LufsSeriesResult: ...
# EBU R128 / Tech 3342 Loudness Range (LRA) in LU for a mono buffer.
def ebur128_loudness_range_lu(
samples: Sequence[float] | list[float],
sample_rate: int,
) -> float | None: ...
# Compute the per-block momentary LUFS time series as a float32 array.
def momentary_lufs(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...
# Compute the per-block short-term LUFS time series as a float32 array.
def short_term_lufs(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...| 関数 | 説明 |
|---|---|
stft | 短時間フーリエ変換 |
mel_spectrogram | メルスペクトログラム。fmin_hz/fmax_hz で帯域の端を指定し、htk=True で HTK 方式のメル公式を使います。結果には power と db のマトリクスのほか、適用された n_fft、hop_length、fmin_hz/fmax_hz、htk が含まれます |
mfcc | メル周波数ケプストラム係数(lifter=0.0 でケプストラルリフタリング無効)。結果には計算に使ったメルのパラメータと lifter が含まれます |
chroma | クロマ特徴(ピッチクラス分布) |
spectral_centroid | フレームごとのスペクトル重心 |
spectral_bandwidth | フレームごとのスペクトル帯域幅 |
spectral_rolloff | フレームごとのスペクトルロールオフ |
spectral_flatness | フレームごとのスペクトル平坦度 |
spectral_contrast | スペクトルコントラスト。形状は (n_bands + 1, n_frames) |
poly_features | フレームごとの多項式スペクトル係数 |
zero_crossing_rate | フレームごとのゼロ交差率 |
zero_crossings | 波形がゼロを横切るサンプル位置 |
waveform_peaks | インターリーブされたマルチチャンネル音声(長さは channels の倍数)を波形描画用のチャンネルごとの min/max バケットに縮約。min/max はチャンネルメジャー(channel * bucket_count + bucket) |
waveform_peak_pyramid | ズームレベルごとに 1 つのピークレポート(バケット幅ごとに 1 エントリ) |
rms_energy | フレームごとの RMS エネルギー |
pitch_yin | YIN ピッチ推定。すべてのフレームの f0 は有限で、有声かどうかは voiced_flag が示す |
pitch_pyin | pYIN ピッチ推定。無声音の f0 は fill_na=True でない限り nan |
pitch_tuning | 検出済み周波数からビン単位のチューニングずれを推定 |
estimate_tuning | 音声からチューニングずれを直接推定。値は bins_per_octave の 1 ビンに対する端数(12 のとき解析の単位と一致) |
tuning_to_reference_hz / reference_hz_to_tuning | セント単位のチューニングずれと Hz 単位の基準ピッチを相互に変換します |
cqt | 定Q変換の振幅 |
vqt | 可変Q変換の振幅。gamma=None で自動の帯域幅、0.0 は CQT と等価 |
hybrid_cqt | ハイブリッド CQT の振幅(ビンごとに CQT/擬似 CQT を切り替えて合成) |
pseudo_cqt | 擬似 CQT の近似振幅 |
bass_chroma | 低域寄りのクロマ(低音域のピッチクラス分布) |
chroma_cens | CENS のエネルギー正規化・平滑化クロマ |
chroma_cqt | 定 Q クロマグラム(librosa.feature.chroma_cqt 相当)。features は形状 (n_chroma, n_frames) |
nnls_chroma | 形状 (12, n_frames) の NNLS クロマグラム。hop_length の既定値は 512 |
decompose | 行優先スペクトログラムから NMF 分解係数 (w, h) を返す |
decompose_stems | 元の複素スペクトログラムにマスクを掛ける NMF 分離。各コンポーネントが元音源の位相を保ち、合計すると入力に戻る。既定は n_components=4、n_iter=100、beta=2.0、init='random'、mask_power=1.0 |
decompose_stems_linked | 1 つ以上の同じ長さのチャンネル(最大 64)で共有 NMF 分離を行い、チャンネル間のレベルと位相を保ちます。components[k][c] の平面を返し、既定値は decompose_stems と同じです。1 チャンネルならビット単位で一致します |
nn_filter | 行優先スペクトログラムの近傍フィルター |
onset_strength_multi | 形状 (n_bands, n_frames) のマルチバンドのオンセット強度(n_bands 既定 3) |
onset_strength | オンセット強度エンベロープ(半波整流したメルスペクトログラムのフラックス)。フレームごとに 1 つの float32 値 |
lufs | Integrated/最後の窓の LUFS(Loudness Units relative to Full Scale)、Max-M / Max-S、ラウドネスレンジ(EBU R128) |
lufs_interleaved | インターリーブされたサンプルからチャンネル重み付きマルチチャンネルラウドネスを測定 |
lufs_series_interleaved | インターリーブされたマルチチャンネルのサンプルから、BS.1770-4 に従ってチャンネルを合算したモーメンタリー LUFS とショートターム LUFS の系列を返す |
ebur128_loudness_range_lu | EBU R128 のラウドネスレンジ(LRA、LU 単位) |
momentary_lufs | フレームごとのモーメンタリー LUFS |
short_term_lufs | フレームごとのショートターム LUFS |
主な既定値は、n_fft=2048、hop_length=512、n_mels=128、n_mfcc=20、ピッチ検出の fmin=65.0、fmax=2093.0、threshold=0.1、roll_percent=0.85 です。
CQT/VQT は fmin=32.70319566 Hz(C1)、n_bins=84、bins_per_octave=12 を使います。VQT の既定 gamma=None は ERB 由来の帯域幅を自動選択し、負または有限でない gamma(NaN を含む)は拒否されます。chroma_cqt と chroma_cens の既定は n_chroma=12、bins_per_octave=36 です。hpss(...) は kernel_harmonic=31、kernel_percussive=31、n_fft=2048、hop_length=None(n_fft の 4 分の 1、つまり 512)、hard_mask=False を既定値とします。
追加のエフェクト系ヘルパーとして phase_vocoder と hpss(..., with_residual=True) も利用できます。直接のフェーズボコーダー時間伸縮(speed_ratio が 1 より大きいと速く短くなります)や、残差信号を HpssResult.residual に保持した HPSS が必要な場合に使います。
# Phase-vocoder time-scale modification (STFT -> phase_vocoder -> iSTFT).
def phase_vocoder(
samples: Sequence[float] | list[float],
sample_rate: int,
speed_ratio: float,
n_fft: int = 2048,
hop_length: int | None = None,
) -> np.ndarray: ...NMF の係数と、聴けるステム
decompose が返すのは振幅スペクトログラムの W/H 係数です。これらは位相を持たないため、そこから音声を再構成するには位相推定器が必要で、推定された位相はステムとしては実用に耐えません。decompose_stems は、同じ因子分解からコンポーネントごとのソフトマスクを作り、それを元の複素スペクトログラムへ適用します。したがって各コンポーネントは元音源の位相を保ちます。モデルにエネルギーがあるところではマスクの総和が 1 になり、逆 STFT は線形なので、コンポーネントを合計すると入力に戻ります。
mask_power はソフトマスクの指数です。1(既定)は振幅比、2 は Wiener 型のパワー比で、分離は強くなる代わりに倍音が重なる箇所でアーティファクトが増えます。1 未満は拒否されます。init は既定 'random'、SVD ウォームスタートなら 'nndsvd' です。beta はダイバージェンス(2 = Frobenius、1 = Kullback-Leibler)です。
stems = sonare.decompose_stems(audio.data, audio.sample_rate, n_components=4, mask_power=2.0)
for component in stems.components:
... # いずれも入力と同じ長さの 1 次元 float32 配列
print(stems.w.shape, stems.h.shape, stems.sample_rate)マルチチャンネル入力には decompose_stems_linked(...) を使います。各チャンネルの振幅を平均して 1 つの NMF モデルとソフトマスクを作り、そのマスクを各チャンネルの元の複素スペクトルへ同じまま適用します。チャンネル間のレベル差と位相差が保たれます。同じ長さのチャンネルを 1 つ以上、最大 64 チャンネルまで渡してください。各 components[k] はチャンネルを行にした 2 次元の float32 配列で、components[k][c] が成分 k のチャンネル c です。w と h はチャンネル間で共有され、既定値は decompose_stems と同じです。1 チャンネルなら decompose_stems(...) とビット単位で一致します。
linked = sonare.decompose_stems_linked(
[left_channel, right_channel], sample_rate=sample_rate
)
first_left = linked.components[0][0]
first_right = linked.components[0][1]
print(linked.w.shape, linked.h.shape)n_components、n_fft、hop_length、n_iter を省略すると既定値を使います。hop_length を省略した場合は n_fft から求めます。Python と JavaScript は明示的な 0 を拒否します。
NNDSVD のシードは倍精度で計算されます
これは精度の改善ではなく再現性の確保です。振幅スペクトログラムの末尾側の特異ベクトルは単精度のノイズフロアに埋もれるため、float でシードすると総和の順序に依存し、ターゲットが違えば違うコンポーネントが返ってしまいます。形状、非負性、再構成品質は影響を受けません。decompose と decompose_stems は、同じ入力でも単精度のシードとは異なる係数を返すため、単精度のシードで得た保存済みの係数やステム書き出しとは一致しません。