The ViTPose model was proposed in ViTPose: Simple Vision Transformer Baselines for Human Pose Estimation by Yufei Xu, Jing Zhang, Qiming Zhang, Dacheng Tao. ViTPose employs a standard, non-hierarchical Vision Transformer as backbone for the task of keypoint estimation. A simple decoder head is added on top to predict the heatmaps from a given image. Despite its simplicity, the model gets state-of-the-art results on the challenging MS COCO Keypoint Detection benchmark.
The abstract from the paper is the following:
Although no specific domain knowledge is considered in the design, plain vision transformers have shown excellent performance in visual recognition tasks. However, little effort has been made to reveal the potential of such simple structures for pose estimation tasks. In this paper, we show the surprisingly good capabilities of plain vision transformers for pose estimation from various aspects, namely simplicity in model structure, scalability in model size, flexibility in training paradigm, and transferability of knowledge between models, through a simple baseline model called ViTPose. Specifically, ViTPose employs plain and non-hierarchical vision transformers as backbones to extract features for a given person instance and a lightweight decoder for pose estimation. It can be scaled up from 100M to 1B parameters by taking the advantages of the scalable model capacity and high parallelism of transformers, setting a new Pareto front between throughput and performance. Besides, ViTPose is very flexible regarding the attention type, input resolution, pre-training and finetuning strategy, as well as dealing with multiple pose tasks. We also empirically demonstrate that the knowledge of large ViTPose models can be easily transferred to small ones via a simple knowledge token. Experimental results show that our basic ViTPose model outperforms representative methods on the challenging MS COCO Keypoint Detection benchmark, while the largest model sets a new state-of-the-art.
This model was contributed by nielsr. The original code can be found here.
( do_affine_transform: bool = True size: Dict = None do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_normalize: bool = True image_mean: Union = None image_std: Union = None **kwargs )
Parameters
bool
, optional, defaults to True
) —
Whether to apply an affine transformation to the input images. Dict[str, int]
optional, defaults to {"height" -- 256, "width": 192}
):
Resolution of the image after affine_transform
is applied. Only has an effect if do_affine_transform
is set to True
. Can
be overriden by size
in the preprocess
method. bool
, optional, defaults to True
) —
Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). int
or float
, optional, defaults to 1/255
) —
Scale factor to use if rescaling the image. Can be overriden by rescale_factor
in the preprocess
method. bool
, optional, defaults to True
) —
Whether or not to normalize the input with mean and standard deviation. List[int]
, defaults to [0.485, 0.456, 0.406]
, optional) —
The sequence of means for each channel, to be used when normalizing images. List[int]
, defaults to [0.229, 0.224, 0.225]
, optional) —
The sequence of standard deviations for each channel, to be used when normalizing images. Constructs a ViTPose image processor.
( images: Union boxes: List do_affine_transform: bool = None size: Dict = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: Union = None image_std: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None ) → BatchFeature
Parameters
ImageInput
) —
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set do_rescale=False
. List[List[float]]
) —
List of bounding boxes for each image. Each box should be a list of 4 floats representing the bounding
box coordinates in COCO format (x, y, w, h). bool
, optional, defaults to self.do_affine_transform
) —
Whether to apply an affine transformation to the input images. Dict[str, int]
optional, defaults to self.size
) —
Dictionary in the format {"height": h, "width": w}
specifying the size of the output image after
resizing. bool
, optional, defaults to self.do_rescale
) —
Whether to rescale the image values between [0 - 1]. float
, optional, defaults to self.rescale_factor
) —
Rescale factor to rescale the image by if do_rescale
is set to True
. bool
, optional, defaults to self.do_normalize
) —
Whether to normalize the image. float
or List[float]
, optional, defaults to self.image_mean
) —
Image mean to use if do_normalize
is set to True
. float
or List[float]
, optional, defaults to self.image_std
) —
Image standard deviation to use if do_normalize
is set to True
. str
or TensorType, optional, defaults to 'np'
) —
If set, will return tensors of a particular framework. Acceptable values are:
'tf'
: Return TensorFlow tf.constant
objects.'pt'
: Return PyTorch torch.Tensor
objects.'np'
: Return NumPy np.ndarray
objects.'jax'
: Return JAX jnp.ndarray
objects.Returns
A BatchFeature with the following fields:
Preprocess an image or batch of images.
( backbone_config: PretrainedConfig = None backbone: str = None use_pretrained_backbone: bool = False use_timm_backbone: bool = False backbone_kwargs: dict = None initializer_range: float = 0.02 scale_factor: int = 4 use_simple_decoder: bool = True **kwargs )
Parameters
PretrainedConfig
or dict
, optional, defaults to VitPoseBackboneConfig()
) —
The configuration of the backbone model. str
, optional) —
Name of backbone to use when backbone_config
is None
. If use_pretrained_backbone
is True
, this
will load the corresponding pretrained weights from the timm or transformers library. If use_pretrained_backbone
is False
, this loads the backbone’s config and uses that to initialize the backbone with random weights. bool
, optional, defaults to False
) —
Whether to use pretrained weights for the backbone. bool
, optional, defaults to False
) —
Whether to load backbone
from the timm library. If False
, the backbone is loaded from the transformers
library. dict
, optional) —
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. {'out_indices': (0, 1, 2, 3)}
. Cannot be specified if backbone_config
is set. float
, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. int
, optional, defaults to 4) —
Factor to upscale the feature maps coming from the ViT backbone. bool
, optional, defaults to True
) —
Whether to use a simple decoder to decode the feature maps from the backbone into heatmaps. This is the configuration class to store the configuration of a ViTPoseForPoseEstimation. It is used to instantiate a ViTPose model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the ViTPose google/vitpose-base-patch16-224 architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Example:
>>> from transformers import ViTPoseConfig, ViTPoseForPoseEstimation
>>> # Initializing a ViTPose configuration
>>> configuration = ViTPoseConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = ViTPoseForPoseEstimation(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
( config: ViTPoseConfig )
Parameters
The ViTPose model with a pose estimation head on top. This model is a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( pixel_values: Tensor dataset_index: Optional = None flip_pairs: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.vitpose.modeling_vitpose.PoseEstimatorOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel values. Pixel values can be obtained using ViTPoseImageProcessor. See
ViTPoseImageProcessor.call() for details. torch.Tensor
of shape (batch_size,)
) —
Index to use in the Mixture-of-Experts (MoE) blocks of the backbone.
This corresponds to the dataset index used during training, e.g. index 0 refers to COCO.
torch.tensor
, optional) —
Pairs of keypoints which are mirrored (for example, left ear — right ear). bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.models.vitpose.modeling_vitpose.PoseEstimatorOutput
or tuple(torch.FloatTensor)
A transformers.models.vitpose.modeling_vitpose.PoseEstimatorOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (ViTPoseConfig) and inputs.
loss (torch.FloatTensor
of shape (1,)
, optional, returned when labels
is provided) — Classification (or regression if config.num_labels==1) loss.
heatmaps (torch.FloatTensor
of shape (batch_size, num_keypoints, height, width)
) — Heatmaps as predicted by the model.
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each stage) of shape (batch_size, sequence_length, hidden_size)
. Hidden-states
(also called feature maps) of the model at the output of each stage.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, patch_size, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The ViTPoseForPoseEstimation forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import AutoImageProcessor, ViTPoseForPoseEstimation
>>> import torch
>>> from PIL import Image
>>> import requests
>>> processor = AutoImageProcessor.from_pretrained("")
>>> model = ViTPoseForPoseEstimation.from_pretrained("")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> boxes = [[[412.8, 157.61, 53.05, 138.01], [384.43, 172.21, 15.12, 35.74]]]
>>> inputs = processor(image, boxes=boxes, return_tensors="pt")
>>> outputs = model(**inputs)
>>> heatmaps = outputs.heatmaps