code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def draw_clip_range(self, frames, preds, bboxes, draw_range): """Draw a range of frames with the same bboxes and predictions.""" # no predictions to be draw if bboxes is None or len(bboxes) == 0: return frames # draw frames in `draw_range` left_frames = frames[:draw_...
Draw a range of frames with the same bboxes and predictions.
draw_clip_range
python
open-mmlab/mmaction2
demo/webcam_demo_spatiotemporal_det.py
https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py
Apache-2.0
def abbrev(name): """Get the abbreviation of label name: 'take (an object) from (a person)' -> 'take ... from ...' """ while name.find('(') != -1: st, ed = name.find('('), name.find(')') name = name[:st] + '...' + name[ed + 1:] return name
Get the abbreviation of label name: 'take (an object) from (a person)' -> 'take ... from ...'
abbrev
python
open-mmlab/mmaction2
demo/webcam_demo_spatiotemporal_det.py
https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py
Apache-2.0
def parse_version_info(version_str: str): """Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int or str]: The version info, e.g., "1.3.0" is parsed into (1, 3, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 'rc1'). """ versio...
Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int or str]: The version info, e.g., "1.3.0" is parsed into (1, 3, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 'rc1').
parse_version_info
python
open-mmlab/mmaction2
mmaction/version.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/version.py
Apache-2.0
def init_recognizer(config: Union[str, Path, mmengine.Config], checkpoint: Optional[str] = None, device: Union[str, torch.device] = 'cuda:0') -> nn.Module: """Initialize a recognizer from config file. Args: config (str or :obj:`Path` or :obj:`mmengine.Config`): C...
Initialize a recognizer from config file. Args: config (str or :obj:`Path` or :obj:`mmengine.Config`): Config file path, :obj:`Path` or the config object. checkpoint (str, optional): Checkpoint path/url. If set to None, the model will not load any weights. Defaults to None. ...
init_recognizer
python
open-mmlab/mmaction2
mmaction/apis/inference.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inference.py
Apache-2.0
def inference_recognizer(model: nn.Module, video: Union[str, dict], test_pipeline: Optional[Compose] = None ) -> ActionDataSample: """Inference a video with the recognizer. Args: model (nn.Module): The loaded recognizer. ...
Inference a video with the recognizer. Args: model (nn.Module): The loaded recognizer. video (Union[str, dict]): The video file path or the results dictionary (the input of pipeline). test_pipeline (:obj:`Compose`, optional): The test pipeline. If not specified, the ...
inference_recognizer
python
open-mmlab/mmaction2
mmaction/apis/inference.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inference.py
Apache-2.0
def inference_skeleton(model: nn.Module, pose_results: List[dict], img_shape: Tuple[int], test_pipeline: Optional[Compose] = None ) -> ActionDataSample: """Inference a pose results with the skeleton recognizer. Args: ...
Inference a pose results with the skeleton recognizer. Args: model (nn.Module): The loaded recognizer. pose_results (List[dict]): The pose estimation results dictionary (the results of `pose_inference`) img_shape (Tuple[int]): The original image shape used for inference ...
inference_skeleton
python
open-mmlab/mmaction2
mmaction/apis/inference.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inference.py
Apache-2.0
def detection_inference(det_config: Union[str, Path, mmengine.Config, nn.Module], det_checkpoint: str, frame_paths: List[str], det_score_thr: float = 0.9, det_cat_id: int = 0, ...
Detect human boxes given frame paths. Args: det_config (Union[str, :obj:`Path`, :obj:`mmengine.Config`, :obj:`torch.nn.Module`]): Det config file path or Detection model object. It can be a :obj:`Path`, a config object, or a module object. det_checkpoint: Checkpo...
detection_inference
python
open-mmlab/mmaction2
mmaction/apis/inference.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inference.py
Apache-2.0
def pose_inference(pose_config: Union[str, Path, mmengine.Config, nn.Module], pose_checkpoint: str, frame_paths: List[str], det_results: List[np.ndarray], device: Union[str, torch.device] = 'cuda:0') -> tuple: """Perform Top-Down pose estim...
Perform Top-Down pose estimation. Args: pose_config (Union[str, :obj:`Path`, :obj:`mmengine.Config`, :obj:`torch.nn.Module`]): Pose config file path or pose model object. It can be a :obj:`Path`, a config object, or a module object. pose_checkpoint: Checkpoint pa...
pose_inference
python
open-mmlab/mmaction2
mmaction/apis/inference.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inference.py
Apache-2.0
def __call__(self, inputs: InputsType, return_datasamples: bool = False, batch_size: int = 1, return_vis: bool = False, show: bool = False, wait_time: int = 0, draw_pred: bool = True, ...
Call the inferencer. Args: inputs (InputsType): Inputs for the inferencer. return_datasamples (bool): Whether to return results as :obj:`BaseDataElement`. Defaults to False. batch_size (int): Inference batch size. Defaults to 1. show (bool): Wheth...
__call__
python
open-mmlab/mmaction2
mmaction/apis/inferencers/actionrecog_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/actionrecog_inferencer.py
Apache-2.0
def _inputs_to_list(self, inputs: InputsType) -> list: """Preprocess the inputs to a list. The main difference from mmengine version is that we don't list a directory cause input could be a frame folder. Preprocess inputs to a list according to its type: - list or tuple: return...
Preprocess the inputs to a list. The main difference from mmengine version is that we don't list a directory cause input could be a frame folder. Preprocess inputs to a list according to its type: - list or tuple: return inputs - str: return a list containing the string. The st...
_inputs_to_list
python
open-mmlab/mmaction2
mmaction/apis/inferencers/actionrecog_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/actionrecog_inferencer.py
Apache-2.0
def visualize( self, inputs: InputsType, preds: PredType, return_vis: bool = False, show: bool = False, wait_time: int = 0, draw_pred: bool = True, fps: int = 30, out_type: str = 'video', target_resolution: Optional[Tuple[int]] = None, ...
Visualize predictions. Args: inputs (List[Union[str, np.ndarray]]): Inputs for the inferencer. preds (List[Dict]): Predictions of the model. return_vis (bool): Whether to return the visualization result. Defaults to False. show (bool): Whether to ...
visualize
python
open-mmlab/mmaction2
mmaction/apis/inferencers/actionrecog_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/actionrecog_inferencer.py
Apache-2.0
def postprocess( self, preds: PredType, visualization: Optional[List[np.ndarray]] = None, return_datasample: bool = False, print_result: bool = False, pred_out_file: str = '', ) -> Union[ResType, Tuple[ResType, np.ndarray]]: """Process the predictions and visu...
Process the predictions and visualization results from ``forward`` and ``visualize``. This method should be responsible for the following tasks: 1. Convert datasamples into a json-serializable dict if needed. 2. Pack the predictions and visualization results and return them. 3....
postprocess
python
open-mmlab/mmaction2
mmaction/apis/inferencers/actionrecog_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/actionrecog_inferencer.py
Apache-2.0
def pred2dict(self, data_sample: ActionDataSample) -> Dict: """Extract elements necessary to represent a prediction into a dictionary. It's better to contain only basic data elements such as strings and numbers in order to guarantee it's json-serializable. Args: data_sample ...
Extract elements necessary to represent a prediction into a dictionary. It's better to contain only basic data elements such as strings and numbers in order to guarantee it's json-serializable. Args: data_sample (ActionDataSample): The data sample to be converted. Returns: ...
pred2dict
python
open-mmlab/mmaction2
mmaction/apis/inferencers/actionrecog_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/actionrecog_inferencer.py
Apache-2.0
def forward(self, inputs: InputType, batch_size: int, **forward_kwargs) -> PredType: """Forward the inputs to the model. Args: inputs (InputsType): The inputs to be forwarded. batch_size (int): Batch size. Defaults to 1. Returns: Dict: The pr...
Forward the inputs to the model. Args: inputs (InputsType): The inputs to be forwarded. batch_size (int): Batch size. Defaults to 1. Returns: Dict: The prediction results. Possibly with keys "rec".
forward
python
open-mmlab/mmaction2
mmaction/apis/inferencers/mmaction2_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/mmaction2_inferencer.py
Apache-2.0
def visualize(self, inputs: InputsType, preds: PredType, **kwargs) -> List[np.ndarray]: """Visualize predictions. Args: inputs (List[Union[str, np.ndarray]]): Inputs for the inferencer. preds (List[Dict]): Predictions of the model. show (bool): Whet...
Visualize predictions. Args: inputs (List[Union[str, np.ndarray]]): Inputs for the inferencer. preds (List[Dict]): Predictions of the model. show (bool): Whether to display the image in a popup window. Defaults to False. wait_time (float): The int...
visualize
python
open-mmlab/mmaction2
mmaction/apis/inferencers/mmaction2_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/mmaction2_inferencer.py
Apache-2.0
def __call__( self, inputs: InputsType, batch_size: int = 1, **kwargs, ) -> dict: """Call the inferencer. Args: inputs (InputsType): Inputs for the inferencer. It can be a path to image / image directory, or an array, or a list of these. ...
Call the inferencer. Args: inputs (InputsType): Inputs for the inferencer. It can be a path to image / image directory, or an array, or a list of these. return_datasamples (bool): Whether to return results as :obj:`BaseDataElement`. Defaults to False. ...
__call__
python
open-mmlab/mmaction2
mmaction/apis/inferencers/mmaction2_inferencer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/apis/inferencers/mmaction2_inferencer.py
Apache-2.0
def load_data_list(self) -> List[Dict]: """Load annotation file to get audio information.""" check_file_exist(self.ann_file) data_list = [] with open(self.ann_file, 'r') as fin: for line in fin: line_split = line.strip().split() video_info = {}...
Load annotation file to get audio information.
load_data_list
python
open-mmlab/mmaction2
mmaction/datasets/audio_dataset.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/audio_dataset.py
Apache-2.0
def parse_img_record(self, img_records: List[dict]) -> tuple: """Merge image records of the same entity at the same time. Args: img_records (List[dict]): List of img_records (lines in AVA annotations). Returns: Tuple(list): A tuple consists of lists of b...
Merge image records of the same entity at the same time. Args: img_records (List[dict]): List of img_records (lines in AVA annotations). Returns: Tuple(list): A tuple consists of lists of bboxes, action labels and entity_ids.
parse_img_record
python
open-mmlab/mmaction2
mmaction/datasets/ava_dataset.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/ava_dataset.py
Apache-2.0
def load_data_list(self) -> List[Dict]: """Load annotation file to get skeleton information.""" assert self.ann_file.endswith('.pkl') mmengine.exists(self.ann_file) data_list = mmengine.load(self.ann_file) if self.split is not None: split, annos = data_list['split'],...
Load annotation file to get skeleton information.
load_data_list
python
open-mmlab/mmaction2
mmaction/datasets/pose_dataset.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/pose_dataset.py
Apache-2.0
def get_type(transform: Union[dict, Callable]) -> str: """get the type of the transform.""" if isinstance(transform, dict) and 'type' in transform: return transform['type'] elif callable(transform): return transform.__repr__().split('(')[0] else: raise TypeError
get the type of the transform.
get_type
python
open-mmlab/mmaction2
mmaction/datasets/repeat_aug_dataset.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/repeat_aug_dataset.py
Apache-2.0
def prepare_data(self, idx) -> List[dict]: """Get data processed by ``self.pipeline``. Reduce the video loading and decompressing. Args: idx (int): The index of ``data_info``. Returns: List[dict]: A list of length num_repeats. """ transforms = sel...
Get data processed by ``self.pipeline``. Reduce the video loading and decompressing. Args: idx (int): The index of ``data_info``. Returns: List[dict]: A list of length num_repeats.
prepare_data
python
open-mmlab/mmaction2
mmaction/datasets/repeat_aug_dataset.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/repeat_aug_dataset.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`PackActionInputs`. Args: results (dict): The result dict. Returns: dict: The result dict. """ packed_results = dict() if self.collect_keys is not None: p...
The transform function of :class:`PackActionInputs`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/formatting.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/formatting.py
Apache-2.0
def transform(self, results): """Method to pack the input data. Args: results (dict): Result dict from the data pipeline. Returns: dict: - 'inputs' (obj:`torch.Tensor`): The forward data of models. - 'data_samples' (obj:`DetDataSample`): The ann...
Method to pack the input data. Args: results (dict): Result dict from the data pipeline. Returns: dict: - 'inputs' (obj:`torch.Tensor`): The forward data of models. - 'data_samples' (obj:`DetDataSample`): The annotation info of the sampl...
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/formatting.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/formatting.py
Apache-2.0
def transform(self, results): """Performs the Transpose formatting. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ for key in self.keys: results[key] = results[key].transpose(self.order) ...
Performs the Transpose formatting. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/formatting.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/formatting.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`FormatGCNInput`. Args: results (dict): The result dict. Returns: dict: The result dict. """ keypoint = results['keypoint'] if 'keypoint_score' in results: ...
The transform function of :class:`FormatGCNInput`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/formatting.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/formatting.py
Apache-2.0
def transform(self, results): """Convert the label dictionary to 3 tensors: "label", "mask" and "category_mask". Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ if not self.hvu_initialized: ...
Convert the label dictionary to 3 tensors: "label", "mask" and "category_mask". Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def _get_train_clips(self, num_frames: int, ori_clip_len: float) -> np.array: """Get clip offsets in train mode. It will calculate the average interval for selected frames, and randomly shift them within offsets between [0, avg_interval]. If the total number of ...
Get clip offsets in train mode. It will calculate the average interval for selected frames, and randomly shift them within offsets between [0, avg_interval]. If the total number of frames is smaller than clips num or origin frames length, it will return all zero indices. Args: ...
_get_train_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def _get_test_clips(self, num_frames: int, ori_clip_len: float) -> np.array: """Get clip offsets in test mode. If the total number of frames is not enough, it will return all zero indices. Args: num_frames (int): Total number of frame in the video. ...
Get clip offsets in test mode. If the total number of frames is not enough, it will return all zero indices. Args: num_frames (int): Total number of frame in the video. ori_clip_len (float): length of original sample clip. Returns: np.ndarray: Sampl...
_get_test_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def _get_ori_clip_len(self, fps_scale_ratio: float) -> float: """calculate length of clip segment for different strategy. Args: fps_scale_ratio (float): Scale ratio to adjust fps. """ if self.target_fps is not None: # align test sample strategy with `PySlowFast` ...
calculate length of clip segment for different strategy. Args: fps_scale_ratio (float): Scale ratio to adjust fps.
_get_ori_clip_len
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def _get_sample_clips(self, num_frames: int) -> np.ndarray: """To sample an n-frame clip from the video. UniformSample basically divides the video into n segments of equal length and randomly samples one frame from each segment. When the duration of video frames is shorter than the desir...
To sample an n-frame clip from the video. UniformSample basically divides the video into n segments of equal length and randomly samples one frame from each segment. When the duration of video frames is shorter than the desired length of the target clip, this approach will duplicate the ...
_get_sample_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Perform the Uniform Sampling. Args: results (dict): The result dict. Returns: dict: The result dict. """ num_frames = results['total_frames'] inds = self._get_sample_clips(num_frames) start_...
Perform the Uniform Sampling. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def _get_train_clips(self, num_frames: int) -> np.array: """Get clip offsets by dense sample strategy in train mode. It will calculate a sample position and sample interval and set start index 0 when sample_pos == 1 or randomly choose from [0, sample_pos - 1]. Then it will shift the sta...
Get clip offsets by dense sample strategy in train mode. It will calculate a sample position and sample interval and set start index 0 when sample_pos == 1 or randomly choose from [0, sample_pos - 1]. Then it will shift the start index by each base offset. Args: num...
_get_train_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def _get_test_clips(self, num_frames: int) -> np.array: """Get clip offsets by dense sample strategy in test mode. It will calculate a sample position and sample interval and evenly sample several start indexes as start positions between [0, sample_position-1]. Then it will shift each s...
Get clip offsets by dense sample strategy in test mode. It will calculate a sample position and sample interval and evenly sample several start indexes as start positions between [0, sample_position-1]. Then it will shift each start index by the base offsets. Args: ...
_get_test_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the PyAV initialization. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ try: import av except ImportError: raise ImportError('P...
Perform the PyAV initialization. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the PyAV decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ container = results['video_reader'] imgs = list() if self.multi_thread: ...
Perform the PyAV decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the PIMS initialization. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ try: import pims except ImportError: raise ImportError(...
Perform the PIMS initialization. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the PIMS decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ container = results['video_reader'] if results['frame_inds'].ndim != 1: ...
Perform the PIMS decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the PyAV motion vector decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ container = results['video_reader'] imgs = list() if self.mult...
Perform the PyAV motion vector decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Perform the Decord initialization. Args: results (dict): The result dict. Returns: dict: The result dict. """ container = self._get_video_reader(results['filename']) results['total_frames'] = len(con...
Perform the Decord initialization. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Perform the Decord decoding. Args: results (dict): The result dict. Returns: dict: The result dict. """ container = results['video_reader'] if results['frame_inds'].ndim != 1: results['f...
Perform the Decord decoding. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: dict) -> dict: """Perform the OpenCV initialization. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ if self.io_backend == 'disk': new_path = results['filename'...
Perform the OpenCV initialization. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: dict) -> dict: """Perform the OpenCV decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ container = results['video_reader'] imgs = list() if results...
Perform the OpenCV decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: dict) -> dict: """Perform the ``RawFrameDecode`` to pick frames given indices. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ mmcv.use_backend(self.decoding_backend) ...
Perform the ``RawFrameDecode`` to pick frames given indices. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the ``ImageDecode`` to load image given the file path. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ mmcv.use_backend(self.decoding_backend) filename...
Perform the ``ImageDecode`` to load image given the file path. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Perform the numpy loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ if osp.exists(results['audio_path']): feature_map = np.load(results...
Perform the numpy loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the building of pseudo clips. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ # the input should be one single image assert len(results['imgs']) == 1 ...
Perform the building of pseudo clips. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Perform the ``AudioFeatureSelector`` to pick audio feature clips. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ audio = results['audios'] frame_...
Perform the ``AudioFeatureSelector`` to pick audio feature clips. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the LoadLocalizationFeature loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ data_path = results['feature_path'] raw_feature = np.loadtxt( ...
Perform the LoadLocalizationFeature loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the GenerateLocalizationLabels loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ video_frame = results['duration_frame'] video_second = results['...
Perform the GenerateLocalizationLabels loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results): """Perform the LoadProposals loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ video_name = results['video_name'] proposal_path = osp.join(self.pgm_proposal...
Perform the LoadProposals loading. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/loading.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/loading.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Perform the pose decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ required_keys = ['total_frames', 'frame_inds', 'keypoint'] for k in req...
Perform the pose decoding. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def generate_a_heatmap(self, arr: np.ndarray, centers: np.ndarray, max_values: np.ndarray) -> None: """Generate pseudo heatmap for one keypoint in one frame. Args: arr (np.ndarray): The array to store the generated heatmaps. Shape: img_h * img_w. ...
Generate pseudo heatmap for one keypoint in one frame. Args: arr (np.ndarray): The array to store the generated heatmaps. Shape: img_h * img_w. centers (np.ndarray): The coordinates of corresponding keypoints (of multiple persons). Shape: M * 2. ...
generate_a_heatmap
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def generate_a_limb_heatmap(self, arr: np.ndarray, starts: np.ndarray, ends: np.ndarray, start_values: np.ndarray, end_values: np.ndarray) -> None: """Generate pseudo heatmap for one limb in one frame. Args: arr (np.ndarray): T...
Generate pseudo heatmap for one limb in one frame. Args: arr (np.ndarray): The array to store the generated heatmaps. Shape: img_h * img_w. starts (np.ndarray): The coordinates of one keypoint in the corresponding limbs. Shape: M * 2. ends (np...
generate_a_limb_heatmap
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def generate_heatmap(self, arr: np.ndarray, kps: np.ndarray, max_values: np.ndarray) -> None: """Generate pseudo heatmap for all keypoints and limbs in one frame (if needed). Args: arr (np.ndarray): The array to store the generated heatmaps. ...
Generate pseudo heatmap for all keypoints and limbs in one frame (if needed). Args: arr (np.ndarray): The array to store the generated heatmaps. Shape: V * img_h * img_w. kps (np.ndarray): The coordinates of keypoints in this frame. Shape: M * V *...
generate_heatmap
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def gen_an_aug(self, results: Dict) -> np.ndarray: """Generate pseudo heatmaps for all frames. Args: results (dict): The dictionary that contains all info of a sample. Returns: np.ndarray: The generated pseudo heatmaps. """ all_kps = results['keypoint']...
Generate pseudo heatmaps for all frames. Args: results (dict): The dictionary that contains all info of a sample. Returns: np.ndarray: The generated pseudo heatmaps.
gen_an_aug
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Generate pseudo heatmaps based on joint coordinates and confidence. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ heatmap = self.gen_an_aug(results) ...
Generate pseudo heatmaps based on joint coordinates and confidence. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """Convert the coordinates of keypoints to make it more compact. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ img_shape = results['img_shape'] h, ...
Convert the coordinates of keypoints to make it more compact. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def angle_between(self, v1: np.ndarray, v2: np.ndarray) -> float: """Returns the angle in radians between vectors 'v1' and 'v2'.""" if np.abs(v1).sum() < 1e-6 or np.abs(v2).sum() < 1e-6: return 0 v1_u = self.unit_vector(v1) v2_u = self.unit_vector(v2) return np.arccos...
Returns the angle in radians between vectors 'v1' and 'v2'.
angle_between
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def rotation_matrix(self, axis: np.ndarray, theta: float) -> np.ndarray: """Returns the rotation matrix associated with counterclockwise rotation about the given axis by theta radians.""" if np.abs(axis).sum() < 1e-6 or np.abs(theta) < 1e-6: return np.eye(3) axis = np.asarray...
Returns the rotation matrix associated with counterclockwise rotation about the given axis by theta radians.
rotation_matrix
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`PreNormalize3D`. Args: results (dict): The result dict. Returns: dict: The result dict. """ skeleton = results['keypoint'] total_frames = results.get('total_frames',...
The transform function of :class:`PreNormalize3D`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`PreNormalize2D`. Args: results (dict): The result dict. Returns: dict: The result dict. """ h, w = results.get('img_shape', self.img_shape) results['keypoint'][..., ...
The transform function of :class:`PreNormalize2D`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`JointToBone`. Args: results (dict): The result dict. Returns: dict: The result dict. """ keypoint = results['keypoint'] M, T, V, C = keypoint.shape bone = np...
The transform function of :class:`JointToBone`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`ToMotion`. Args: results (dict): The result dict. Returns: dict: The result dict. """ data = results[self.source] M, T, V, C = data.shape motion = np.zeros_l...
The transform function of :class:`ToMotion`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`MergeSkeFeat`. Args: results (dict): The result dict. Returns: dict: The result dict. """ feats = [] for name in self.feat_list: feats.append(results.pop...
The transform function of :class:`MergeSkeFeat`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`GenSkeFeat`. Args: results (dict): The result dict. Returns: dict: The result dict. """ if 'keypoint_score' in results and 'keypoint' in results: assert self.dat...
The transform function of :class:`GenSkeFeat`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def _get_train_clips(self, num_frames: int, clip_len: int) -> np.ndarray: """Uniformly sample indices for training clips. Args: num_frames (int): The number of frames. clip_len (int): The length of the clip. Returns: np.ndarray: The sampled indices for train...
Uniformly sample indices for training clips. Args: num_frames (int): The number of frames. clip_len (int): The length of the clip. Returns: np.ndarray: The sampled indices for training clips.
_get_train_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def _get_test_clips(self, num_frames: int, clip_len: int) -> np.ndarray: """Uniformly sample indices for testing clips. Args: num_frames (int): The number of frames. clip_len (int): The length of the clip. Returns: np.ndarray: The sampled indices for testing...
Uniformly sample indices for testing clips. Args: num_frames (int): The number of frames. clip_len (int): The length of the clip. Returns: np.ndarray: The sampled indices for testing clips.
_get_test_clips
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`UniformSampleFrames`. Args: results (dict): The result dict. Returns: dict: The result dict. """ num_frames = results['total_frames'] if self.test_mode: ...
The transform function of :class:`UniformSampleFrames`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`PadTo`. Args: results (dict): The result dict. Returns: dict: The result dict. """ total_frames = results['total_frames'] assert total_frames <= self.length ...
The transform function of :class:`PadTo`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def _load_kpscore(kpscore: np.ndarray, frame_inds: np.ndarray) -> np.ndarray: """Load keypoint scores according to sampled indexes.""" return kpscore[:, frame_inds].astype(np.float32)
Load keypoint scores according to sampled indexes.
_load_kpscore
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`PoseDecode`. Args: results (dict): The result dict. Returns: dict: The result dict. """ if 'total_frames' not in results: results['total_frames'] = results['keyp...
The transform function of :class:`PoseDecode`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`MMUniformSampleFrames`. Args: results (dict): The result dict. Returns: dict: The result dict. """ num_frames = results['total_frames'] modalities = [] for m...
The transform function of :class:`MMUniformSampleFrames`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`MMDecode`. Args: results (dict): The result dict. Returns: dict: The result dict. """ for mod in results['modality']: if results[f'{mod}_inds'].ndim != 1: ...
The transform function of :class:`MMDecode`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def _get_box(self, keypoint: np.ndarray, img_shape: Tuple[int]) -> Tuple: """Calculate the bounding box surrounding all joints in the frames.""" h, w = img_shape kp_x = keypoint[..., 0] kp_y = keypoint[..., 1] min_x = np.min(kp_x[kp_x != 0], initial=np.Inf) min_y = np.m...
Calculate the bounding box surrounding all joints in the frames.
_get_box
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def _compact_images(self, imgs: List[np.ndarray], img_shape: Tuple[int], box: Tuple[int]) -> List: """Crop the images acoordding the bounding box.""" h, w = img_shape min_x, min_y, max_x, max_y = box pad_l, pad_u, pad_r, pad_d = 0, 0, 0, 0 if min_x < 0: ...
Crop the images acoordding the bounding box.
_compact_images
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`MMCompact`. Args: results (dict): The result dict. Returns: dict: The result dict. """ img_shape = results['img_shape'] kp = results['keypoint'] # Make NaN z...
The transform function of :class:`MMCompact`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/pose_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py
Apache-2.0
def transform(self, results): """Fuse lazy operations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ if 'lazy' not in results: raise ValueError('No lazy operation detected') lazyo...
Fuse lazy operations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/processing.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py
Apache-2.0
def transform(self, results): """Perform ColorJitter. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ imgs = results['imgs'] num_clips, clip_len = 1, len(imgs) new_imgs = [] fo...
Perform ColorJitter. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/processing.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py
Apache-2.0
def transform(self, results: Dict) -> Dict: """The transform function of :class:`CLIPTokenize`. Args: results (dict): The result dict. Returns: dict: The result dict. """ try: import clip except ImportError: raise ImportE...
The transform function of :class:`CLIPTokenize`. Args: results (dict): The result dict. Returns: dict: The result dict.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/text_transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/text_transforms.py
Apache-2.0
def transform(self, results): """Perform Torchvision augmentations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ assert 'imgs' in results imgs = [x.transpose(2, 0, 1) for x in results['imgs...
Perform Torchvision augmentations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/wrappers.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py
Apache-2.0
def transform(self, results): """Perform PytorchVideoTrans augmentations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ assert 'imgs' in results assert 'gt_bboxes' not in results,\ ...
Perform PytorchVideoTrans augmentations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/wrappers.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py
Apache-2.0
def default_transforms(): """Default transforms for imgaug. Implement RandAugment by imgaug. Please visit `https://arxiv.org/abs/1909.13719` for more information. Augmenters and hyper parameters are borrowed from the following repo: https://github.com/tensorflow/tpu/blob/master...
Default transforms for imgaug. Implement RandAugment by imgaug. Please visit `https://arxiv.org/abs/1909.13719` for more information. Augmenters and hyper parameters are borrowed from the following repo: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaug...
default_transforms
python
open-mmlab/mmaction2
mmaction/datasets/transforms/wrappers.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py
Apache-2.0
def imgaug_builder(self, cfg): """Import a module from imgaug. It follows the logic of :func:`build_from_cfg`. Use a dict object to create an iaa.Augmenter object. Args: cfg (dict): Config dict. It should at least contain the key "type". Returns: obj:`i...
Import a module from imgaug. It follows the logic of :func:`build_from_cfg`. Use a dict object to create an iaa.Augmenter object. Args: cfg (dict): Config dict. It should at least contain the key "type". Returns: obj:`iaa.Augmenter`: The constructed imgaug augm...
imgaug_builder
python
open-mmlab/mmaction2
mmaction/datasets/transforms/wrappers.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py
Apache-2.0
def transform(self, results): """Perform Imgaug augmentations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ assert results['modality'] == 'RGB', 'Imgaug only support RGB images.' in_type = r...
Perform Imgaug augmentations. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
transform
python
open-mmlab/mmaction2
mmaction/datasets/transforms/wrappers.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py
Apache-2.0
def _draw_samples(self, batch_idx: int, data_batch: dict, data_samples: Sequence[ActionDataSample], step: int = 0) -> None: """Visualize every ``self.interval`` samples from a data batch. Args: batch_idx...
Visualize every ``self.interval`` samples from a data batch. Args: batch_idx (int): The index of the current batch in the val loop. data_batch (dict): Data from dataloader. outputs (Sequence[:obj:`ActionDataSample`]): Outputs from model. step (int): Global step v...
_draw_samples
python
open-mmlab/mmaction2
mmaction/engine/hooks/visualization_hook.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/hooks/visualization_hook.py
Apache-2.0
def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict, outputs: Sequence[ActionDataSample]) -> None: """Visualize every ``self.interval`` samples during validation. Args: runner (:obj:`Runner`): The runner of the validation process. bat...
Visualize every ``self.interval`` samples during validation. Args: runner (:obj:`Runner`): The runner of the validation process. batch_idx (int): The index of the current batch in the val loop. data_batch (dict): Data from dataloader. outputs (Sequence[:obj:`Acti...
after_val_iter
python
open-mmlab/mmaction2
mmaction/engine/hooks/visualization_hook.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/hooks/visualization_hook.py
Apache-2.0
def conv_branch_init(conv: nn.Module, branches: int) -> None: """Perform initialization for a conv branch. Args: conv (nn.Module): The conv module of a branch. branches (int): The number of branches. """ weight = conv.weight n = weight.size(0) k1 = weight.size(1) k2 = weigh...
Perform initialization for a conv branch. Args: conv (nn.Module): The conv module of a branch. branches (int): The number of branches.
conv_branch_init
python
open-mmlab/mmaction2
mmaction/engine/model/weight_init.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/model/weight_init.py
Apache-2.0
def add_params(self, params: List[dict], module: nn.Module, prefix: str = 'base', **kwargs) -> None: """Add all parameters of module to the params list. The parameters of the given module will be added to the list of param ...
Add all parameters of module to the params list. The parameters of the given module will be added to the list of param groups, with specific rules defined by paramwise_cfg. Args: params (list[dict]): A list of param groups, it will be modified in place. ...
add_params
python
open-mmlab/mmaction2
mmaction/engine/optimizers/swin_optim_wrapper_constructor.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/swin_optim_wrapper_constructor.py
Apache-2.0
def add_params(self, params, model, **kwargs): """Add parameters and their corresponding lr and wd to the params. Args: params (list): The list to be modified, containing all parameter groups and their corresponding lr and wd configurations. model (nn.Module): Th...
Add parameters and their corresponding lr and wd to the params. Args: params (list): The list to be modified, containing all parameter groups and their corresponding lr and wd configurations. model (nn.Module): The model to be trained with the optimizer.
add_params
python
open-mmlab/mmaction2
mmaction/engine/optimizers/tsm_optim_wrapper_constructor.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/tsm_optim_wrapper_constructor.py
Apache-2.0
def confusion_matrix(y_pred, y_real, normalize=None): """Compute confusion matrix. Args: y_pred (list[int] | np.ndarray[int]): Prediction labels. y_real (list[int] | np.ndarray[int]): Ground truth labels. normalize (str | None): Normalizes confusion matrix over the true (row...
Compute confusion matrix. Args: y_pred (list[int] | np.ndarray[int]): Prediction labels. y_real (list[int] | np.ndarray[int]): Ground truth labels. normalize (str | None): Normalizes confusion matrix over the true (rows), predicted (columns) conditions or all the population. ...
confusion_matrix
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def mean_class_accuracy(scores, labels): """Calculate mean class accuracy. Args: scores (list[np.ndarray]): Prediction scores for each class. labels (list[int]): Ground truth labels. Returns: np.ndarray: Mean class accuracy. """ pred = np.argmax(scores, axis=1) cf_mat =...
Calculate mean class accuracy. Args: scores (list[np.ndarray]): Prediction scores for each class. labels (list[int]): Ground truth labels. Returns: np.ndarray: Mean class accuracy.
mean_class_accuracy
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def top_k_classes(scores, labels, k=10, mode='accurate'): """Calculate the most K accurate (inaccurate) classes. Given the prediction scores, ground truth label and top-k value, compute the top K accurate (inaccurate) classes. Args: scores (list[np.ndarray]): Prediction scores for each class. ...
Calculate the most K accurate (inaccurate) classes. Given the prediction scores, ground truth label and top-k value, compute the top K accurate (inaccurate) classes. Args: scores (list[np.ndarray]): Prediction scores for each class. labels (list[int] | np.ndarray): Ground truth labels. ...
top_k_classes
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def top_k_accuracy(scores, labels, topk=(1, )): """Calculate top k accuracy score. Args: scores (list[np.ndarray]): Prediction scores for each class. labels (list[int]): Ground truth labels. topk (tuple[int]): K value for top_k_accuracy. Default: (1, ). Returns: list[float]...
Calculate top k accuracy score. Args: scores (list[np.ndarray]): Prediction scores for each class. labels (list[int]): Ground truth labels. topk (tuple[int]): K value for top_k_accuracy. Default: (1, ). Returns: list[float]: Top k accuracy score for each k.
top_k_accuracy
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def mean_average_precision(scores, labels): """Mean average precision for multi-label recognition. Args: scores (list[np.ndarray]): Prediction scores of different classes for each sample. labels (list[np.ndarray]): Ground truth many-hot vector for each sample. Retur...
Mean average precision for multi-label recognition. Args: scores (list[np.ndarray]): Prediction scores of different classes for each sample. labels (list[np.ndarray]): Ground truth many-hot vector for each sample. Returns: np.float64: The mean average precision....
mean_average_precision
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def binary_precision_recall_curve(y_score, y_true): """Calculate the binary precision recall curve at step thresholds. Args: y_score (np.ndarray): Prediction scores for each class. Shape should be (num_classes, ). y_true (np.ndarray): Ground truth many-hot vector. Shape ...
Calculate the binary precision recall curve at step thresholds. Args: y_score (np.ndarray): Prediction scores for each class. Shape should be (num_classes, ). y_true (np.ndarray): Ground truth many-hot vector. Shape should be (num_classes, ). Returns: precision ...
binary_precision_recall_curve
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def pairwise_temporal_iou(candidate_segments, target_segments, calculate_overlap_self=False): """Compute intersection over union between segments. Args: candidate_segments (np.ndarray): 1-dim/2-dim array in format ``[init, end]/[m x 2:=[in...
Compute intersection over union between segments. Args: candidate_segments (np.ndarray): 1-dim/2-dim array in format ``[init, end]/[m x 2:=[init, end]]``. target_segments (np.ndarray): 2-dim array in format ``[n x 2:=[init, end]]``. calculate_overlap_self (bool): Whe...
pairwise_temporal_iou
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def average_recall_at_avg_proposals(ground_truth, proposals, total_num_proposals, max_avg_proposals=None, temporal_iou_thresholds=np.linspace( ...
Computes the average recall given an average number (percentile) of proposals per video. Args: ground_truth (dict): Dict containing the ground truth instances. proposals (dict): Dict containing the proposal instances. total_num_proposals (int): Total number of proposals in the ...
average_recall_at_avg_proposals
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def get_weighted_score(score_list, coeff_list): """Get weighted score with given scores and coefficients. Given n predictions by different classifier: [score_1, score_2, ..., score_n] (score_list) and their coefficients: [coeff_1, coeff_2, ..., coeff_n] (coeff_list), return weighted score: weighted_sco...
Get weighted score with given scores and coefficients. Given n predictions by different classifier: [score_1, score_2, ..., score_n] (score_list) and their coefficients: [coeff_1, coeff_2, ..., coeff_n] (coeff_list), return weighted score: weighted_score = score_1 * coeff_1 + score_2 * coeff_2 + ... + ...
get_weighted_score
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def average_precision_at_temporal_iou(ground_truth, prediction, temporal_iou_thresholds=(np.linspace( 0.5, 0.95, 10))): """Compute average precision (in detection task) between ground truth and ...
Compute average precision (in detection task) between ground truth and predicted data frames. If multiple predictions match the same predicted segment, only the one with highest score is matched as true positive. This code is greatly inspired by Pascal VOC devkit. Args: ground_truth (dict): Dic...
average_precision_at_temporal_iou
python
open-mmlab/mmaction2
mmaction/evaluation/functional/accuracy.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py
Apache-2.0
def det2csv(results, custom_classes): """Convert detection results to csv file.""" csv_results = [] for idx in range(len(results)): video_id = results[idx]['video_id'] timestamp = results[idx]['timestamp'] result = results[idx]['outputs'] for label, _ in enumerate(result): ...
Convert detection results to csv file.
det2csv
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py
Apache-2.0