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 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 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 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 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 _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 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_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 |
def get_kinetics_frames(kinetics_anotation_file: str) -> dict:
"""Given the AVA-kinetics anotation file, return a lookup to map the video
id and the the set of timestamps involved of this video id.
Args:
kinetics_anotation_file (str): Path to the AVA-like anotation file for
the kinetics... | Given the AVA-kinetics anotation file, return a lookup to map the video
id and the the set of timestamps involved of this video id.
Args:
kinetics_anotation_file (str): Path to the AVA-like anotation file for
the kinetics subset.
Returns:
dict: the dict keys are the kinetics vid... | get_kinetics_frames | python | open-mmlab/mmaction2 | tools/data/ava_kinetics/cut_kinetics.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/ava_kinetics/cut_kinetics.py | Apache-2.0 |
def filter_missing_videos(kinetics_list: str, frame_lookup: dict) -> dict:
"""Given the kinetics700 dataset list, remove the video ids from the lookup
that are missing videos or frames.
Args:
kinetics_list (str): Path to the kinetics700 dataset list.
The content of the list should be:
... | Given the kinetics700 dataset list, remove the video ids from the lookup
that are missing videos or frames.
Args:
kinetics_list (str): Path to the kinetics700 dataset list.
The content of the list should be:
```
Path_to_video1 label_1
Path_to... | filter_missing_videos | python | open-mmlab/mmaction2 | tools/data/ava_kinetics/cut_kinetics.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/ava_kinetics/cut_kinetics.py | Apache-2.0 |
def remove_failed_video(video_path: str) -> None:
"""Given the path to the video, delete the video if it cannot be read or if
the actual length of the video is 0.75 seconds shorter than expected."""
try:
v = decord.VideoReader(video_path)
fps = v.get_avg_fps()
num_frames = len(v)
... | Given the path to the video, delete the video if it cannot be read or if
the actual length of the video is 0.75 seconds shorter than expected. | remove_failed_video | python | open-mmlab/mmaction2 | tools/data/ava_kinetics/cut_kinetics.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/ava_kinetics/cut_kinetics.py | Apache-2.0 |
def construct_video_filename(item, trim_format, output_dir):
"""Given a dataset row, this function constructs the output filename for a
given video."""
youtube_id, start_time, end_time = item
start_time, end_time = int(start_time * 10), int(end_time * 10)
basename = '%s_%s_%s.mp4' % (youtube_id, tri... | Given a dataset row, this function constructs the output filename for a
given video. | construct_video_filename | python | open-mmlab/mmaction2 | tools/data/hvu/download.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/hvu/download.py | Apache-2.0 |
def download_clip(video_identifier,
output_filename,
start_time,
end_time,
tmp_dir='/tmp/hvu/.tmp_dir',
num_attempts=5,
url_base='https://www.youtube.com/watch?v='):
"""Download a video from youtube if exists... | 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.
start_time: float
Indicates the beginning time in seconds from... | download_clip | python | open-mmlab/mmaction2 | tools/data/hvu/download.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/hvu/download.py | Apache-2.0 |
def parse_hvu_annotations(input_csv):
"""Returns a parsed DataFrame.
arguments:
---------
input_csv: str
Path to CSV file containing the following columns:
'Tags, youtube_id, time_start, time_end'
returns:
-------
dataset: List of tuples. Each tuple consists of
(you... | Returns a parsed DataFrame.
arguments:
---------
input_csv: str
Path to CSV file containing the following columns:
'Tags, youtube_id, time_start, time_end'
returns:
-------
dataset: List of tuples. Each tuple consists of
(youtube_id, time_start, time_end). The type of t... | parse_hvu_annotations | python | open-mmlab/mmaction2 | tools/data/hvu/download.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/hvu/download.py | Apache-2.0 |
def create_video_folders(dataset, output_dir, tmp_dir):
"""Creates a directory for each label name in the dataset."""
if 'label-name' not in dataset.columns:
this_dir = os.path.join(output_dir, 'test')
if not os.path.exists(this_dir):
os.makedirs(this_dir)
# I should return a... | Creates a directory for each label name in the dataset. | create_video_folders | python | open-mmlab/mmaction2 | tools/data/kinetics/download.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/kinetics/download.py | Apache-2.0 |
def parse_kinetics_annotations(input_csv, ignore_is_cc=False):
"""Returns a parsed DataFrame.
arguments:
---------
input_csv: str
Path to CSV file containing the following columns:
'YouTube Identifier,Start time,End time,Class label'
returns:
-------
dataset: DataFrame
... | Returns a parsed DataFrame.
arguments:
---------
input_csv: str
Path to CSV file containing the following columns:
'YouTube Identifier,Start time,End time,Class label'
returns:
-------
dataset: DataFrame
Pandas with the following columns:
'video-id', 'start-... | parse_kinetics_annotations | python | open-mmlab/mmaction2 | tools/data/kinetics/download.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/kinetics/download.py | Apache-2.0 |
def _compress_images(input_output_pair, size=224):
"""Scale and downsample an input image to a given fps and size (shorter
side size).
This also removes the audio from the image.
"""
input_image_path, output_image_path = input_output_pair
try:
resize_image(input_image_path, output_image... | Scale and downsample an input image to a given fps and size (shorter
side size).
This also removes the audio from the image.
| _compress_images | python | open-mmlab/mmaction2 | tools/data/msrvtt/compress.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/msrvtt/compress.py | Apache-2.0 |
def _compress_videos(input_output_pair, size=224, fps=3):
"""Scale and downsample an input video to a given fps and size (shorter
side size).
This also removes the audio from the video.
"""
input_file_path, output_file_path = input_output_pair
try:
command = [
'ffmpeg',
... | Scale and downsample an input video to a given fps and size (shorter
side size).
This also removes the audio from the video.
| _compress_videos | python | open-mmlab/mmaction2 | tools/data/msrvtt/compress.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/msrvtt/compress.py | Apache-2.0 |
def format_det_result():
"""convert test results to specified format in MultiSports competition."""
test_results = load(args.test_result)
annos = load(args.anno_path)
test_videos = annos['test_videos'][0]
resolutions = annos['resolution']
frm_dets = []
for pred in track(test_results, descrip... | convert test results to specified format in MultiSports competition. | format_det_result | python | open-mmlab/mmaction2 | tools/data/multisports/format_det_result.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/data/multisports/format_det_result.py | Apache-2.0 |
def mmaction2torchserve(
config_file: str,
checkpoint_file: str,
output_folder: str,
model_name: str,
label_file: str,
model_version: str = '1.0',
force: bool = False,
):
"""Converts MMAction2 model (config + checkpoint) to TorchServe `.mar`.
Args:
config_file (str): In MMAc... | Converts MMAction2 model (config + checkpoint) to TorchServe `.mar`.
Args:
config_file (str): In MMAction2 config format.
checkpoint_file (str): In MMAction2 checkpoint format.
output_folder (str): Folder where `{model_name}.mar` will be created.
The file created will be in Torc... | mmaction2torchserve | python | open-mmlab/mmaction2 | tools/deployment/mmaction2torchserve.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/deployment/mmaction2torchserve.py | Apache-2.0 |
def load_video_infos(ann_file):
"""Load the video annotations.
Args:
ann_file (str): A json file path of the annotation file.
Returns:
list[dict]: A list containing annotations for videos.
"""
video_infos = []
anno_database = mmengine.load(ann_file)
for video_name in anno_d... | Load the video annotations.
Args:
ann_file (str): A json file path of the annotation file.
Returns:
list[dict]: A list containing annotations for videos.
| load_video_infos | python | open-mmlab/mmaction2 | tools/misc/bsn_proposal_generation.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/misc/bsn_proposal_generation.py | Apache-2.0 |
def generate_proposals(ann_file, tem_results_dir, pgm_proposals_dir,
pgm_proposals_thread, **kwargs):
"""Generate proposals using multi-process.
Args:
ann_file (str): A json file path of the annotation file for
all videos to be processed.
tem_results_dir (str)... | Generate proposals using multi-process.
Args:
ann_file (str): A json file path of the annotation file for
all videos to be processed.
tem_results_dir (str): Directory to read tem results
pgm_proposals_dir (str): Directory to save generated proposals.
pgm_proposals_thread... | generate_proposals | python | open-mmlab/mmaction2 | tools/misc/bsn_proposal_generation.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/misc/bsn_proposal_generation.py | Apache-2.0 |
def generate_features(ann_file, tem_results_dir, pgm_proposals_dir,
pgm_features_dir, pgm_features_thread, **kwargs):
"""Generate proposals features using multi-process.
Args:
ann_file (str): A json file path of the annotation file for
all videos to be processed.
... | Generate proposals features using multi-process.
Args:
ann_file (str): A json file path of the annotation file for
all videos to be processed.
tem_results_dir (str): Directory to read tem results.
pgm_proposals_dir (str): Directory to read generated proposals.
pgm_featur... | generate_features | python | open-mmlab/mmaction2 | tools/misc/bsn_proposal_generation.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/misc/bsn_proposal_generation.py | Apache-2.0 |
def flow_to_img(raw_flow, bound=20.):
"""Convert flow to gray image.
Args:
raw_flow (np.ndarray[float]): Estimated flow with the shape (w, h).
bound (float): Bound for the flow-to-image normalization. Default: 20.
Returns:
np.ndarray[uint8]: The result list of np.ndarray[uint8], wi... | Convert flow to gray image.
Args:
raw_flow (np.ndarray[float]): Estimated flow with the shape (w, h).
bound (float): Bound for the flow-to-image normalization. Default: 20.
Returns:
np.ndarray[uint8]: The result list of np.ndarray[uint8], with shape
(w, h).
| flow_to_img | python | open-mmlab/mmaction2 | tools/misc/flow_extraction.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/misc/flow_extraction.py | Apache-2.0 |
def generate_flow(frames, method='tvl1'):
"""Estimate flow with given frames.
Args:
frames (list[np.ndarray[uint8]]): List of rgb frames, with shape
(w, h, 3).
method (str): Use which method to generate flow. Options are 'tvl1'
and 'fa... | Estimate flow with given frames.
Args:
frames (list[np.ndarray[uint8]]): List of rgb frames, with shape
(w, h, 3).
method (str): Use which method to generate flow. Options are 'tvl1'
and 'farneback'. Default: 'tvl1'.
Returns:
... | generate_flow | python | open-mmlab/mmaction2 | tools/misc/flow_extraction.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/misc/flow_extraction.py | Apache-2.0 |
def extract_dense_flow(path,
dest,
bound=20.,
save_rgb=False,
start_idx=0,
rgb_tmpl='img_{:05d}.jpg',
flow_tmpl='{}_{:05d}.jpg',
method='tvl1'):
"""Extract... | Extract dense flow given video or frames, save them as gray-scale
images.
Args:
path (str): Location of the input video.
dest (str): The directory to store the extracted flow images.
bound (float): Bound for the flow-to-image normalization. Default: 20.
save_rgb (bool): Save ext... | extract_dense_flow | python | open-mmlab/mmaction2 | tools/misc/flow_extraction.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/misc/flow_extraction.py | Apache-2.0 |
def build_inputs(model: nn.Module,
video_path: str,
use_frames: bool = False) -> Dict:
"""build inputs for GradCAM.
Note that, building inputs for GradCAM is exactly the same as building
inputs for Recognizer test stage. Codes from `inference_recognizer`.
Args:
... | build inputs for GradCAM.
Note that, building inputs for GradCAM is exactly the same as building
inputs for Recognizer test stage. Codes from `inference_recognizer`.
Args:
model (nn.Module): Recognizer model.
video_path (str): video file/url or rawframes directory.
use_frames (bool... | build_inputs | python | open-mmlab/mmaction2 | tools/visualizations/vis_cam.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/visualizations/vis_cam.py | Apache-2.0 |
def _resize_frames(frame_list: List[np.ndarray],
scale: Optional[Tuple[int]] = None,
keep_ratio: bool = True,
interpolation: str = 'bilinear') -> List[np.ndarray]:
"""Resize frames according to given scale.
Codes are modified from `mmaction/datasets/tran... | Resize frames according to given scale.
Codes are modified from `mmaction/datasets/transforms/processing.py`,
`Resize` class.
Args:
frame_list (list[np.ndarray]): Frames to be resized.
scale (tuple[int]): If keep_ratio is True, it serves as scaling
factor or maximum size: the i... | _resize_frames | python | open-mmlab/mmaction2 | tools/visualizations/vis_cam.py | https://github.com/open-mmlab/mmaction2/blob/master/tools/visualizations/vis_cam.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.