INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Compute p th - order spectral bandwidth:
def spectral_bandwidth(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, centroid=None, norm=True, p=2): '''Compute p'th-order spectral bandwidth: (sum_k S[k] * (freq[k] - centroid)...
Compute spectral contrast [ 1 ] _
def spectral_contrast(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, fmin=200.0, n_bands=6, quantile=0.02, linear=False): '''Compute spectral contrast [1]_ .. [1]...
Compute roll - off frequency.
def spectral_rolloff(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, roll_percent=0.85): '''Compute roll-off frequency. The roll-off frequency is defined for each frame as the center freq...
Compute spectral flatness
def spectral_flatness(y=None, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', amin=1e-10, power=2.0): '''Compute spectral flatness Spectral flatness (or tonality coefficient) is a measure to quantify how much n...
Compute root - mean - square ( RMS ) value for each frame either from the audio samples y or from a spectrogram S.
def rms(y=None, S=None, frame_length=2048, hop_length=512, center=True, pad_mode='reflect'): '''Compute root-mean-square (RMS) value for each frame, either from the audio samples `y` or from a spectrogram `S`. Computing the RMS value from audio samples is faster as it doesn't require a STFT cal...
Get coefficients of fitting an nth - order polynomial to the columns of a spectrogram.
def poly_features(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', order=1, freq=None): '''Get coefficients of fitting an nth-order polynomial to the columns of a spectrogram. Parameters ----------...
Compute the zero - crossing rate of an audio time series.
def zero_crossing_rate(y, frame_length=2048, hop_length=512, center=True, **kwargs): '''Compute the zero-crossing rate of an audio time series. Parameters ---------- y : np.ndarray [shape=(n,)] Audio time series frame_length : int > 0 Length of the frame over...
Compute a chromagram from a waveform or power spectrogram.
def chroma_stft(y=None, sr=22050, S=None, norm=np.inf, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', tuning=None, **kwargs): """Compute a chromagram from a waveform or power spectrogram. This implementation is derived from `chromagr...
r Constant - Q chromagram
def chroma_cqt(y=None, sr=22050, C=None, hop_length=512, fmin=None, norm=np.inf, threshold=0.0, tuning=None, n_chroma=12, n_octaves=7, window=None, bins_per_octave=None, cqt_mode='full'): r'''Constant-Q chromagram Parameters ---------- y : np.ndarray [shape=(n,)] a...
r Computes the chroma variant Chroma Energy Normalized ( CENS ) following [ 1 ] _.
def chroma_cens(y=None, sr=22050, C=None, hop_length=512, fmin=None, tuning=None, n_chroma=12, n_octaves=7, bins_per_octave=None, cqt_mode='full', window=None, norm=2, win_len_smooth=41, smoothing_window='hann'): r'''Computes the chroma variant "Chroma Energy Normaliz...
Computes the tonal centroid features ( tonnetz ) following the method of [ 1 ] _.
def tonnetz(y=None, sr=22050, chroma=None): '''Computes the tonal centroid features (tonnetz), following the method of [1]_. .. [1] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic Change in Musical Audio." In Proceedings of the 1st ACM Workshop on Audio and Music Comp...
Mel - frequency cepstral coefficients ( MFCCs )
def mfcc(y=None, sr=22050, S=None, n_mfcc=20, dct_type=2, norm='ortho', **kwargs): """Mel-frequency cepstral coefficients (MFCCs) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] sampling rate of `y` S : np.ndarray [shape=(d,...
Compute a mel - scaled spectrogram.
def melspectrogram(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', power=2.0, **kwargs): """Compute a mel-scaled spectrogram. If a spectrogram input `S` is provided, then it is mapped directly onto ...
Load an audio file and estimate tuning ( in cents )
def estimate_tuning(input_file): '''Load an audio file and estimate tuning (in cents)''' print('Loading ', input_file) y, sr = librosa.load(input_file) print('Separating harmonic component ... ') y_harm = librosa.effects.harmonic(y) print('Estimating tuning ... ') # Just track the pitches...
Jaccard similarity between two intervals
def __jaccard(int_a, int_b): # pragma: no cover '''Jaccard similarity between two intervals Parameters ---------- int_a, int_b : np.ndarrays, shape=(2,) Returns ------- Jaccard similarity between intervals ''' ends = [int_a[1], int_b[1]] if ends[1] < ends[0]: ends.reve...
Find the best Jaccard match from query to candidates
def __match_interval_overlaps(query, intervals_to, candidates): # pragma: no cover '''Find the best Jaccard match from query to candidates''' best_score = -1 best_idx = -1 for idx in candidates: score = __jaccard(query, intervals_to[idx]) if score > best_score: best_score,...
Numba - accelerated interval matching algorithm.
def __match_intervals(intervals_from, intervals_to, strict=True): # pragma: no cover '''Numba-accelerated interval matching algorithm. ''' # sort index of the interval starts start_index = np.argsort(intervals_to[:, 0]) # sort index of the interval ends end_index = np.argsort(intervals_to[:, ...
Match one set of time intervals to another.
def match_intervals(intervals_from, intervals_to, strict=True): '''Match one set of time intervals to another. This can be useful for tasks such as mapping beat timings to segments. Each element `[a, b]` of `intervals_from` is matched to the element `[c, d]` of `intervals_to` which maximizes the ...
Match one set of events to another.
def match_events(events_from, events_to, left=True, right=True): '''Match one set of events to another. This is useful for tasks such as matching beats to the nearest detected onsets, or frame-aligned events to the nearest zero-crossing. .. note:: A target event may be matched to multiple source event...
Harmonic salience function.
def salience(S, freqs, h_range, weights=None, aggregate=None, filter_peaks=True, fill_value=np.nan, kind='linear', axis=0): """Harmonic salience function. Parameters ---------- S : np.ndarray [shape=(d, n)] input time frequency magnitude representation (stft, ifgram, etc). ...
Compute the energy at harmonics of time - frequency representation.
def interp_harmonics(x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Compute the energy at harmonics of time-frequency representation. Given a frequency-based energy representation such as a spectrogram or tempogram, this function computes the energy at the chosen harmonics of the frequency...
Populate a harmonic tensor from a time - frequency representation.
def harmonics_1d(harmonic_out, x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Populate a harmonic tensor from a time-frequency representation. Parameters ---------- harmonic_out : np.ndarray, shape=(len(h_range), X.shape) The output array to store harmonics X ...
Populate a harmonic tensor from a time - frequency representation with time - varying frequencies.
def harmonics_2d(harmonic_out, x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Populate a harmonic tensor from a time-frequency representation with time-varying frequencies. Parameters ---------- harmonic_out : np.ndarray The output array to store harmonics ...
Load an audio file as a floating point time series.
def load(path, sr=22050, mono=True, offset=0.0, duration=None, dtype=np.float32, res_type='kaiser_best'): """Load an audio file as a floating point time series. Audio will be automatically resampled to the given rate (default `sr=22050`). To preserve the native sampling rate of the file, use ...
Load an audio buffer using audioread.
def __audioread_load(path, offset, duration, dtype): '''Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results. ''' y = [] with audioread.audio_open(path) as input_file: sr_native = input_file.samplerate n_channels = input_file.chann...
Force an audio signal down to mono.
def to_mono(y): '''Force an audio signal down to mono. Parameters ---------- y : np.ndarray [shape=(2,n) or shape=(n,)] audio time series, either stereo or mono Returns ------- y_mono : np.ndarray [shape=(n,)] `y` as a monophonic time-series Notes ----- This fu...
Resample a time series from orig_sr to target_sr
def resample(y, orig_sr, target_sr, res_type='kaiser_best', fix=True, scale=False, **kwargs): """Resample a time series from orig_sr to target_sr Parameters ---------- y : np.ndarray [shape=(n,) or shape=(2, n)] audio time series. Can be mono or stereo. orig_sr : number > 0 [scalar] ...
Compute the duration ( in seconds ) of an audio time series feature matrix or filename.
def get_duration(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, filename=None): """Compute the duration (in seconds) of an audio time series, feature matrix, or filename. Examples -------- >>> # Load the example audio file >>> y, sr = librosa.load(librosa.ut...
Bounded auto - correlation
def autocorrelate(y, max_size=None, axis=-1): """Bounded auto-correlation Parameters ---------- y : np.ndarray array to autocorrelate max_size : int > 0 or None maximum correlation lag. If unspecified, defaults to `y.shape[axis]` (unbounded) axis : int The axi...
Linear Prediction Coefficients via Burg s method
def lpc(y, order): """Linear Prediction Coefficients via Burg's method This function applies Burg's method to estimate coefficients of a linear filter on `y` of order `order`. Burg's method is an extension to the Yule-Walker approach, which are both sometimes referred to as LPC parameter estimatio...
Find the zero - crossings of a signal y: indices i such that sign ( y [ i ] ) ! = sign ( y [ j ] ).
def zero_crossings(y, threshold=1e-10, ref_magnitude=None, pad=True, zero_pos=True, axis=-1): '''Find the zero-crossings of a signal `y`: indices `i` such that `sign(y[i]) != sign(y[j])`. If `y` is multi-dimensional, then zero-crossings are computed along the specified `axis`. ...
Returns a signal with the signal click placed at each specified time
def clicks(times=None, frames=None, sr=22050, hop_length=512, click_freq=1000.0, click_duration=0.1, click=None, length=None): """Returns a signal with the signal `click` placed at each specified time Parameters ---------- times : np.ndarray or None times to place clicks, in seconds ...
Returns a pure tone signal. The signal generated is a cosine wave.
def tone(frequency, sr=22050, length=None, duration=None, phi=None): """Returns a pure tone signal. The signal generated is a cosine wave. Parameters ---------- frequency : float > 0 frequency sr : number > 0 desired sampling rate of the output signal length : int > 0 ...
Returns a chirp signal that goes from frequency fmin to frequency fmax
def chirp(fmin, fmax, sr=22050, length=None, duration=None, linear=False, phi=None): """Returns a chirp signal that goes from frequency `fmin` to frequency `fmax` Parameters ---------- fmin : float > 0 initial frequency fmax : float > 0 final frequency sr : number > 0 ...
Compute the tempogram: local autocorrelation of the onset strength envelope. [ 1 ] _
def tempogram(y=None, sr=22050, onset_envelope=None, hop_length=512, win_length=384, center=True, window='hann', norm=np.inf): '''Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_ .. [1] Grosche, Peter, Meinard Müller, and Frank Kurth. "Cyclic tempogram - A...
Get a sorted list of ( audio ) files in a directory or directory sub - tree.
def find_files(directory, ext=None, recurse=True, case_sensitive=False, limit=None, offset=0): '''Get a sorted list of (audio) files in a directory or directory sub-tree. Examples -------- >>> # Get all audio files in a directory sub-tree >>> files = librosa.util.find_files('~/Music'...
Helper function to get files in a single directory
def __get_files(dir_name, extensions): '''Helper function to get files in a single directory''' # Expand out the directory dir_name = os.path.abspath(os.path.expanduser(dir_name)) myfiles = set() for sub_ext in extensions: globstr = os.path.join(dir_name, '*' + os.path.extsep + sub_ext) ...
Phase - vocoder time stretch demo function.
def stretch_demo(input_file, output_file, speed): '''Phase-vocoder time stretch demo function. :parameters: - input_file : str path to input audio - output_file : str path to save output (wav) - speed : float > 0 speed up by this factor ''' # 1. Load the...
Argparse function to get the program parameters
def process_arguments(args): '''Argparse function to get the program parameters''' parser = argparse.ArgumentParser(description='Time stretching example') parser.add_argument('input_file', action='store', help='path to the input file (wav, mp3, etc)') p...
HPSS demo function.
def hpss_demo(input_file, output_harmonic, output_percussive): '''HPSS demo function. :parameters: - input_file : str path to input audio - output_harmonic : str path to save output harmonic (wav) - output_percussive : str path to save output harmonic (wav) '...
r Dynamic programming beat tracker.
def beat_track(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120.0, tightness=100, trim=True, bpm=None, units='frames'): r'''Dynamic programming beat tracker. Beats are detected in three stages, following the method of [1]_: 1. Measure onset strength ...
Estimate the tempo ( beats per minute )
def tempo(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate=np.mean): """Estimate the tempo (beats per minute) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [sca...
Internal function that tracks beats in an onset strength envelope.
def __beat_tracker(onset_envelope, bpm, fft_res, tightness, trim): """Internal function that tracks beats in an onset strength envelope. Parameters ---------- onset_envelope : np.ndarray [shape=(n,)] onset strength envelope bpm : float [scalar] tempo estimate fft_res : float ...
Maps onset strength function into the range [ 0 1 ]
def __normalize_onsets(onsets): '''Maps onset strength function into the range [0, 1]''' norm = onsets.std(ddof=1) if norm > 0: onsets = onsets / norm return onsets
Construct the local score for an onset envlope and given period
def __beat_local_score(onset_envelope, period): '''Construct the local score for an onset envlope and given period''' window = np.exp(-0.5 * (np.arange(-period, period+1)*32.0/period)**2) return scipy.signal.convolve(__normalize_onsets(onset_envelope), window, ...
Core dynamic program for beat tracking
def __beat_track_dp(localscore, period, tightness): """Core dynamic program for beat tracking""" backlink = np.zeros_like(localscore, dtype=int) cumscore = np.zeros_like(localscore) # Search range for previous beat window = np.arange(-2 * period, -np.round(period / 2) + 1, dtype=int) # Make a...
Get the last beat from the cumulative score array
def __last_beat(cumscore): """Get the last beat from the cumulative score array""" maxes = util.localmax(cumscore) med_score = np.median(cumscore[np.argwhere(maxes)]) # The last of these is the last beat (since score generally increases) return np.argwhere((cumscore * maxes * 2 > med_score)).max()
Final post - processing: throw out spurious leading/ trailing beats
def __trim_beats(localscore, beats, trim): """Final post-processing: throw out spurious leading/trailing beats""" smooth_boe = scipy.signal.convolve(localscore[beats], scipy.signal.hann(5), 'same') if trim: threshold = 0...
Compute a recurrence matrix from a data matrix.
def recurrence_matrix(data, k=None, width=1, metric='euclidean', sym=False, sparse=False, mode='connectivity', bandwidth=None, self=False, axis=-1): '''Compute a recurrence matrix from a data matrix. `rec[i, j]` is non-zero if (`data[:, i]`, `data[:, j]`) are k-n...
Convert a recurrence matrix into a lag matrix.
def recurrence_to_lag(rec, pad=True, axis=-1): '''Convert a recurrence matrix into a lag matrix. `lag[i, j] == rec[i+j, j]` Parameters ---------- rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)] A (binary) recurrence matrix, as returned by `recurrence_matrix` pad : bool ...
Convert a lag matrix into a recurrence matrix.
def lag_to_recurrence(lag, axis=-1): '''Convert a lag matrix into a recurrence matrix. Parameters ---------- lag : np.ndarray or scipy.sparse.spmatrix A lag matrix, as produced by `recurrence_to_lag` axis : int The axis corresponding to the time dimension. The alternate axi...
Filtering in the time - lag domain.
def timelag_filter(function, pad=True, index=0): '''Filtering in the time-lag domain. This is primarily useful for adapting image filters to operate on `recurrence_to_lag` output. Using `timelag_filter` is equivalent to the following sequence of operations: >>> data_tl = librosa.segment.recur...
Sub - divide a segmentation by feature clustering.
def subsegment(data, frames, n_segments=4, axis=-1): '''Sub-divide a segmentation by feature clustering. Given a set of frame boundaries (`frames`), and a data matrix (`data`), each successive interval defined by `frames` is partitioned into `n_segments` by constrained agglomerative clustering. .....
Bottom - up temporal segmentation.
def agglomerative(data, k, clusterer=None, axis=-1): """Bottom-up temporal segmentation. Use a temporally-constrained agglomerative clustering routine to partition `data` into `k` contiguous segments. Parameters ---------- data : np.ndarray data to cluster k : int > 0 [...
Multi - angle path enhancement for self - and cross - similarity matrices.
def path_enhance(R, n, window='hann', max_ratio=2.0, min_ratio=None, n_filters=7, zero_mean=False, clip=True, **kwargs): '''Multi-angle path enhancement for self- and cross-similarity matrices. This function convolves multiple diagonal smoothing filters with a self-similarity (or recurrenc...
Onset detection function
def onset_detect(input_file, output_csv): '''Onset detection function :parameters: - input_file : str Path to input audio file (wav, mp3, m4a, flac, etc.) - output_file : str Path to save onset timestamps as a CSV file ''' # 1. load the wav file and resample to 22.050 ...
Slice a time series into overlapping frames.
def frame(y, frame_length=2048, hop_length=512): '''Slice a time series into overlapping frames. This implementation uses low-level stride manipulation to avoid redundant copies of the time series data. Parameters ---------- y : np.ndarray [shape=(n,)] Time series to frame. Must be one...
Validate whether a variable contains valid mono audio data.
def valid_audio(y, mono=True): '''Validate whether a variable contains valid, mono audio data. Parameters ---------- y : np.ndarray The input data to validate mono : bool Whether or not to force monophonic audio Returns ------- valid : bool True if all tests pass ...
Ensure that an input value is integer - typed. This is primarily useful for ensuring integrable - valued array indices.
def valid_int(x, cast=None): '''Ensure that an input value is integer-typed. This is primarily useful for ensuring integrable-valued array indices. Parameters ---------- x : number A scalar value to be cast to int cast : function [optional] A function to modify `x` before c...
Ensure that an array is a valid representation of time intervals:
def valid_intervals(intervals): '''Ensure that an array is a valid representation of time intervals: - intervals.ndim == 2 - intervals.shape[1] == 2 - intervals[i, 0] <= intervals[i, 1] for all i Parameters ---------- intervals : np.ndarray [shape=(n, 2)] set of time in...
Wrapper for np. pad to automatically center an array prior to padding. This is analogous to str. center ()
def pad_center(data, size, axis=-1, **kwargs): '''Wrapper for np.pad to automatically center an array prior to padding. This is analogous to `str.center()` Examples -------- >>> # Generate a vector >>> data = np.ones(5) >>> librosa.util.pad_center(data, 10, mode='constant') array([ 0., ...
Fix the length an array data to exactly size.
def fix_length(data, size, axis=-1, **kwargs): '''Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad with zeros >>...
Fix a list of frames to lie within [ x_min x_max ]
def fix_frames(frames, x_min=0, x_max=None, pad=True): '''Fix a list of frames to lie within [x_min, x_max] Examples -------- >>> # Generate a list of frame indices >>> frames = np.arange(0, 1000.0, 50) >>> frames array([ 0., 50., 100., 150., 200., 250., 300., 350., 40...
Sort an array along its rows or columns.
def axis_sort(S, axis=-1, index=False, value=None): '''Sort an array along its rows or columns. Examples -------- Visualize NMF output for a spectrogram S >>> # Sort the columns of W by peak frequency bin >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> S = np.abs(librosa.st...
Normalize an array along a chosen axis.
def normalize(S, norm=np.inf, axis=0, threshold=None, fill=None): '''Normalize an array along a chosen axis. Given a norm (described below) and a target axis, the input array is scaled so that `norm(S, axis=axis) == 1` For example, `axis=0` normalizes each column of a 2-d array by aggrega...
Find local maxima in an array x.
def localmax(x, axis=0): """Find local maxima in an array `x`. An element `x[i]` is considered a local maximum if the following conditions are met: - `x[i] > x[i-1]` - `x[i] >= x[i+1]` Note that the first condition is strict, and that the first element `x[0]` will never be considered as a...
Uses a flexible heuristic to pick peaks in a signal.
def peak_pick(x, pre_max, post_max, pre_avg, post_avg, delta, wait): '''Uses a flexible heuristic to pick peaks in a signal. A sample n is selected as an peak if the corresponding x[n] fulfills the following three conditions: 1. `x[n] == max(x[n - pre_max:n + post_max])` 2. `x[n] >= mean(x[n - pre...
Return a row - sparse matrix approximating the input x.
def sparsify_rows(x, quantile=0.01): ''' Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x` Returns --...
Sparse matrix roll
def roll_sparse(x, shift, axis=0): '''Sparse matrix roll This operation is equivalent to ``numpy.roll``, but operates on sparse matrices. Parameters ---------- x : scipy.sparse.spmatrix or np.ndarray The sparse matrix input shift : int The number of positions to roll the speci...
Convert an integer buffer to floating point values. This is primarily useful when loading integer - valued wav data into numpy arrays.
def buf_to_float(x, n_bytes=2, dtype=np.float32): """Convert an integer buffer to floating point values. This is primarily useful when loading integer-valued wav data into numpy arrays. See Also -------- buf_to_float Parameters ---------- x : np.ndarray [dtype=int] The inte...
Generate a slice array from an index array.
def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True): '''Generate a slice array from an index array. Parameters ---------- idx : list-like Array of index boundaries idx_min : None or int idx_max : None or int Minimum and maximum allowed indices step : N...
Synchronous aggregation of a multi - dimensional array between boundaries
def sync(data, idx, aggregate=None, pad=True, axis=-1): """Synchronous aggregation of a multi-dimensional array between boundaries .. note:: In order to ensure total coverage, boundary points may be added to `idx`. If synchronizing a feature matrix against beat tracker output, ensure ...
Robustly compute a softmask operation.
def softmask(X, X_ref, power=1, split_zeros=False): '''Robustly compute a softmask operation. `M = X**power / (X**power + X_ref**power)` Parameters ---------- X : np.ndarray The (non-negative) input array corresponding to the positive mask elements X_ref : np.ndarray The ...
Compute the tiny - value corresponding to an input s data type.
def tiny(x): '''Compute the tiny-value corresponding to an input's data type. This is the smallest "usable" number representable in `x`'s data type (e.g., float32). This is primarily useful for determining a threshold for numerical underflow in division or multiplication operations. Parameter...
Sets all cells of a matrix to a given value if they lie outside a constraint region. In this case the constraint region is the Sakoe - Chiba band which runs with a fixed radius along the main diagonal. When x. shape [ 0 ] ! = x. shape [ 1 ] the radius will be expanded so that x [ - 1 - 1 ] = 1 always.
def fill_off_diagonal(x, radius, value=0): """Sets all cells of a matrix to a given ``value`` if they lie outside a constraint region. In this case, the constraint region is the Sakoe-Chiba band which runs with a fixed ``radius`` along the main diagonal. When ``x.shape[0] != x.shape[1]``, the ra...
Read the frame images from a directory and join them as a video
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): """Read the frame images from a directory and join them as a video ...
Read the next frame.
def read(self): """Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it. Returns: ndarray or None: Return the frame if successful, otherwise None. """ # pos = self._p...
Get frame by index.
def get_frame(self, frame_id): """Get frame by index. Args: frame_id (int): Index of the expected frame, 0-based. Returns: ndarray or None: Return the frame if successful, otherwise None. """ if frame_id < 0 or frame_id >= self._frame_cnt: ra...
Convert a video to frame images
def cvt2frames(self, frame_dir, file_start=0, filename_tmpl='{:06d}.jpg', start=0, max_num=0, show_progress=True): """Convert a video to frame images Args: frame_dir (str): Outp...
Track the progress of tasks execution with a progress bar.
def track_progress(func, tasks, bar_width=50, **kwargs): """Track the progress of tasks execution with a progress bar. Tasks are done with a simple for-loop. Args: func (callable): The function to be applied to each task. tasks (list or tuple[Iterable, int]): A list of tasks or ...
Track the progress of parallel task execution with a progress bar.
def track_parallel_progress(func, tasks, nproc, initializer=None, initargs=None, bar_width=50, chunksize=1, skip_first=False...
Flip an image horizontally or vertically.
def imflip(img, direction='horizontal'): """Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image. """ assert direction in ['horizontal'...
Rotate an image.
def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False): """Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise...
Clip bboxes to fit the image shape.
def bbox_clip(bboxes, img_shape): """Clip bboxes to fit the image shape. Args: bboxes (ndarray): Shape (..., 4*k) img_shape (tuple): (height, width) of the image. Returns: ndarray: Clipped bboxes. """ assert bboxes.shape[-1] % 4 == 0 clipped_bboxes = np.empty_like(bboxe...
Scaling bboxes w. r. t the box center.
def bbox_scaling(bboxes, scale, clip_shape=None): """Scaling bboxes w.r.t the box center. Args: bboxes (ndarray): Shape(..., 4). scale (float): Scaling factor. clip_shape (tuple, optional): If specified, bboxes that exceed the boundary will be clipped according to the given ...
Crop image patches.
def imcrop(img, bboxes, scale=1.0, pad_fill=None): """Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of...
Pad an image to a certain shape.
def impad(img, shape, pad_val=0): """Pad an image to a certain shape. Args: img (ndarray): Image to be padded. shape (tuple): Expected padding shape. pad_val (number or sequence): Values to be filled in padding areas. Returns: ndarray: The padded image. """ if not i...
Pad an image to ensure each edge to be multiple to some number.
def impad_to_multiple(img, divisor, pad_val=0): """Pad an image to ensure each edge to be multiple to some number. Args: img (ndarray): Image to be padded. divisor (int): Padded image edges will be multiple to divisor. pad_val (number or sequence): Same as :func:`impad`. Returns: ...
Rescale a size by a ratio.
def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple): w, h. scale (float): Scaling factor. Returns: tuple[int]: scaled size. """ w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
Resize image to a given size.
def imresize(img, size, return_scale=False, interpolation='bilinear'): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, a...
Resize image to the same size of a given image.
def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'): """Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolat...
Resize image while keeping the aspect ratio.
def imrescale(img, scale, return_scale=False, interpolation='bilinear'): """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float or tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by...
Load data from json/ yaml/ pickle files.
def load(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file for...
Dump data to json/ yaml/ pickle strings or files.
def dump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. ...
Register a handler for some file extensions.
def _register_handler(handler, file_formats): """Register a handler for some file extensions. Args: handler (:obj:`BaseFileHandler`): Handler to be registered. file_formats (str or list[str]): File formats to be handled by this handler. """ if not isinstance(handler, BaseFil...
Get priority value.
def get_priority(priority): """Get priority value. Args: priority (int or str or :obj:`Priority`): Priority. Returns: int: The priority value. """ if isinstance(priority, int): if priority < 0 or priority > 100: raise ValueError('priority must be between 0 and 1...
Quantize an array of ( - inf inf ) to [ 0 levels - 1 ].
def quantize(arr, min_val, max_val, levels, dtype=np.int64): """Quantize an array of (-inf, inf) to [0, levels-1]. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. ...
Dequantize an array.
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): """Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): Th...
Generate argparser from config file automatically ( experimental )
def auto_argparser(description=None): """Generate argparser from config file automatically (experimental) """ partial_parser = ArgumentParser(description=description) partial_parser.add_argument('config', help='config file path') cfg_file = partial_parser.parse_known_args()[0].co...
Puts each data field into a tensor/ DataContainer with outer dimension batch size.
def collate(batch, samples_per_gpu=1): """Puts each data field into a tensor/DataContainer with outer dimension batch size. Extend default_collate to add support for :type:`~mmcv.parallel.DataContainer`. There are 3 cases. 1. cpu_only = True, e.g., meta data 2. cpu_only = False, stack = True, ...