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 split_coeff(self, coeffs):
"""
Return:
coeffs_dict -- a dict of torch.tensors
Parameters:
coeffs -- torch.tensor, size (B, 256)
"""
id_coeffs = coeffs[:, :80]
exp_coeffs = coeffs[:, 80: 144]
tex_coeffs = coeffs[:, 144: 224... |
Return:
coeffs_dict -- a dict of torch.tensors
Parameters:
coeffs -- torch.tensor, size (B, 256)
| split_coeff | python | OpenTalker/video-retalking | third_part/face3d/models/bfm.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py | Apache-2.0 |
def compute_for_render(self, coeffs):
"""
Return:
face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate
face_color -- torch.tensor, size (B, N, 3), in RGB order
landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v directi... |
Return:
face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate
face_color -- torch.tensor, size (B, N, 3), in RGB order
landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v direction
Parameters:
coeffs ... | compute_for_render | python | OpenTalker/video-retalking | third_part/face3d/models/bfm.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py | Apache-2.0 |
def modify_commandline_options(parser, is_train=True):
""" Configures options specific for CUT model
"""
# net structure and parameters
parser.add_argument('--net_recon', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50'], help='network structure')
parser... | Configures options specific for CUT model
| modify_commandline_options | python | OpenTalker/video-retalking | third_part/face3d/models/facerecon_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py | Apache-2.0 |
def __init__(self, opt):
"""Initialize this model class.
Parameters:
opt -- training/test options
A few things can be done here.
- (required) call the initialization function of BaseModel
- define loss function, visualization images, model names, and optimizers
... | Initialize this model class.
Parameters:
opt -- training/test options
A few things can be done here.
- (required) call the initialization function of BaseModel
- define loss function, visualization images, model names, and optimizers
| __init__ | python | OpenTalker/video-retalking | third_part/face3d/models/facerecon_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py | Apache-2.0 |
def set_input(self, input):
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
Parameters:
input: a dictionary that contains the data itself and its metadata information.
"""
self.input_img = input['imgs'].to(self.device)
self.atten... | Unpack input data from the dataloader and perform necessary pre-processing steps.
Parameters:
input: a dictionary that contains the data itself and its metadata information.
| set_input | python | OpenTalker/video-retalking | third_part/face3d/models/facerecon_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py | Apache-2.0 |
def compute_losses(self):
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
assert self.net_recog.training == False
trans_m = self.trans_m
if not self.opt.use_predef_M:
trans_m = estimate_norm_torch(self.pred_lm, self.input_img... | Calculate losses, gradients, and update network weights; called in every training iteration | compute_losses | python | OpenTalker/video-retalking | third_part/face3d/models/facerecon_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py | Apache-2.0 |
def forward(imageA, imageB, M):
"""
1 - cosine distance
Parameters:
imageA --torch.tensor (B, 3, H, W), range (0, 1) , RGB order
imageB --same as imageA
"""
imageA = self.preprocess(resize_n_crop(imageA, M, self.input_size))
imageB = s... |
1 - cosine distance
Parameters:
imageA --torch.tensor (B, 3, H, W), range (0, 1) , RGB order
imageB --same as imageA
| forward | python | OpenTalker/video-retalking | third_part/face3d/models/losses.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py | Apache-2.0 |
def photo_loss(imageA, imageB, mask, eps=1e-6):
"""
l2 norm (with sqrt, to ensure backward stabililty, use eps, otherwise Nan may occur)
Parameters:
imageA --torch.tensor (B, 3, H, W), range (0, 1), RGB order
imageB --same as imageA
"""
loss = torch.sqrt(eps + torch.sum(... |
l2 norm (with sqrt, to ensure backward stabililty, use eps, otherwise Nan may occur)
Parameters:
imageA --torch.tensor (B, 3, H, W), range (0, 1), RGB order
imageB --same as imageA
| photo_loss | python | OpenTalker/video-retalking | third_part/face3d/models/losses.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py | Apache-2.0 |
def landmark_loss(predict_lm, gt_lm, weight=None):
"""
weighted mse loss
Parameters:
predict_lm --torch.tensor (B, 68, 2)
gt_lm --torch.tensor (B, 68, 2)
weight --numpy.array (1, 68)
"""
if not weight:
weight = np.ones([68])
weight[28:31] = 2... |
weighted mse loss
Parameters:
predict_lm --torch.tensor (B, 68, 2)
gt_lm --torch.tensor (B, 68, 2)
weight --numpy.array (1, 68)
| landmark_loss | python | OpenTalker/video-retalking | third_part/face3d/models/losses.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py | Apache-2.0 |
def reg_loss(coeffs_dict, opt=None):
"""
l2 norm without the sqrt, from yu's implementation (mse)
tf.nn.l2_loss https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss
Parameters:
coeffs_dict -- a dict of torch.tensors , keys: id, exp, tex, angle, gamma, trans
"""
# coefficient re... |
l2 norm without the sqrt, from yu's implementation (mse)
tf.nn.l2_loss https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss
Parameters:
coeffs_dict -- a dict of torch.tensors , keys: id, exp, tex, angle, gamma, trans
| reg_loss | python | OpenTalker/video-retalking | third_part/face3d/models/losses.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py | Apache-2.0 |
def reflectance_loss(texture, mask):
"""
minimize texture variance (mse), albedo regularization to ensure an uniform skin albedo
Parameters:
texture --torch.tensor, (B, N, 3)
mask --torch.tensor, (N), 1 or 0
"""
mask = mask.reshape([1, mask.shape[0], 1])
texture_m... |
minimize texture variance (mse), albedo regularization to ensure an uniform skin albedo
Parameters:
texture --torch.tensor, (B, N, 3)
mask --torch.tensor, (N), 1 or 0
| reflectance_loss | python | OpenTalker/video-retalking | third_part/face3d/models/losses.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py | Apache-2.0 |
def resnext50_32x4d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
r"""ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on Im... | ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext50_32x4d | python | OpenTalker/video-retalking | third_part/face3d/models/networks.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py | Apache-2.0 |
def resnext101_32x8d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
r"""ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ... | ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext101_32x8d | python | OpenTalker/video-retalking | third_part/face3d/models/networks.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py | Apache-2.0 |
def wide_resnet50_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
r"""Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every ... | Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 h... | wide_resnet50_2 | python | OpenTalker/video-retalking | third_part/face3d/models/networks.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py | Apache-2.0 |
def wide_resnet101_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
r"""Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in ever... | Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 ... | wide_resnet101_2 | python | OpenTalker/video-retalking | third_part/face3d/models/networks.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py | Apache-2.0 |
def modify_commandline_options(parser, is_train=True):
"""Add new model-specific options and rewrite default values for existing options.
Parameters:
parser -- the option parser
is_train -- if it is training phase or test phase. You can use this flag to add training-specific or ... | Add new model-specific options and rewrite default values for existing options.
Parameters:
parser -- the option parser
is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options.
Returns:
the modified ... | modify_commandline_options | python | OpenTalker/video-retalking | third_part/face3d/models/template_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py | Apache-2.0 |
def optimize_parameters(self):
"""Update network weights; it will be called in every training iteration."""
self.forward() # first call forward to calculate intermediate results
self.optimizer.zero_grad() # clear network G's existing gradients
self.backward() ... | Update network weights; it will be called in every training iteration. | optimize_parameters | python | OpenTalker/video-retalking | third_part/face3d/models/template_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py | Apache-2.0 |
def find_model_using_name(model_name):
"""Import the module "models/[model_name]_model.py".
In the file, the class called DatasetNameModel() will
be instantiated. It has to be a subclass of BaseModel,
and it is case-insensitive.
"""
model_filename = "face3d.models." + model_name + "_model"
... | Import the module "models/[model_name]_model.py".
In the file, the class called DatasetNameModel() will
be instantiated. It has to be a subclass of BaseModel,
and it is case-insensitive.
| find_model_using_name | python | OpenTalker/video-retalking | third_part/face3d/models/__init__.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/__init__.py | Apache-2.0 |
def create_model(opt):
"""Create a model given the option.
This function warps the class CustomDatasetDataLoader.
This is the main interface between this package and 'train.py'/'test.py'
Example:
>>> from models import create_model
>>> model = create_model(opt)
"""
model = find... | Create a model given the option.
This function warps the class CustomDatasetDataLoader.
This is the main interface between this package and 'train.py'/'test.py'
Example:
>>> from models import create_model
>>> model = create_model(opt)
| create_model | python | OpenTalker/video-retalking | third_part/face3d/models/__init__.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/__init__.py | Apache-2.0 |
def __init__(self, rank, local_rank, world_size, batch_size, resume,
margin_softmax, num_classes, sample_rate=1.0, embedding_size=512, prefix="./"):
"""
rank: int
Unique process(GPU) ID from 0 to world_size - 1.
local_rank: int
Unique process(GPU) ID with... |
rank: int
Unique process(GPU) ID from 0 to world_size - 1.
local_rank: int
Unique process(GPU) ID within the server from 0 to 7.
world_size: int
Number of GPU.
batch_size: int
Batch size on current rank(GPU).
resume: bool
... | __init__ | python | OpenTalker/video-retalking | third_part/face3d/models/arcface_torch/partial_fc.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py | Apache-2.0 |
def sample(self, total_label):
"""
Sample all positive class centers in each rank, and random select neg class centers to filling a fixed
`num_sample`.
total_label: tensor
Label after all gather, which cross all GPUs.
"""
index_positive = (self.class_start <=... |
Sample all positive class centers in each rank, and random select neg class centers to filling a fixed
`num_sample`.
total_label: tensor
Label after all gather, which cross all GPUs.
| sample | python | OpenTalker/video-retalking | third_part/face3d/models/arcface_torch/partial_fc.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py | Apache-2.0 |
def update(self):
""" Set updated weight and weight_mom to memory bank.
"""
self.weight_mom[self.index] = self.sub_weight_mom
self.weight[self.index] = self.sub_weight | Set updated weight and weight_mom to memory bank.
| update | python | OpenTalker/video-retalking | third_part/face3d/models/arcface_torch/partial_fc.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py | Apache-2.0 |
def prepare(self, label, optimizer):
"""
get sampled class centers for cal softmax.
label: tensor
Label tensor on each rank.
optimizer: opt
Optimizer for partial fc, which need to get weight mom.
"""
with torch.cuda.stream(self.stream):
... |
get sampled class centers for cal softmax.
label: tensor
Label tensor on each rank.
optimizer: opt
Optimizer for partial fc, which need to get weight mom.
| prepare | python | OpenTalker/video-retalking | third_part/face3d/models/arcface_torch/partial_fc.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py | Apache-2.0 |
def forward_backward(self, label, features, optimizer):
"""
Partial fc forward and backward with model parallel
label: tensor
Label tensor on each rank(GPU)
features: tensor
Features tensor on each rank(GPU)
optimizer: optimizer
Optimizer for ... |
Partial fc forward and backward with model parallel
label: tensor
Label tensor on each rank(GPU)
features: tensor
Features tensor on each rank(GPU)
optimizer: optimizer
Optimizer for partial fc
Returns:
--------
x_grad: tenso... | forward_backward | python | OpenTalker/video-retalking | third_part/face3d/models/arcface_torch/partial_fc.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py | Apache-2.0 |
def scale(self, outputs):
"""
Multiplies ('scales') a tensor or list of tensors by the scale factor.
Returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, outputs are returned
unmodified.
Arguments:
outputs (Tensor or iterable of Tensors):... |
Multiplies ('scales') a tensor or list of tensors by the scale factor.
Returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, outputs are returned
unmodified.
Arguments:
outputs (Tensor or iterable of Tensors): Outputs to scale.
| scale | python | OpenTalker/video-retalking | third_part/face3d/models/arcface_torch/utils/utils_amp.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/utils/utils_amp.py | Apache-2.0 |
def __init__(self, cmd_line=None):
"""Reset the class; indicates the class hasn't been initialized"""
self.initialized = False
self.cmd_line = None
if cmd_line is not None:
self.cmd_line = cmd_line.split() | Reset the class; indicates the class hasn't been initialized | __init__ | python | OpenTalker/video-retalking | third_part/face3d/options/base_options.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py | Apache-2.0 |
def initialize(self, parser):
"""Define the common options that are used in both training and test."""
# basic parameters
parser.add_argument('--name', type=str, default='face_recon', help='name of the experiment. It decides where to store samples and models')
parser.add_argument('--gpu_... | Define the common options that are used in both training and test. | initialize | python | OpenTalker/video-retalking | third_part/face3d/options/base_options.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py | Apache-2.0 |
def gather_options(self):
"""Initialize our parser with basic options(only once).
Add additional model-specific and dataset-specific options.
These options are defined in the <modify_commandline_options> function
in model and dataset classes.
"""
if not self.initialized: ... | Initialize our parser with basic options(only once).
Add additional model-specific and dataset-specific options.
These options are defined in the <modify_commandline_options> function
in model and dataset classes.
| gather_options | python | OpenTalker/video-retalking | third_part/face3d/options/base_options.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py | Apache-2.0 |
def print_options(self, opt):
"""Print and save options
It will print both current options and default values(if different).
It will save options into a text file / [checkpoints_dir] / opt.txt
"""
message = ''
message += '----------------- Options ---------------\n'
... | Print and save options
It will print both current options and default values(if different).
It will save options into a text file / [checkpoints_dir] / opt.txt
| print_options | python | OpenTalker/video-retalking | third_part/face3d/options/base_options.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py | Apache-2.0 |
def parse(self):
"""Parse our options, create checkpoints directory suffix, and set up gpu device."""
opt = self.gather_options()
opt.isTrain = self.isTrain # train or test
# process opt.suffix
if opt.suffix:
suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.s... | Parse our options, create checkpoints directory suffix, and set up gpu device. | parse | python | OpenTalker/video-retalking | third_part/face3d/options/base_options.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py | Apache-2.0 |
def __init__(self, web_dir, title, refresh=0):
"""Initialize the HTML classes
Parameters:
web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/
title (str) -- the webpage name
... | Initialize the HTML classes
Parameters:
web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/
title (str) -- the webpage name
refresh (int) -- how often the website refresh itself; ... | __init__ | python | OpenTalker/video-retalking | third_part/face3d/util/html.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/html.py | Apache-2.0 |
def add_images(self, ims, txts, links, width=400):
"""add images to the HTML file
Parameters:
ims (str list) -- a list of image paths
txts (str list) -- a list of image names shown on the website
links (str list) -- a list of hyperref links; when you click an ima... | add images to the HTML file
Parameters:
ims (str list) -- a list of image paths
txts (str list) -- a list of image names shown on the website
links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page
| add_images | python | OpenTalker/video-retalking | third_part/face3d/util/html.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/html.py | Apache-2.0 |
def save(self):
"""save the current content to the HTML file"""
html_file = '%s/index.html' % self.web_dir
f = open(html_file, 'wt')
f.write(self.doc.render())
f.close() | save the current content to the HTML file | save | python | OpenTalker/video-retalking | third_part/face3d/util/html.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/html.py | Apache-2.0 |
def forward(self, vertex, tri, feat=None):
"""
Return:
mask -- torch.tensor, size (B, 1, H, W)
depth -- torch.tensor, size (B, 1, H, W)
features(optional) -- torch.tensor, size (B, C, H, W) if feat is not None
Parameters:
... |
Return:
mask -- torch.tensor, size (B, 1, H, W)
depth -- torch.tensor, size (B, 1, H, W)
features(optional) -- torch.tensor, size (B, C, H, W) if feat is not None
Parameters:
vertex -- torch.tensor, size (B, N, 3)
... | forward | python | OpenTalker/video-retalking | third_part/face3d/util/nvdiffrast.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/nvdiffrast.py | Apache-2.0 |
def align_img(img, lm, lm3D, mask=None, target_size=224., rescale_factor=102.):
"""
Return:
transparams --numpy.array (raw_W, raw_H, scale, tx, ty)
img_new --PIL.Image (target_size, target_size, 3)
lm_new --numpy.array (68, 2), y direction is opposite to ... |
Return:
transparams --numpy.array (raw_W, raw_H, scale, tx, ty)
img_new --PIL.Image (target_size, target_size, 3)
lm_new --numpy.array (68, 2), y direction is opposite to v direction
mask_new --PIL.Image (target_size, target_size)
... | align_img | python | OpenTalker/video-retalking | third_part/face3d/util/preprocess.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/preprocess.py | Apache-2.0 |
def estimate_norm(lm_68p, H):
# from https://github.com/deepinsight/insightface/blob/c61d3cd208a603dfa4a338bd743b320ce3e94730/recognition/common/face_align.py#L68
"""
Return:
trans_m --numpy.array (2, 3)
Parameters:
lm --numpy.array (68, 2), y direction is op... |
Return:
trans_m --numpy.array (2, 3)
Parameters:
lm --numpy.array (68, 2), y direction is opposite to v direction
H --int/float , image height
| estimate_norm | python | OpenTalker/video-retalking | third_part/face3d/util/preprocess.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/preprocess.py | Apache-2.0 |
def tensor2im(input_image, imtype=np.uint8):
""""Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input image tensor array, range(0, 1)
imtype (type) -- the desired type of the converted numpy array
"""
if not isinstance(input_image, np.... | "Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input image tensor array, range(0, 1)
imtype (type) -- the desired type of the converted numpy array
| tensor2im | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def diagnose_network(net, name='network'):
"""Calculate and print the mean of average absolute(gradients)
Parameters:
net (torch network) -- Torch network
name (str) -- the name of the network
"""
mean = 0.0
count = 0
for param in net.parameters():
if param.grad is not N... | Calculate and print the mean of average absolute(gradients)
Parameters:
net (torch network) -- Torch network
name (str) -- the name of the network
| diagnose_network | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def save_image(image_numpy, image_path, aspect_ratio=1.0):
"""Save a numpy image to the disk
Parameters:
image_numpy (numpy array) -- input numpy array
image_path (str) -- the path of the image
"""
image_pil = Image.fromarray(image_numpy)
h, w, _ = image_numpy.shape
i... | Save a numpy image to the disk
Parameters:
image_numpy (numpy array) -- input numpy array
image_path (str) -- the path of the image
| save_image | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def print_numpy(x, val=True, shp=False):
"""Print the mean, min, max, median, std, and size of a numpy array
Parameters:
val (bool) -- if print the values of the numpy array
shp (bool) -- if print the shape of the numpy array
"""
x = x.astype(np.float64)
if shp:
print('shape... | Print the mean, min, max, median, std, and size of a numpy array
Parameters:
val (bool) -- if print the values of the numpy array
shp (bool) -- if print the shape of the numpy array
| print_numpy | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def mkdirs(paths):
"""create empty directories if they don't exist
Parameters:
paths (str list) -- a list of directory paths
"""
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths) | create empty directories if they don't exist
Parameters:
paths (str list) -- a list of directory paths
| mkdirs | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def draw_landmarks(img, landmark, color='r', step=2):
"""
Return:
img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255)
Parameters:
img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255)
landmark -- numpy.array,... |
Return:
img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255)
Parameters:
img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255)
landmark -- numpy.array, (B, 68, 2), y direction is opposite to v direction
c... | draw_landmarks | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256):
"""Save images to the disk.
Parameters:
webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
visuals (OrderedDict) -- an ordered dictionary that stores (name, ima... | Save images to the disk.
Parameters:
webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs
image_path (str) -- the string... | save_images | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def __init__(self, opt):
"""Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: create a tensorboard writer
Step 3: create an HTML object for saving ... | Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: create a tensorboard writer
Step 3: create an HTML object for saving HTML filters
Step 4: create ... | __init__ | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def display_current_results(self, visuals, total_iters, epoch, save_result):
"""Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
total_iters (int) -- total iterations
... | Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
total_iters (int) -- total iterations
epoch (int) - - the current epoch
save_result (bool) - - if save the c... | display_current_results | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def print_current_losses(self, epoch, iters, losses, t_comp, t_data):
"""print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
... | print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
losses (OrderedDict) -- training losses stored in the format of (name... | print_current_losses | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def display_current_results(self, visuals, total_iters, epoch, dataset='train', save_results=False, count=0, name=None,
add_image=True):
"""Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to ... | Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
total_iters (int) -- total iterations
epoch (int) - - the current epoch
dataset (str) - - 'train' or 'val' o... | display_current_results | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def transform(point, center, scale, resolution, invert=False):
"""Generate and affine transformation matrix.
Given a set of points, a center, a scale and a targer resolution, the
function generates and affine transformation matrix. If invert is ``True``
it will produce the inverse transformation.
... | Generate and affine transformation matrix.
Given a set of points, a center, a scale and a targer resolution, the
function generates and affine transformation matrix. If invert is ``True``
it will produce the inverse transformation.
Arguments:
point {torch.tensor} -- the input 2D point
... | transform | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def crop(image, center, scale, resolution=256.0):
"""Center crops an image or set of heatmaps
Arguments:
image {numpy.array} -- an rgb image
center {numpy.array} -- the center of the object, usually the same as of the bounding box
scale {float} -- scale of the face
Keyword Argument... | Center crops an image or set of heatmaps
Arguments:
image {numpy.array} -- an rgb image
center {numpy.array} -- the center of the object, usually the same as of the bounding box
scale {float} -- scale of the face
Keyword Arguments:
resolution {float} -- the size of the output c... | crop | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def get_preds_fromhm(hm, center=None, scale=None):
"""Obtain (x,y) coordinates given a set of N heatmaps. If the center
and the scale is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W,... | Obtain (x,y) coordinates given a set of N heatmaps. If the center
and the scale is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W, H]
Keyword Arguments:
center {torch.tensor} ... | get_preds_fromhm | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def get_preds_fromhm_batch(hm, centers=None, scales=None):
"""Obtain (x,y) coordinates given a set of N heatmaps. If the centers
and the scales is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape... | Obtain (x,y) coordinates given a set of N heatmaps. If the centers
and the scales is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W, H]
Keyword Arguments:
centers {torch.tenso... | get_preds_fromhm_batch | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def shuffle_lr(parts, pairs=None):
"""Shuffle the points left-right according to the axis of symmetry
of the object.
Arguments:
parts {torch.tensor} -- a 3D or 4D object containing the
heatmaps.
Keyword Arguments:
pairs {list of integers} -- [order of the flipped points] (defau... | Shuffle the points left-right according to the axis of symmetry
of the object.
Arguments:
parts {torch.tensor} -- a 3D or 4D object containing the
heatmaps.
Keyword Arguments:
pairs {list of integers} -- [order of the flipped points] (default: {None})
| shuffle_lr | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def flip(tensor, is_label=False):
"""Flip an image or a set of heatmaps left-right
Arguments:
tensor {numpy.array or torch.tensor} -- [the input image or heatmaps]
Keyword Arguments:
is_label {bool} -- [denote wherever the input is an image or a set of heatmaps ] (default: {False})
"""... | Flip an image or a set of heatmaps left-right
Arguments:
tensor {numpy.array or torch.tensor} -- [the input image or heatmaps]
Keyword Arguments:
is_label {bool} -- [denote wherever the input is an image or a set of heatmaps ] (default: {False})
| flip | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def appdata_dir(appname=None, roaming=False):
""" appdata_dir(appname=None, roaming=False)
Get the path to the application directory, where applications are allowed
to write user specific files (e.g. configurations). For non-user specific
data, consider using common_appdata_dir().
If appname is giv... | appdata_dir(appname=None, roaming=False)
Get the path to the application directory, where applications are allowed
to write user specific files (e.g. configurations). For non-user specific
data, consider using common_appdata_dir().
If appname is given, a subdir is appended (and created if necessary).
... | appdata_dir | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def detect_from_directory(self, path, extensions=['.jpg', '.png'], recursive=False, show_progress_bar=True):
"""Detects faces from all the images present in a given directory.
Arguments:
path {string} -- a string containing a path that points to the folder containing the images
Key... | Detects faces from all the images present in a given directory.
Arguments:
path {string} -- a string containing a path that points to the folder containing the images
Keyword Arguments:
extensions {list} -- list of string containing the extensions to be
consider in ... | detect_from_directory | python | OpenTalker/video-retalking | third_part/face_detection/detection/core.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/core.py | Apache-2.0 |
def tensor_or_path_to_ndarray(tensor_or_path, rgb=True):
"""Convert path (represented as a string) or torch.tensor to a numpy.ndarray
Arguments:
tensor_or_path {numpy.ndarray, torch.tensor or string} -- path to the image, or the image itself
"""
if isinstance(tensor_or_path,... | Convert path (represented as a string) or torch.tensor to a numpy.ndarray
Arguments:
tensor_or_path {numpy.ndarray, torch.tensor or string} -- path to the image, or the image itself
| tensor_or_path_to_ndarray | python | OpenTalker/video-retalking | third_part/face_detection/detection/core.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/core.py | Apache-2.0 |
def encode(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
... | Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
priors: (tensor) Prior boxes in center-offset... | encode | python | OpenTalker/video-retalking | third_part/face_detection/detection/sfd/bbox.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/sfd/bbox.py | Apache-2.0 |
def decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form... | Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
... | decode | python | OpenTalker/video-retalking | third_part/face_detection/detection/sfd/bbox.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/sfd/bbox.py | Apache-2.0 |
def get_norm_layer(norm_type='instance'):
"""Return a normalization layer
Parameters:
norm_type (str) -- the name of the normalization layer: batch | instance | none
For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
For InstanceNorm, we do not use lear... | Return a normalization layer
Parameters:
norm_type (str) -- the name of the normalization layer: batch | instance | none
For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
For InstanceNorm, we do not use learnable affine parameters. We do not track running ... | get_norm_layer | python | OpenTalker/video-retalking | third_part/ganimation_replicate/model/model_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/ganimation_replicate/model/model_utils.py | Apache-2.0 |
def forward(self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
... | Forward function for StyleGAN2GeneratorSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or ... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | Apache-2.0 |
def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):
"""Forward function for GFPGANv1.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate... | Forward function for GFPGANv1.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate rgb images. Default: True.
randomize_noise (bool): Randomize noise, used when 'no... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | Apache-2.0 |
def forward(self, x, return_feats=False):
"""Forward function for FacialComponentDiscriminator.
Args:
x (Tensor): Input images.
return_feats (bool): Whether to return intermediate features. Default: False.
"""
feat = self.conv1(x)
feat = self.conv3(self.c... | Forward function for FacialComponentDiscriminator.
Args:
x (Tensor): Input images.
return_feats (bool): Whether to return intermediate features. Default: False.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | Apache-2.0 |
def forward(self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
... | Forward function for StyleGAN2GeneratorCSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | Apache-2.0 |
def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):
"""Forward function for GFPGANv1Clean.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return interme... | Forward function for GFPGANv1Clean.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate rgb images. Default: True.
randomize_noise (bool): Randomize noise, used whe... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | Apache-2.0 |
def forward(self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
... | Forward function for StyleGAN2GeneratorBilinearSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input n... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | Apache-2.0 |
def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):
"""Forward function for GFPGANBilinear.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return interm... | Forward function for GFPGANBilinear.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate rgb images. Default: True.
randomize_noise (bool): Randomize noise, used wh... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | Apache-2.0 |
def forward(self, x, style):
"""Forward function.
Args:
x (Tensor): Tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
Returns:
Tensor: Modulated tensor after convolution.
"""
b, c, h, w = x.shape # c = c_... | Forward function.
Args:
x (Tensor): Tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
Returns:
Tensor: Modulated tensor after convolution.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | Apache-2.0 |
def forward(self, x, style, skip=None):
"""Forward function.
Args:
x (Tensor): Feature tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
skip (Tensor): Base/skip tensor. Default: None.
Returns:
Tensor: RGB ima... | Forward function.
Args:
x (Tensor): Feature tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
skip (Tensor): Base/skip tensor. Default: None.
Returns:
Tensor: RGB images.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | Apache-2.0 |
def forward(self,
styles,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
"""Forward function f... | Forward function for StyleGAN2Generator.
Args:
styles (list[Tensor]): Sample codes of styles.
input_is_latent (bool): Whether input is latent style.
Default: False.
noise (Tensor | None): Input noise or None. Default: None.
randomize_noise (bool):... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | Apache-2.0 |
def forward(self,
styles,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
"""Forward function f... | Forward function for StyleGAN2GeneratorClean.
Args:
styles (list[Tensor]): Sample codes of styles.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or None. Default: None.
randomize_noise (bool): Randomize ... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | Apache-2.0 |
def color_jitter(img, shift):
"""jitter color: randomly jitter the RGB values, in numpy formats"""
jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32)
img = img + jitter_val
img = np.clip(img, 0, 1)
return img | jitter color: randomly jitter the RGB values, in numpy formats | color_jitter | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | Apache-2.0 |
def color_jitter_pt(img, brightness, contrast, saturation, hue):
"""jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats"""
fn_idx = torch.randperm(4)
for fn_id in fn_idx:
if fn_id == 0 and brightness is not None:
bright... | jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats | color_jitter_pt | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | Apache-2.0 |
def get_component_coordinates(self, index, status):
"""Get facial component (left_eye, right_eye, mouth) coordinates from a pre-loaded pth file"""
components_bbox = self.components_list[f'{index:08d}']
if status[0]: # hflip
# exchange right and left eye
tmp = components_... | Get facial component (left_eye, right_eye, mouth) coordinates from a pre-loaded pth file | get_component_coordinates | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | Apache-2.0 |
def construct_img_pyramid(self):
"""Construct image pyramid for intermediate restoration loss"""
pyramid_gt = [self.gt]
down_img = self.gt
for _ in range(0, self.log_size - 3):
down_img = F.interpolate(down_img, scale_factor=0.5, mode='bilinear', align_corners=False)
... | Construct image pyramid for intermediate restoration loss | construct_img_pyramid | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/models/gfpgan_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/models/gfpgan_model.py | Apache-2.0 |
def _gram_mat(self, x):
"""Calculate Gram matrix.
Args:
x (torch.Tensor): Tensor with shape of (n, c, h, w).
Returns:
torch.Tensor: Gram matrix.
"""
n, c, h, w = x.size()
features = x.view(n, c, w * h)
features_t = features.transpose(1, 2... | Calculate Gram matrix.
Args:
x (torch.Tensor): Tensor with shape of (n, c, h, w).
Returns:
torch.Tensor: Gram matrix.
| _gram_mat | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/models/gfpgan_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/models/gfpgan_model.py | Apache-2.0 |
def _umeyama(src, dst, estimate_scale=True, scale=1.0):
"""Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate sc... | Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate scaling factor.
Returns
-------
T : (N + 1, N + 1)
... | _umeyama | python | OpenTalker/video-retalking | third_part/GPEN/align_faces.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/align_faces.py | Apache-2.0 |
def remove_prefix(self, state_dict, prefix):
''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.items()} | Old style model is stored with all names of parameters sharing common prefix 'module.' | remove_prefix | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/retinaface_detection.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/retinaface_detection.py | Apache-2.0 |
def detection_collate(batch):
"""Custom collate fn for dealing with batches of images that have a different
number of associated object annotations (bounding boxes).
Arguments:
batch: (tuple) A tuple of tensor images and lists of annotations
Return:
A tuple containing:
1) (... | Custom collate fn for dealing with batches of images that have a different
number of associated object annotations (bounding boxes).
Arguments:
batch: (tuple) A tuple of tensor images and lists of annotations
Return:
A tuple containing:
1) (tensor) batch of images stacked on th... | detection_collate | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/data/wider_face.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/data/wider_face.py | Apache-2.0 |
def __init__(self, cfg = None, phase = 'train'):
"""
:param cfg: Network related settings.
:param phase: train or test.
"""
super(RetinaFace,self).__init__()
self.phase = phase
backbone = None
if cfg['name'] == 'mobilenet0.25':
backbone = Mobi... |
:param cfg: Network related settings.
:param phase: train or test.
| __init__ | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/facemodels/retinaface.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/facemodels/retinaface.py | Apache-2.0 |
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
... | Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
| point_form | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def center_size(boxes):
""" Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
return torch.cat((boxes[:, 2:]... | Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
| center_size | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes... | We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes, Shape: [B,4].
Return:
(t... | intersect | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def matrix_iou(a, b):
"""
return iou of a and b, numpy version for data augenmentation
"""
lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
... |
return iou of a and b, numpy version for data augenmentation
| matrix_iou | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def matrix_iof(a, b):
"""
return iof of a and b, numpy version for data augenmentation
"""
lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
... |
return iof of a and b, numpy version for data augenmentation
| matrix_iof | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def encode_landm(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 10].... | Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 10].
priors: (tensor) Prior boxes in center-offse... | encode_landm | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def decode_landm(pre, priors, variances):
"""Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm predictions for loc layers,
Shape: [num_priors,10]
priors (tensor): Prior boxes in center-offset form... | Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm predictions for loc layers,
Shape: [num_priors,10]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
vari... | decode_landm | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def log_sum_exp(x):
"""Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
"""
x_max = x.data.max()
return torch.log(torch.sum(to... | Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
| log_sum_exp | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def nms(boxes, scores, overlap=0.5, top_k=200):
"""Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
scores: (tensor) The class predscores for the ... | Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
scores: (tensor) The class predscores for the img, Shape:[num_priors].
overlap: (float) The o... | nms | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def positive_cap(num):
""" Cap a number to ensure positivity
:param num: positive or negative number
:returns: (overflow, capped_number)
"""
if num < 0:
return 0, abs(num)
else:
return num, 0 | Cap a number to ensure positivity
:param num: positive or negative number
:returns: (overflow, capped_number)
| positive_cap | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def roi_coordinates(rect, size, scale):
""" Align the rectangle into the center and return the top-left coordinates
within the new size. If rect is smaller, we add borders.
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:param scale: scaling f... | Align the rectangle into the center and return the top-left coordinates
within the new size. If rect is smaller, we add borders.
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:param scale: scaling factor of the rectangle to be resized
:retur... | roi_coordinates | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def scaling_factor(rect, size):
""" Calculate the scaling factor for the current image to be
resized to the new dimensions
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:returns: floating point scaling factor
"""
new_height, new_width... | Calculate the scaling factor for the current image to be
resized to the new dimensions
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:returns: floating point scaling factor
| scaling_factor | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def resize_image(img, scale):
""" Resize image with the provided scaling factor
:param img: image to be resized
:param scale: scaling factor for resizing the image
"""
cur_height, cur_width = img.shape[:2]
new_scaled_height = int(scale * cur_height)
new_scaled_width = int(scale * cur_width)
return cv2... | Resize image with the provided scaling factor
:param img: image to be resized
:param scale: scaling factor for resizing the image
| resize_image | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def resize_align(img, points, size):
""" Resize image and associated points, align face to the center
and crop to the desired size
:param img: image to be resized
:param points: *m* x 2 array of points
:param size: (height, width) tuple of new desired size
"""
new_height, new_width = size
# Resize i... | Resize image and associated points, align face to the center
and crop to the desired size
:param img: image to be resized
:param points: *m* x 2 array of points
:param size: (height, width) tuple of new desired size
| resize_align | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def mask_from_points(size, points):
""" Create a mask of supplied size from supplied points
:param size: tuple of output mask size
:param points: array of [x, y] points
:returns: mask of values 0 and 255 where
255 indicates the convex hull containing the points
"""
radius = 10 # kernel size
k... | Create a mask of supplied size from supplied points
:param size: tuple of output mask size
:param points: array of [x, y] points
:returns: mask of values 0 and 255 where
255 indicates the convex hull containing the points
| mask_from_points | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/blender.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/blender.py | Apache-2.0 |
def overlay_image(foreground_image, mask, background_image):
""" Overlay foreground image onto the background given a mask
:param foreground_image: foreground image points
:param mask: [0-255] values in mask
:param background_image: background image points
:returns: image with foreground where mask > 0 overla... | Overlay foreground image onto the background given a mask
:param foreground_image: foreground image points
:param mask: [0-255] values in mask
:param background_image: background image points
:returns: image with foreground where mask > 0 overlaid on background image
| overlay_image | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/blender.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/blender.py | Apache-2.0 |
def apply_mask(img, mask):
""" Apply mask to supplied image
:param img: max 3 channel image
:param mask: [0-255] values in mask
:returns: new image with mask applied
"""
masked_img = np.copy(img)
num_channels = 3
for c in range(num_channels):
masked_img[..., c] = img[..., c] * (mask / 255)
return... | Apply mask to supplied image
:param img: max 3 channel image
:param mask: [0-255] values in mask
:returns: new image with mask applied
| apply_mask | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/blender.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/blender.py | Apache-2.0 |
def boundary_points(points, width_percent=0.1, height_percent=0.1):
""" Produce additional boundary points
:param points: *m* x 2 array of x,y points
:param width_percent: [-1, 1] percentage of width to taper inwards. Negative for opposite direction
:param height_percent: [-1, 1] percentage of height to taper d... | Produce additional boundary points
:param points: *m* x 2 array of x,y points
:param width_percent: [-1, 1] percentage of width to taper inwards. Negative for opposite direction
:param height_percent: [-1, 1] percentage of height to taper downwards. Negative for opposite direction
:returns: 2 additional points... | boundary_points | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/locator.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/locator.py | Apache-2.0 |
def face_points_dlib(img, add_boundary_points=True):
""" Locates 68 face points using dlib (http://dlib.net)
Requires shape_predictor_68_face_landmarks.dat to be in face_morpher/data
Download at: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
:param img: an image array
:param add_boundary... | Locates 68 face points using dlib (http://dlib.net)
Requires shape_predictor_68_face_landmarks.dat to be in face_morpher/data
Download at: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
:param img: an image array
:param add_boundary_points: bool to add additional boundary points
:returns... | face_points_dlib | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/locator.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/locator.py | Apache-2.0 |
def weighted_average_points(start_points, end_points, percent=0.5):
""" Weighted average of two sets of supplied points
:param start_points: *m* x 2 array of start face points.
:param end_points: *m* x 2 array of end face points.
:param percent: [0, 1] percentage weight on start_points
:returns: *m* x 2 arra... | Weighted average of two sets of supplied points
:param start_points: *m* x 2 array of start face points.
:param end_points: *m* x 2 array of end face points.
:param percent: [0, 1] percentage weight on start_points
:returns: *m* x 2 array of weighted average points
| weighted_average_points | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/locator.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/locator.py | Apache-2.0 |
def morph(src_img, src_points, dest_img, dest_points,
video, width=500, height=600, num_frames=20, fps=10,
out_frames=None, out_video=None, plot=False, background='black'):
"""
Create a morph sequence from source to destination image
:param src_img: ndarray source image
:param src_points: s... |
Create a morph sequence from source to destination image
:param src_img: ndarray source image
:param src_points: source image array of x,y face points
:param dest_img: ndarray destination image
:param dest_points: destination image array of x,y face points
:param video: facemorpher.videoer.Video object
| morph | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/morpher.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/morpher.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.