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 __getitem__(self, img_key): """Sample long term features like `lfb['0f39OWEqJ24,0902']` where `lfb` is a instance of class LFB.""" video_id, timestamp = img_key.split(',') return self.sample_long_term_features(video_id, int(timestamp))
Sample long term features like `lfb['0f39OWEqJ24,0902']` where `lfb` is a instance of class LFB.
__getitem__
python
open-mmlab/mmaction2
mmaction/models/roi_heads/shared_heads/lfb.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/roi_heads/shared_heads/lfb.py
Apache-2.0
def forward(self, x, rois, img_metas, **kwargs): """Defines the computation performed at every call. Args: x (torch.Tensor): The extracted RoI feature. rois (torch.Tensor): The regions of interest. img_metas (List[dict]): The meta information of the data. Re...
Defines the computation performed at every call. Args: x (torch.Tensor): The extracted RoI feature. rois (torch.Tensor): The regions of interest. img_metas (List[dict]): The meta information of the data. Returns: torch.Tensor: The RoI features that have ...
forward
python
open-mmlab/mmaction2
mmaction/models/roi_heads/shared_heads/lfb_infer_head.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/roi_heads/shared_heads/lfb_infer_head.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type)
Defines the computation performed at every call.
forward
python
open-mmlab/mmaction2
mmaction/models/similarity/adapters.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/similarity/adapters.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x
Defines the computation performed at every call.
forward
python
open-mmlab/mmaction2
mmaction/models/similarity/adapters.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/similarity/adapters.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" b, seq_length, c = x.size() x_original = x x = x + self.positional_embedding x = x.transpose(0, 1) # NLD -> LND x = self.transformer(x) x = x.transpose(0, ...
Defines the computation performed at every call.
forward
python
open-mmlab/mmaction2
mmaction/models/similarity/adapters.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/similarity/adapters.py
Apache-2.0
def _freeze_stages(self) -> None: """Prevent all the parameters from being optimized before ``self.frozen_layers``.""" if self.frozen_layers >= 0: top_layers = [ 'ln_final', 'text_projection', 'logit_scale', 'visual.ln_post', 'visual.proj' ...
Prevent all the parameters from being optimized before ``self.frozen_layers``.
_freeze_stages
python
open-mmlab/mmaction2
mmaction/models/similarity/clip_similarity.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/similarity/clip_similarity.py
Apache-2.0
def assign_wrt_overlaps(self, overlaps: Tensor, gt_labels: Tensor) -> AssignResult: """Assign w.r.t. the overlaps of bboxes with gts. Args: overlaps (Tensor): Overlaps between k gt_bboxes and n bboxes, shape(k, n). gt_labels (Tensor): ...
Assign w.r.t. the overlaps of bboxes with gts. Args: overlaps (Tensor): Overlaps between k gt_bboxes and n bboxes, shape(k, n). gt_labels (Tensor): Labels of k gt_bboxes, shape (k, num_classes). Returns: :obj:`AssignResult`: The assig...
assign_wrt_overlaps
python
open-mmlab/mmaction2
mmaction/models/task_modules/assigners/max_iou_assigner_ava.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/task_modules/assigners/max_iou_assigner_ava.py
Apache-2.0
def __call__(self, imgs: torch.Tensor, batch_data_samples: SampleList, **kwargs) -> Tuple: """Blending data in a mini-batch. Images are float tensors with the shape of (B, N, C, H, W) for 2D recognizers or (B, N, C, T, H, W) for 3D recognizers. Besides, labels are conv...
Blending data in a mini-batch. Images are float tensors with the shape of (B, N, C, H, W) for 2D recognizers or (B, N, C, T, H, W) for 3D recognizers. Besides, labels are converted from hard labels to soft labels. Hard labels are integer tensors with the shape of (B, ) and all of the ...
__call__
python
open-mmlab/mmaction2
mmaction/models/utils/blending_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/blending_utils.py
Apache-2.0
def do_blending(self, imgs: torch.Tensor, label: torch.Tensor, **kwargs) -> Tuple: """Blending images with mixup. Args: imgs (torch.Tensor): Model input images, float tensor with the shape of (B, N, C, H, W) or (B, N, C, T, H, W). label (torch...
Blending images with mixup. Args: imgs (torch.Tensor): Model input images, float tensor with the shape of (B, N, C, H, W) or (B, N, C, T, H, W). label (torch.Tensor): One hot labels, integer tensor with the shape of (B, num_classes). Returns: ...
do_blending
python
open-mmlab/mmaction2
mmaction/models/utils/blending_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/blending_utils.py
Apache-2.0
def do_blending(self, imgs: torch.Tensor, label: torch.Tensor, **kwargs) -> Tuple: """Blending images with cutmix. Args: imgs (torch.Tensor): Model input images, float tensor with the shape of (B, N, C, H, W) or (B, N, C, T, H, W). label (torc...
Blending images with cutmix. Args: imgs (torch.Tensor): Model input images, float tensor with the shape of (B, N, C, H, W) or (B, N, C, T, H, W). label (torch.Tensor): One hot labels, integer tensor with the shape of (B, num_classes). Returns: ...
do_blending
python
open-mmlab/mmaction2
mmaction/models/utils/blending_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/blending_utils.py
Apache-2.0
def do_blending(self, imgs: torch.Tensor, label: torch.Tensor, **kwargs) -> Tuple: """Randomly apply batch augmentations to the batch inputs and batch data samples.""" aug_index = np.random.choice(len(self.augments), p=self.probs) aug = self.augments[aug_index] ...
Randomly apply batch augmentations to the batch inputs and batch data samples.
do_blending
python
open-mmlab/mmaction2
mmaction/models/utils/blending_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/blending_utils.py
Apache-2.0
def get_pad_shape(self, input_shape): """Calculate the padding size of input. Args: input_shape (:obj:`torch.Size`): arrange as (H, W). Returns: Tuple[int]: The padding size along the original H and W directions """ input_t, input_h, input_w ...
Calculate the padding size of input. Args: input_shape (:obj:`torch.Size`): arrange as (H, W). Returns: Tuple[int]: The padding size along the original H and W directions
get_pad_shape
python
open-mmlab/mmaction2
mmaction/models/utils/embed.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/embed.py
Apache-2.0
def forward(self, x): """Add padding to `x` Args: x (Tensor): Input tensor has shape (B, C, H, W). Returns: Tensor: The tensor with adaptive padding """ pad_d, pad_h, pad_w = self.get_pad_shape(x.size()[-2:]) if pad_d > 0 or pad_h > 0 or pad_w > ...
Add padding to `x` Args: x (Tensor): Input tensor has shape (B, C, H, W). Returns: Tensor: The tensor with adaptive padding
forward
python
open-mmlab/mmaction2
mmaction/models/utils/embed.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/embed.py
Apache-2.0
def forward(self, x): """ Args: x (Tensor): Has shape (B, C, T, H, W). In most case, C is 3. Returns: tuple: Contains merged results and its spatial shape. - x (Tensor): Has shape (B, out_t * out_h * out_w, embed_dims) - out_size (tuple[int]): Sp...
Args: x (Tensor): Has shape (B, C, T, H, W). In most case, C is 3. Returns: tuple: Contains merged results and its spatial shape. - x (Tensor): Has shape (B, out_t * out_h * out_w, embed_dims) - out_size (tuple[int]): Spatial shape of x, arrange as ...
forward
python
open-mmlab/mmaction2
mmaction/models/utils/embed.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/embed.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" n, c, t, v = x.shape res = self.down(x) if self.with_res else 0 A_switch = {None: self.A, 'init': self.A} if hasattr(self, 'PA'): A_switch.update({ ...
Defines the computation performed at every call.
forward
python
open-mmlab/mmaction2
mmaction/models/utils/gcn_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/gcn_utils.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" N, C, T, V = x.size() y = None if self.adaptive: for i in range(self.num_subset): A1 = self.conv_a[i](x).permute(0, 3, 1, 2).contiguous().view( ...
Defines the computation performed at every call.
forward
python
open-mmlab/mmaction2
mmaction/models/utils/gcn_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/gcn_utils.py
Apache-2.0
def inner_forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" N, C, T, V = x.shape branch_outs = [] for tempconv in self.branches: out = tempconv(x) branch_outs.append(out) feat = torch.cat(branch_outs, ...
Defines the computation performed at every call.
inner_forward
python
open-mmlab/mmaction2
mmaction/models/utils/gcn_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/gcn_utils.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call.""" out = self.inner_forward(x) out = self.bn(out) return self.drop(out)
Defines the computation performed at every call.
forward
python
open-mmlab/mmaction2
mmaction/models/utils/gcn_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/gcn_utils.py
Apache-2.0
def k_adjacency(A: Union[torch.Tensor, np.ndarray], k: int, with_self: bool = False, self_factor: float = 1) -> np.ndarray: """Construct k-adjacency matrix. Args: A (torch.Tensor or np.ndarray): The adjacency matrix. k (int): The number of hops. ...
Construct k-adjacency matrix. Args: A (torch.Tensor or np.ndarray): The adjacency matrix. k (int): The number of hops. with_self (bool): Whether to add self-loops to the k-adjacency matrix. The self-loops is critical for learning the relationships between the current...
k_adjacency
python
open-mmlab/mmaction2
mmaction/models/utils/graph.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/graph.py
Apache-2.0
def edge2mat(edges: List[Tuple[int, int]], num_node: int) -> np.ndarray: """Get adjacency matrix from edges. Args: edges (list[tuple[int, int]]): The edges of the graph. num_node (int): The number of nodes of the graph. Returns: np.ndarray: The adjacency matrix. """ A = np....
Get adjacency matrix from edges. Args: edges (list[tuple[int, int]]): The edges of the graph. num_node (int): The number of nodes of the graph. Returns: np.ndarray: The adjacency matrix.
edge2mat
python
open-mmlab/mmaction2
mmaction/models/utils/graph.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/graph.py
Apache-2.0
def normalize_digraph(A: np.ndarray, dim: int = 0) -> np.ndarray: """Normalize the digraph according to the given dimension. Args: A (np.ndarray): The adjacency matrix. dim (int): The dimension to perform normalization. Defaults to 0. Returns: np.ndarray: The normalized...
Normalize the digraph according to the given dimension. Args: A (np.ndarray): The adjacency matrix. dim (int): The dimension to perform normalization. Defaults to 0. Returns: np.ndarray: The normalized adjacency matrix.
normalize_digraph
python
open-mmlab/mmaction2
mmaction/models/utils/graph.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/graph.py
Apache-2.0
def get_hop_distance(num_node: int, edges: List[Tuple[int, int]], max_hop: int = 1) -> np.ndarray: """Get n-hop distance matrix by edges. Args: num_node (int): The number of nodes of the graph. edges (list[tuple[int, int]]): The edges of the graph. ...
Get n-hop distance matrix by edges. Args: num_node (int): The number of nodes of the graph. edges (list[tuple[int, int]]): The edges of the graph. max_hop (int): The maximal distance between two connected nodes. Defaults to 1. Returns: np.ndarray: The n-hop distance...
get_hop_distance
python
open-mmlab/mmaction2
mmaction/models/utils/graph.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/utils/graph.py
Apache-2.0
def format_label(value: LABEL_TYPE) -> torch.Tensor: """Convert various python types to label-format tensor. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int`. Args: value (torch.Tensor | numpy.ndarray | Sequence | int): Label value. Retur...
Convert various python types to label-format tensor. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int`. Args: value (torch.Tensor | numpy.ndarray | Sequence | int): Label value. Returns: :obj:`torch.Tensor`: The formatted label tensor....
format_label
python
open-mmlab/mmaction2
mmaction/structures/action_data_sample.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/structures/action_data_sample.py
Apache-2.0
def format_score(value: SCORE_TYPE) -> Union[torch.Tensor, Dict]: """Convert various python types to score-format tensor. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`. Args: value (torch.Tensor | numpy.ndarray | Sequence | dict): Score value...
Convert various python types to score-format tensor. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`. Args: value (torch.Tensor | numpy.ndarray | Sequence | dict): Score values or dict of scores values. Returns: :obj:`torch.Tensor` | d...
format_score
python
open-mmlab/mmaction2
mmaction/structures/action_data_sample.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/structures/action_data_sample.py
Apache-2.0
def bbox_target(pos_bboxes_list: List[torch.Tensor], neg_bboxes_list: List[torch.Tensor], gt_labels: List[torch.Tensor], cfg: Union[dict, mmengine.ConfigDict]) -> tuple: """Generate classification targets for bboxes. Args: pos_bboxes_list (List[torch.Tens...
Generate classification targets for bboxes. Args: pos_bboxes_list (List[torch.Tensor]): Positive bboxes list. neg_bboxes_list (List[torch.Tensor]): Negative bboxes list. gt_labels (List[torch.Tensor]): Groundtruth classification label list. cfg (dict | mmengine.ConfigDict): RCNN con...
bbox_target
python
open-mmlab/mmaction2
mmaction/structures/bbox/bbox_target.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/structures/bbox/bbox_target.py
Apache-2.0
def bbox2result(bboxes: torch.Tensor, labels: torch.Tensor, num_classes: int, thr: float = 0.01) -> list: """Convert detection results to a list of numpy arrays. This identifies single-label classification (as opposed to multi-label) through the thr parameter...
Convert detection results to a list of numpy arrays. This identifies single-label classification (as opposed to multi-label) through the thr parameter which is set to a negative value. ToDo: The ideal way would be for this to be automatically set when the Currently, the way to set this is to set ``tes...
bbox2result
python
open-mmlab/mmaction2
mmaction/structures/bbox/transforms.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/structures/bbox/transforms.py
Apache-2.0
def check_norm_state(modules, train_state): """Check if norm layer is in correct train state.""" for mod in modules: if isinstance(mod, _BatchNorm): if mod.training != train_state: return False return True
Check if norm layer is in correct train state.
check_norm_state
python
open-mmlab/mmaction2
mmaction/testing/_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/testing/_utils.py
Apache-2.0
def generate_backbone_demo_inputs(input_shape=(1, 3, 64, 64)): """Create a superset of inputs needed to run backbone. Args: input_shape (tuple): input batch dimensions. Defaults to ``(1, 3, 64, 64)``. """ imgs = np.random.random(input_shape) imgs = torch.FloatTensor(imgs) r...
Create a superset of inputs needed to run backbone. Args: input_shape (tuple): input batch dimensions. Defaults to ``(1, 3, 64, 64)``.
generate_backbone_demo_inputs
python
open-mmlab/mmaction2
mmaction/testing/_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/testing/_utils.py
Apache-2.0
def generate_recognizer_demo_inputs( input_shape=(1, 3, 3, 224, 224), model_type='2D'): """Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions. Default: (1, 250, 3, 224, 224). model_type (str): Model type for dat...
Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions. Default: (1, 250, 3, 224, 224). model_type (str): Model type for data generation, from {'2D', '3D'}. Default:'2D'
generate_recognizer_demo_inputs
python
open-mmlab/mmaction2
mmaction/testing/_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/testing/_utils.py
Apache-2.0
def get_cfg(config_type, fname): """Grab configs necessary to create a recognizer. These are deep copied to allow for safe modification of parameters without influencing other tests. """ config_types = ('recognition', 'recognition_audio', 'localization', 'detection', 'skeleton',...
Grab configs necessary to create a recognizer. These are deep copied to allow for safe modification of parameters without influencing other tests.
get_cfg
python
open-mmlab/mmaction2
mmaction/testing/_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/testing/_utils.py
Apache-2.0
def collect_env(): """Collect the information of the running environments.""" env_info = collect_basic_env() env_info['MMAction2'] = ( mmaction.__version__ + '+' + get_git_hash(digits=7)) env_info['MMCV'] = (mmcv.__version__) try: import mmdet env_info['MMDetection'] = (mmde...
Collect the information of the running environments.
collect_env
python
open-mmlab/mmaction2
mmaction/utils/collect_env.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/collect_env.py
Apache-2.0
def require(dep, install=None): """A wrapper of function for extra package requirements. Args: dep (str): The dependency package name, like ``transformers`` or ``transformers>=4.28.0``. install (str, optional): The installation command hint. Defaults to None, which means...
A wrapper of function for extra package requirements. Args: dep (str): The dependency package name, like ``transformers`` or ``transformers>=4.28.0``. install (str, optional): The installation command hint. Defaults to None, which means to use "pip install dep".
require
python
open-mmlab/mmaction2
mmaction/utils/dependency.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/dependency.py
Apache-2.0
def _register_hooks(self, layer_name: str) -> None: """Register forward and backward hook to a layer, given layer_name, to obtain gradients and activations. Args: layer_name (str): name of the layer. """ def get_gradients(module, grad_input, grad_output): ...
Register forward and backward hook to a layer, given layer_name, to obtain gradients and activations. Args: layer_name (str): name of the layer.
_register_hooks
python
open-mmlab/mmaction2
mmaction/utils/gradcam_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/gradcam_utils.py
Apache-2.0
def _calculate_localization_map(self, data: dict, use_labels: bool, delta=1e-20) -> tuple: """Calculate localization map for all inputs with Grad-CAM. Args: data (dict): model inputs,...
Calculate localization map for all inputs with Grad-CAM. Args: data (dict): model inputs, generated by test pipeline, use_labels (bool): Whether to use given labels to generate localization map. delta (float): used in localization map normalization, ...
_calculate_localization_map
python
open-mmlab/mmaction2
mmaction/utils/gradcam_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/gradcam_utils.py
Apache-2.0
def _alpha_blending(self, localization_map: torch.Tensor, input_imgs: torch.Tensor, alpha: float) -> torch.Tensor: """Blend heatmaps and model input images and get visulization results. Args: localization_map (torch.Tensor): localization map f...
Blend heatmaps and model input images and get visulization results. Args: localization_map (torch.Tensor): localization map for all inputs, generated with Grad-CAM. input_imgs (torch.Tensor): model inputs, raw images. alpha (float): transparency level of the ...
_alpha_blending
python
open-mmlab/mmaction2
mmaction/utils/gradcam_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/gradcam_utils.py
Apache-2.0
def __call__(self, data: dict, use_labels: bool = False, alpha: float = 0.5) -> tuple: """Visualize the localization maps on their corresponding inputs as heatmap, using Grad-CAM. Generate visualization results for **ALL CROPS**. For ex...
Visualize the localization maps on their corresponding inputs as heatmap, using Grad-CAM. Generate visualization results for **ALL CROPS**. For example, for I3D model, if `clip_len=32, num_clips=10` and use `ThreeCrop` in test pipeline, then for every model inputs, there are 960...
__call__
python
open-mmlab/mmaction2
mmaction/utils/gradcam_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/gradcam_utils.py
Apache-2.0
def get_random_string(length: int = 15) -> str: """Get random string with letters and digits. Args: length (int): Length of random string. Defaults to 15. """ return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(length))
Get random string with letters and digits. Args: length (int): Length of random string. Defaults to 15.
get_random_string
python
open-mmlab/mmaction2
mmaction/utils/misc.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/misc.py
Apache-2.0
def frame_extract(video_path: str, short_side: Optional[int] = None, out_dir: str = './tmp'): """Extract frames given video_path. Args: video_path (str): The video path. short_side (int): Target short-side of the output image. Defaults to None, me...
Extract frames given video_path. Args: video_path (str): The video path. short_side (int): Target short-side of the output image. Defaults to None, means keeping original shape. out_dir (str): The output directory. Defaults to ``'./tmp'``.
frame_extract
python
open-mmlab/mmaction2
mmaction/utils/misc.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/misc.py
Apache-2.0
def get_str_type(module: Union[str, ModuleType, FunctionType]) -> str: """Return the string type name of module. Args: module (str | ModuleType | FunctionType): The target module class Returns: Class name of the module """ if isinstance(module, str): str_type = ...
Return the string type name of module. Args: module (str | ModuleType | FunctionType): The target module class Returns: Class name of the module
get_str_type
python
open-mmlab/mmaction2
mmaction/utils/misc.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/misc.py
Apache-2.0
def register_all_modules(init_default_scope: bool = True) -> None: """Register all modules in mmaction into the registries. Args: init_default_scope (bool): Whether initialize the mmaction default scope. If True, the global default scope will be set to `mmaction`, and all regist...
Register all modules in mmaction into the registries. Args: init_default_scope (bool): Whether initialize the mmaction default scope. If True, the global default scope will be set to `mmaction`, and all registries will build modules from mmaction's registry node. To unde...
register_all_modules
python
open-mmlab/mmaction2
mmaction/utils/setup_env.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/utils/setup_env.py
Apache-2.0
def _load_video(self, video: Union[np.ndarray, Sequence[np.ndarray], str], target_resolution: Optional[Tuple[int]] = None): """Load video from multiple source and convert to target resolution. Args: video (np.ndarray, str): The video to draw. ...
Load video from multiple source and convert to target resolution. Args: video (np.ndarray, str): The video to draw. target_resolution (Tuple[int], optional): Set to (desired_width desired_height) to have resized frames. If either dimension is None, the fr...
_load_video
python
open-mmlab/mmaction2
mmaction/visualization/action_visualizer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/visualization/action_visualizer.py
Apache-2.0
def add_datasample(self, name: str, video: Union[np.ndarray, Sequence[np.ndarray], str], data_sample: Optional[ActionDataSample] = None, draw_gt: bool = True, draw_pred: bool = True, ...
Draw datasample and save to all backends. - If ``out_path`` is specified, all storage backends are ignored and save the videos to the ``out_path``. - If ``show_frames`` is True, plot the frames in a window sequentially, please confirm you are able to access the graphical interface. ...
add_datasample
python
open-mmlab/mmaction2
mmaction/visualization/action_visualizer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/visualization/action_visualizer.py
Apache-2.0
def add_video( self, name: str, image: np.ndarray, step: int = 0, fps: int = 4, out_type: str = 'img', ) -> None: """Record the image. Args: name (str): The image identifier. image (np.ndarray, optional): The image to be saved....
Record the image. Args: name (str): The image identifier. image (np.ndarray, optional): The image to be saved. The format should be RGB. Default to None. step (int): Global step value to record. Default to 0. fps (int): Frames per second for savin...
add_video
python
open-mmlab/mmaction2
mmaction/visualization/action_visualizer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/visualization/action_visualizer.py
Apache-2.0
def add_video(self, name: str, frames: np.ndarray, step: int = 0, fps: Optional[int] = 4, out_type: Optional[int] = 'img', **kwargs) -> None: """Record the frames of a video to disk. Args: ...
Record the frames of a video to disk. Args: name (str): The video identifier (frame folder). frames (np.ndarray): The frames to be saved. The format should be RGB. The shape should be (T, H, W, C). step (int): Global step value to record. Defaults to 0. ...
add_video
python
open-mmlab/mmaction2
mmaction/visualization/video_backend.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/visualization/video_backend.py
Apache-2.0
def add_video(self, name: str, frames: np.ndarray, fps: int = 4, **kwargs) -> None: """Record the frames of a video to wandb. Note that this requires the ``moviepy`` package. Args: name (str): The video identif...
Record the frames of a video to wandb. Note that this requires the ``moviepy`` package. Args: name (str): The video identifier (frame folder). frames (np.ndarray): The frames to be saved. The format should be RGB. The shape should be (T, H, W, C). st...
add_video
python
open-mmlab/mmaction2
mmaction/visualization/video_backend.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/visualization/video_backend.py
Apache-2.0
def add_video(self, name: str, frames: np.ndarray, step: int = 0, fps: int = 4, **kwargs) -> None: """Record the frames of a video to tensorboard. Note that this requires the ``moviepy`` package. Args: ...
Record the frames of a video to tensorboard. Note that this requires the ``moviepy`` package. Args: name (str): The video identifier (frame folder). frames (np.ndarray): The frames to be saved. The format should be RGB. The shape should be (T, H, W, C). ...
add_video
python
open-mmlab/mmaction2
mmaction/visualization/video_backend.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/visualization/video_backend.py
Apache-2.0
def check_crop(origin_imgs, result_imgs, result_bbox, num_crops=1): """Check if the result_bbox is in correspond to result_imgs.""" def check_single_crop(origin_imgs, result_imgs, result_bbox): result_img_shape = result_imgs[0].shape[:2] crop_w = result_bbox[2] - result_bbox[0] crop_h =...
Check if the result_bbox is in correspond to result_imgs.
check_crop
python
open-mmlab/mmaction2
tests/datasets/transforms/test_processing.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/datasets/transforms/test_processing.py
Apache-2.0
def check_flip(origin_imgs, result_imgs, flip_type): """Check if the origin_imgs are flipped correctly into result_imgs in different flip_types.""" n, _, _, _ = np.shape(origin_imgs) if flip_type == 'horizontal': for i in range(n): if np.any(result_imgs[i] != np.fliplr(origin_imgs[i]...
Check if the origin_imgs are flipped correctly into result_imgs in different flip_types.
check_flip
python
open-mmlab/mmaction2
tests/datasets/transforms/test_processing.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/datasets/transforms/test_processing.py
Apache-2.0
def check_flip(origin_imgs, result_imgs, flip_type): """Check if the origin_imgs are flipped correctly into result_imgs in different flip_types.""" n, _, _, _ = np.shape(origin_imgs) if flip_type == 'horizontal': for i in range(n): if np.any(result_imgs[i] != np.fliplr(origin_imgs[i]...
Check if the origin_imgs are flipped correctly into result_imgs in different flip_types.
check_flip
python
open-mmlab/mmaction2
tests/datasets/transforms/test_wrappers.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/datasets/transforms/test_wrappers.py
Apache-2.0
def test_evaluate(self): """Test using the metric in the same way as Evalutor.""" pred = [ ActionDataSample().set_pred_score(i).set_pred_label( j).set_gt_label(k).to_dict() for i, j, k in zip([ torch.tensor([0.7, 0.0, 0.3]), torch.tenso...
Test using the metric in the same way as Evalutor.
test_evaluate
python
open-mmlab/mmaction2
tests/evaluation/metrics/test_acc_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/evaluation/metrics/test_acc_metric.py
Apache-2.0
def gt_confusion_matrix(gt_labels, pred_labels, normalize=None): """Calculate the ground truth confusion matrix.""" max_index = max(max(gt_labels), max(pred_labels)) confusion_mat = np.zeros((max_index + 1, max_index + 1), dtype=np.int64) for gt, pred in zip(gt_labels, pred_labels): confusion_ma...
Calculate the ground truth confusion matrix.
gt_confusion_matrix
python
open-mmlab/mmaction2
tests/evaluation/metrics/test_metric_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/evaluation/metrics/test_metric_utils.py
Apache-2.0
def test_evaluate(self): """Test using the metric in the same way as Evalutor.""" pred = [ ActionDataSample().set_pred_score(i).set_gt_label(k).to_dict() for i, k in zip([ torch.tensor([0.7, 0.0, 0.3]), torch.tensor([0.5, 0.2, 0.3]), ...
Test using the metric in the same way as Evalutor.
test_evaluate
python
open-mmlab/mmaction2
tests/evaluation/metrics/test_retrieval_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/evaluation/metrics/test_retrieval_metric.py
Apache-2.0
def test_calculate(self): """Test using the metric from static method.""" # seq of indices format y_true = [[0, 2, 5, 8, 9], [1, 4, 6]] y_pred = [np.arange(10)] * 2 # test with average is 'macro' recall_score = RetrievalRecall.calculate( y_pred, y_true, topk...
Test using the metric from static method.
test_calculate
python
open-mmlab/mmaction2
tests/evaluation/metrics/test_retrieval_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/evaluation/metrics/test_retrieval_metric.py
Apache-2.0
def is_norm(modules): """Check if is one of the norms.""" if isinstance(modules, (GroupNorm, _BatchNorm)): return True return False
Check if is one of the norms.
is_norm
python
open-mmlab/mmaction2
tests/models/backbones/test_mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/backbones/test_mobilenet_v2.py
Apache-2.0
def is_block(modules): """Check if is ResNet building block.""" if isinstance(modules, (InvertedResidual, )): return True return False
Check if is ResNet building block.
is_block
python
open-mmlab/mmaction2
tests/models/backbones/test_mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/backbones/test_mobilenet_v2.py
Apache-2.0
def test_i3d_head(): """Test loss method, layer construction, attributes and forward function in i3d head.""" i3d_head = I3DHead(num_classes=4, in_channels=2048) i3d_head.init_weights() assert i3d_head.num_classes == 4 assert i3d_head.dropout_ratio == 0.5 assert i3d_head.in_channels == 2048...
Test loss method, layer construction, attributes and forward function in i3d head.
test_i3d_head
python
open-mmlab/mmaction2
tests/models/heads/test_i3d_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_i3d_head.py
Apache-2.0
def test_slowfast_head(): """Test loss method, layer construction, attributes and forward function in slowfast head.""" sf_head = SlowFastHead(num_classes=4, in_channels=2304) sf_head.init_weights() assert sf_head.num_classes == 4 assert sf_head.dropout_ratio == 0.8 assert sf_head.in_channe...
Test loss method, layer construction, attributes and forward function in slowfast head.
test_slowfast_head
python
open-mmlab/mmaction2
tests/models/heads/test_slowfast_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_slowfast_head.py
Apache-2.0
def test_timesformer_head(): """Test loss method, layer construction, attributes and forward function in timesformer head.""" timesformer_head = TimeSformerHead(num_classes=4, in_channels=64) timesformer_head.init_weights() assert timesformer_head.num_classes == 4 assert timesformer_head.in_cha...
Test loss method, layer construction, attributes and forward function in timesformer head.
test_timesformer_head
python
open-mmlab/mmaction2
tests/models/heads/test_timesformer_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_timesformer_head.py
Apache-2.0
def test_tpn_head(): """Test loss method, layer construction, attributes and forward function in tpn head.""" tpn_head = TPNHead(num_classes=4, in_channels=2048) tpn_head.init_weights() assert hasattr(tpn_head, 'avg_pool2d') assert hasattr(tpn_head, 'avg_pool3d') assert isinstance(tpn_head....
Test loss method, layer construction, attributes and forward function in tpn head.
test_tpn_head
python
open-mmlab/mmaction2
tests/models/heads/test_tpn_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_tpn_head.py
Apache-2.0
def test_trn_head(): """Test loss method, layer construction, attributes and forward function in trn head.""" from mmaction.models.heads.trn_head import (RelationModule, RelationModuleMultiScale) trn_head = TRNHead(num_classes=4, in_channels=2048, relation...
Test loss method, layer construction, attributes and forward function in trn head.
test_trn_head
python
open-mmlab/mmaction2
tests/models/heads/test_trn_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_trn_head.py
Apache-2.0
def test_tsm_head(): """Test loss method, layer construction, attributes and forward function in tsm head.""" tsm_head = TSMHead(num_classes=4, in_channels=2048) tsm_head.init_weights() assert tsm_head.num_classes == 4 assert tsm_head.dropout_ratio == 0.8 assert tsm_head.in_channels == 2048...
Test loss method, layer construction, attributes and forward function in tsm head.
test_tsm_head
python
open-mmlab/mmaction2
tests/models/heads/test_tsm_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_tsm_head.py
Apache-2.0
def test_tsn_head(): """Test loss method, layer construction, attributes and forward function in tsn head.""" tsn_head = TSNHead(num_classes=4, in_channels=2048) tsn_head.init_weights() assert tsn_head.num_classes == 4 assert tsn_head.dropout_ratio == 0.4 assert tsn_head.in_channels == 2048...
Test loss method, layer construction, attributes and forward function in tsn head.
test_tsn_head
python
open-mmlab/mmaction2
tests/models/heads/test_tsn_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_tsn_head.py
Apache-2.0
def test_x3d_head(): """Test loss method, layer construction, attributes and forward function in x3d head.""" x3d_head = X3DHead(in_channels=432, num_classes=4, fc1_bias=False) x3d_head.init_weights() assert x3d_head.num_classes == 4 assert x3d_head.dropout_ratio == 0.5 assert x3d_head.in_c...
Test loss method, layer construction, attributes and forward function in x3d head.
test_x3d_head
python
open-mmlab/mmaction2
tests/models/heads/test_x3d_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/heads/test_x3d_head.py
Apache-2.0
def test_bbox_head_ava(): """Test loss method, layer construction, attributes and forward function in bbox head.""" with pytest.raises(TypeError): # topk must be None, int or tuple[int] BBoxHeadAVA(background_class=True, topk=0.1) with pytest.raises(AssertionError): # topk shoul...
Test loss method, layer construction, attributes and forward function in bbox head.
test_bbox_head_ava
python
open-mmlab/mmaction2
tests/models/roi_heads/test_bbox_heads.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/roi_heads/test_bbox_heads.py
Apache-2.0
def test_fbo_head(): """Test layer construction, attributes and forward function in fbo head.""" lfb_prefix_path = osp.normpath( osp.join(osp.dirname(__file__), '../../data/lfb')) st_feat_shape = (1, 16, 1, 8, 8) st_feat = torch.rand(st_feat_shape) rois = torch.randn(1, 5) rois[0][0] = ...
Test layer construction, attributes and forward function in fbo head.
test_fbo_head
python
open-mmlab/mmaction2
tests/models/roi_heads/test_fbo_head.py
https://github.com/open-mmlab/mmaction2/blob/master/tests/models/roi_heads/test_fbo_head.py
Apache-2.0
def __call__(self, results): """Select frames to verify. Select the first, last and three random frames, Required key is "total_frames", added or modified key is "frame_inds". Args: results (dict): The resulting dict to be modified and passed to the next tran...
Select frames to verify. Select the first, last and three random frames, Required key is "total_frames", added or modified key is "frame_inds". Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline.
__call__
python
open-mmlab/mmaction2
tools/analysis_tools/check_videos.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/analysis_tools/check_videos.py
Apache-2.0
def cuhk17_top1(): """Assign label for each proposal with the cuhk17 result, which is the #2 entry in http://activity-net.org/challenges/2017/evaluation.html.""" if not osp.exists('cuhk_anet17_pred.json'): os.system('wget https://download.openmmlab.com/' 'mmaction/localization/cuhk...
Assign label for each proposal with the cuhk17 result, which is the #2 entry in http://activity-net.org/challenges/2017/evaluation.html.
cuhk17_top1
python
open-mmlab/mmaction2
tools/analysis_tools/report_map.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/analysis_tools/report_map.py
Apache-2.0
def lines2dictlist(lines, format): """Convert lines in 'txt' format to dictionaries in 'json' format. Currently support single-label and multi-label. Example of a single-label rawframes annotation txt file: .. code-block:: txt (frame_dir num_frames label) some/directory-1 163 1 ...
Convert lines in 'txt' format to dictionaries in 'json' format. Currently support single-label and multi-label. Example of a single-label rawframes annotation txt file: .. code-block:: txt (frame_dir num_frames label) some/directory-1 163 1 some/directory-2 122 1 some/dire...
lines2dictlist
python
open-mmlab/mmaction2
tools/data/anno_txt2json.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/anno_txt2json.py
Apache-2.0
def generate_spectrogram_magphase(self, audio, with_phase=False): """Separate a complex-valued spectrogram D into its magnitude (S) and phase (P) components, so that D = S * P. Args: audio (np.ndarray): The input audio signal. with_phase (bool): Determines whether t...
Separate a complex-valued spectrogram D into its magnitude (S) and phase (P) components, so that D = S * P. Args: audio (np.ndarray): The input audio signal. with_phase (bool): Determines whether to output the phase components. Default: False. Retur...
generate_spectrogram_magphase
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def adjust_time_resolution(self, quantized, mel): """Adjust time resolution by repeating features. Args: quantized (np.ndarray): (T,) mel (np.ndarray): (N, D) Returns: tuple: Tuple of (T,) and (T, D) """ assert quantized.ndim == 1 ass...
Adjust time resolution by repeating features. Args: quantized (np.ndarray): (T,) mel (np.ndarray): (N, D) Returns: tuple: Tuple of (T,) and (T, D)
adjust_time_resolution
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def start_and_end_indices(quantized, silence_threshold=2): """Trim the audio file when reaches the silence threshold.""" for start in range(quantized.size): if abs(quantized[start] - 127) > silence_threshold: break for end in range(quantized.size - 1, 1, -1): ...
Trim the audio file when reaches the silence threshold.
start_and_end_indices
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def lws_num_frames(length, fsize, fshift): """Compute number of time frames of lws spectrogram. Please refer to <https://pypi.org/project/lws/1.2.6/>`_. """ pad = (fsize - fshift) if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: ...
Compute number of time frames of lws spectrogram. Please refer to <https://pypi.org/project/lws/1.2.6/>`_.
lws_num_frames
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def lws_pad_lr(self, x, fsize, fshift): """Compute left and right padding lws internally uses. Please refer to <https://pypi.org/project/lws/1.2.6/>`_. """ M = self.lws_num_frames(len(x), fsize, fshift) pad = (fsize - fshift) T = len(x) + 2 * pad r = (M - 1) * fs...
Compute left and right padding lws internally uses. Please refer to <https://pypi.org/project/lws/1.2.6/>`_.
lws_pad_lr
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def _linear_to_mel(self, spectrogram): """Warp linear scale spectrograms to the mel scale. Please refer to <https://github.com/r9y9/deepvoice3_pytorch>`_ """ global _mel_basis _mel_basis = self._build_mel_basis() return np.dot(_mel_basis, spectrogram)
Warp linear scale spectrograms to the mel scale. Please refer to <https://github.com/r9y9/deepvoice3_pytorch>`_
_linear_to_mel
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def _build_mel_basis(self): """Build mel filters. Please refer to <https://github.com/r9y9/deepvoice3_pytorch>`_ """ assert self.fmax <= self.sample_rate // 2 return librosa.filters.mel( self.sample_rate, self.fft_size, fmin=self.fmin, ...
Build mel filters. Please refer to <https://github.com/r9y9/deepvoice3_pytorch>`_
_build_mel_basis
python
open-mmlab/mmaction2
tools/data/build_audio_features.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_audio_features.py
Apache-2.0
def build_file_list(splits, frame_info, shuffle=False): """Build file list for a certain data split. Args: splits (tuple): Data split to generate file list. frame_info (dict): Dict mapping from frames to path. e.g., 'Skiing/v_Skiing_g18_c02': ('data/ucf101/rawframes/Skiing/v_Skiing_...
Build file list for a certain data split. Args: splits (tuple): Data split to generate file list. frame_info (dict): Dict mapping from frames to path. e.g., 'Skiing/v_Skiing_g18_c02': ('data/ucf101/rawframes/Skiing/v_Skiing_g18_c02', 0, 0). # noqa: E501 shuffle (bool): Whether ...
build_file_list
python
open-mmlab/mmaction2
tools/data/build_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_file_list.py
Apache-2.0
def build_list(split): """Build RGB and Flow file list with a given split. Args: split (list): Split to be generate file list. Returns: tuple[list, list]: (rgb_list, flow_list), rgb_list is the generated file list for rgb, flow_list is the generated ...
Build RGB and Flow file list with a given split. Args: split (list): Split to be generate file list. Returns: tuple[list, list]: (rgb_list, flow_list), rgb_list is the generated file list for rgb, flow_list is the generated file list for flow. ...
build_list
python
open-mmlab/mmaction2
tools/data/build_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_file_list.py
Apache-2.0
def extract_frame(vid_item): """Generate optical flow using dense flow. Args: vid_item (list): Video item containing video full path, video (short) path, video id. Returns: bool: Whether generate optical flow successfully. """ full_path, vid_path, vid_id, method, task, ...
Generate optical flow using dense flow. Args: vid_item (list): Video item containing video full path, video (short) path, video id. Returns: bool: Whether generate optical flow successfully.
extract_frame
python
open-mmlab/mmaction2
tools/data/build_rawframes.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_rawframes.py
Apache-2.0
def encode_video(frame_dir_item): """Encode frames to video using ffmpeg. Args: frame_dir_item (list): Rawframe item containing raw frame directory full path, rawframe directory (short) path, rawframe directory id. Returns: bool: Whether synthesize video successfully. """ ...
Encode frames to video using ffmpeg. Args: frame_dir_item (list): Rawframe item containing raw frame directory full path, rawframe directory (short) path, rawframe directory id. Returns: bool: Whether synthesize video successfully.
encode_video
python
open-mmlab/mmaction2
tools/data/build_videos.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/build_videos.py
Apache-2.0
def process_norm_proposal_file(norm_proposal_file, frame_dict): """Process the normalized proposal file and denormalize it. Args: norm_proposal_file (str): Name of normalized proposal file. frame_dict (dict): Information of frame folders. """ proposal_file = norm_proposal_file.replace('...
Process the normalized proposal file and denormalize it. Args: norm_proposal_file (str): Name of normalized proposal file. frame_dict (dict): Information of frame folders.
process_norm_proposal_file
python
open-mmlab/mmaction2
tools/data/denormalize_proposal_file.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/denormalize_proposal_file.py
Apache-2.0
def extract_audio_wav(line): """Extract the audio wave from video streams using FFMPEG.""" video_id, _ = osp.splitext(osp.basename(line)) video_dir = osp.dirname(line) video_rel_dir = osp.relpath(video_dir, args.root) dst_dir = osp.join(args.dst_root, video_rel_dir) os.popen(f'mkdir -p {dst_dir}...
Extract the audio wave from video streams using FFMPEG.
extract_audio_wav
python
open-mmlab/mmaction2
tools/data/extract_audio.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/extract_audio.py
Apache-2.0
def parse_directory(path, rgb_prefix='img_', flow_x_prefix='flow_x_', flow_y_prefix='flow_y_', level=1): """Parse directories holding extracted frames from standard benchmarks. Args: path (str): Directory path to parse fram...
Parse directories holding extracted frames from standard benchmarks. Args: path (str): Directory path to parse frames. rgb_prefix (str): Prefix of generated rgb frames name. default: 'img_'. flow_x_prefix (str): Prefix of generated flow x name. default: `flow_x_`. ...
parse_directory
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def count_files(directory, prefix_list): """Count file number with a given directory and prefix. Args: directory (str): Data directory to be search. prefix_list (list): List or prefix. Returns: list (int): Number list of the file with the prefix. """...
Count file number with a given directory and prefix. Args: directory (str): Data directory to be search. prefix_list (list): List or prefix. Returns: list (int): Number list of the file with the prefix.
count_files
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_ucf101_splits(level): """Parse UCF-101 dataset into "train", "val", "test" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of UCF-101. """ class_i...
Parse UCF-101 dataset into "train", "val", "test" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of UCF-101.
parse_ucf101_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def line_to_map(line): """A function to map line string to video and label. Args: line (str): A long directory path, which is a text path. Returns: tuple[str, str]: (video, label), video is the video id, label is the video label. """ item...
A function to map line string to video and label. Args: line (str): A long directory path, which is a text path. Returns: tuple[str, str]: (video, label), video is the video id, label is the video label.
line_to_map
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_jester_splits(level): """Parse Jester into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Jester dataset. """ # Read the annota...
Parse Jester into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Jester dataset.
parse_jester_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_sthv1_splits(level): """Parse Something-Something dataset V1 into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Something-Something V1...
Parse Something-Something dataset V1 into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Something-Something V1 dataset.
parse_sthv1_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_sthv2_splits(level): """Parse Something-Something dataset V2 into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Something-Something V2...
Parse Something-Something dataset V2 into "train", "val" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. Returns: list: "train", "val", "test" splits of Something-Something V2 dataset.
parse_sthv2_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_mmit_splits(): """Parse Multi-Moments in Time dataset into "train", "val" splits. Returns: list: "train", "val", "test" splits of Multi-Moments in Time. """ # Read the annotations def line_to_map(x): video = osp.splitext(x[0])[0] labels = [int(digit) for digit in ...
Parse Multi-Moments in Time dataset into "train", "val" splits. Returns: list: "train", "val", "test" splits of Multi-Moments in Time.
parse_mmit_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_kinetics_splits(level, dataset): """Parse Kinetics dataset into "train", "val", "test" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. dataset (str): Denotes the version of Kinetics that needs to be parse...
Parse Kinetics dataset into "train", "val", "test" splits. Args: level (int): Directory level of data. 1 for the single-level directory, 2 for the two-level directory. dataset (str): Denotes the version of Kinetics that needs to be parsed, choices are "kinetics400", "kinetic...
parse_kinetics_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def convert_label(s, keep_whitespaces=False): """Convert label name to a formal string. Remove redundant '"' and convert whitespace to '_'. Args: s (str): String to be converted. keep_whitespaces(bool): Whether to keep whitespace. Default: False. Returns: ...
Convert label name to a formal string. Remove redundant '"' and convert whitespace to '_'. Args: s (str): String to be converted. keep_whitespaces(bool): Whether to keep whitespace. Default: False. Returns: str: Converted string.
convert_label
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def line_to_map(x, test=False): """A function to map line string to video and label. Args: x (str): A single line from Kinetics csv file. test (bool): Indicate whether the line comes from test annotation file. Returns: tuple[str, str]: (video...
A function to map line string to video and label. Args: x (str): A single line from Kinetics csv file. test (bool): Indicate whether the line comes from test annotation file. Returns: tuple[str, str]: (video, label), video is the video id, ...
line_to_map
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def parse_mit_splits(): """Parse Moments in Time dataset into "train", "val" splits. Returns: list: "train", "val", "test" splits of Moments in Time. """ # Read the annotations class_mapping = {} with open('data/mit/annotations/moments_categories.txt') as f_cat: for line in f_ca...
Parse Moments in Time dataset into "train", "val" splits. Returns: list: "train", "val", "test" splits of Moments in Time.
parse_mit_splits
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def generate_class_index_file(): """This function will generate a `ClassInd.txt` for HMDB51 in a format like UCF101, where class id starts with 1.""" video_path = 'data/hmdb51/videos' annotation_dir = 'data/hmdb51/annotations' class_list = sorted(os.listdir(video_path)) ...
This function will generate a `ClassInd.txt` for HMDB51 in a format like UCF101, where class id starts with 1.
generate_class_index_file
python
open-mmlab/mmaction2
tools/data/parse_file_list.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/parse_file_list.py
Apache-2.0
def resize_videos(vid_item): """Generate resized video cache. Args: vid_item (list): Video item containing video full path, video relative path. Returns: bool: Whether generate video cache successfully. """ full_path, vid_path = vid_item # Change the output video ex...
Generate resized video cache. Args: vid_item (list): Video item containing video full path, video relative path. Returns: bool: Whether generate video cache successfully.
resize_videos
python
open-mmlab/mmaction2
tools/data/resize_videos.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/resize_videos.py
Apache-2.0
def pool_feature(data, num_proposals=100, num_sample_bins=3, pool_type='mean'): """Pool features with arbitrary temporal length. Args: data (list[np.ndarray] | np.ndarray): Features of an untrimmed video, with arbitrary temporal length. num_proposals (int): The temporal dim of poole...
Pool features with arbitrary temporal length. Args: data (list[np.ndarray] | np.ndarray): Features of an untrimmed video, with arbitrary temporal length. num_proposals (int): The temporal dim of pooled feature. Default: 100. num_sample_bins (int): How many points to sample to ge...
pool_feature
python
open-mmlab/mmaction2
tools/data/activitynet/activitynet_feature_postprocessing.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/activitynet/activitynet_feature_postprocessing.py
Apache-2.0
def load_annotations(ann_file): """Load the annotation according to ann_file into video_infos.""" video_infos = [] anno_database = mmengine.load(ann_file) for video_name in anno_database: video_info = anno_database[video_name] video_info['video_name'] = video_name video_infos.app...
Load the annotation according to ann_file into video_infos.
load_annotations
python
open-mmlab/mmaction2
tools/data/activitynet/convert_proposal_format.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/activitynet/convert_proposal_format.py
Apache-2.0
def dump_formatted_proposal(video_idx, video_id, num_frames, fps, gts, proposals, tiou, t_overlap_self, formatted_proposal_file): """dump the formatted proposal file, which is the input proposal file of action classifier (e.g: SSN). Args: vide...
dump the formatted proposal file, which is the input proposal file of action classifier (e.g: SSN). Args: video_idx (int): Index of video. video_id (str): ID of video. num_frames (int): Total frames of the video. fps (float): Fps of the video. gts (np.ndarray[float]): t_...
dump_formatted_proposal
python
open-mmlab/mmaction2
tools/data/activitynet/convert_proposal_format.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/activitynet/convert_proposal_format.py
Apache-2.0
def download_clip(video_identifier, output_filename, num_attempts=5, url_base='https://www.youtube.com/watch?v='): """Download a video from youtube if exists and is not blocked. arguments: --------- video_identifier: str Unique YouTube video ...
Download a video from youtube if exists and is not blocked. arguments: --------- video_identifier: str Unique YouTube video identifier (11 characters) output_filename: str File path where the video will be stored.
download_clip
python
open-mmlab/mmaction2
tools/data/activitynet/download.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/activitynet/download.py
Apache-2.0
def parse_activitynet_annotations(input_csv, is_bsn_case=False): """Returns a list of YoutubeID. arguments: --------- input_csv: str Path to CSV file containing the following columns: 'video,numFrame,seconds,fps,rfps,subset,featureFrame' returns: ------- youtube_ids: list ...
Returns a list of YoutubeID. arguments: --------- input_csv: str Path to CSV file containing the following columns: 'video,numFrame,seconds,fps,rfps,subset,featureFrame' returns: ------- youtube_ids: list List of all YoutubeIDs in ActivityNet.
parse_activitynet_annotations
python
open-mmlab/mmaction2
tools/data/activitynet/download.py
https://github.com/open-mmlab/mmaction2/blob/master/tools/data/activitynet/download.py
Apache-2.0