├── tools ├── __init__.py └── tools.py ├── utils ├── __init__.py └── util.py ├── model ├── ops │ ├── __init__.py │ ├── utils.py │ └── basic_ops.py ├── loss.py ├── metric.py ├── places365_SUN_model.py └── stgcn.py ├── trainer ├── __init__.py └── trainer.py ├── logger ├── __init__.py ├── logger.py ├── logger_config.json └── visualization.py ├── model.png ├── glove_840B_embeddings.npy ├── base ├── __init__.py ├── base_model.py ├── base_data_loader.py └── base_trainer.py ├── misc ├── BOLD_test_max_x_joint.npy ├── BOLD_test_max_y_joint.npy ├── BOLD_val_max_x_joint.npy ├── BOLD_val_max_y_joint.npy ├── BOLD_train_max_x_joint.npy └── BOLD_train_max_y_joint.npy ├── .gitignore ├── main_config.json ├── README.md ├── requirements.txt ├── skeleton_dataset.py ├── parse_config.py ├── train_stgcn.py ├── infer_stgcn.py ├── transforms.py ├── train_tsn.py ├── infer_tsn.py ├── dataset.py └── LICENSE /tools/__init__.py: -------------------------------------------------------------------------------- 1 | from .tools import * 2 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .util import * 2 | -------------------------------------------------------------------------------- /model/ops/__init__.py: -------------------------------------------------------------------------------- 1 | from .basic_ops import * -------------------------------------------------------------------------------- /trainer/__init__.py: -------------------------------------------------------------------------------- 1 | from .trainer import * 2 | -------------------------------------------------------------------------------- /logger/__init__.py: -------------------------------------------------------------------------------- 1 | from .logger import * 2 | from .visualization import * -------------------------------------------------------------------------------- /model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/model.png -------------------------------------------------------------------------------- /glove_840B_embeddings.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/glove_840B_embeddings.npy -------------------------------------------------------------------------------- /base/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_data_loader import * 2 | from .base_model import * 3 | from .base_trainer import * 4 | -------------------------------------------------------------------------------- /misc/BOLD_test_max_x_joint.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/misc/BOLD_test_max_x_joint.npy -------------------------------------------------------------------------------- /misc/BOLD_test_max_y_joint.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/misc/BOLD_test_max_y_joint.npy -------------------------------------------------------------------------------- /misc/BOLD_val_max_x_joint.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/misc/BOLD_val_max_x_joint.npy -------------------------------------------------------------------------------- /misc/BOLD_val_max_y_joint.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/misc/BOLD_val_max_y_joint.npy -------------------------------------------------------------------------------- /misc/BOLD_train_max_x_joint.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/misc/BOLD_train_max_x_joint.npy -------------------------------------------------------------------------------- /misc/BOLD_train_max_y_joint.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GiannisPikoulis/FG2021-BoLD/HEAD/misc/BOLD_train_max_y_joint.npy -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | .ipynb_checkpoints/ 3 | *.pyc 4 | *.png 5 | *.txt 6 | *.avi 7 | *.tar 8 | log/ 9 | *.pth 10 | *.tar 11 | -------------------------------------------------------------------------------- /base/base_model.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import numpy as np 3 | from abc import abstractmethod 4 | 5 | 6 | class BaseModel(nn.Module): 7 | """ 8 | Base class for all models 9 | """ 10 | @abstractmethod 11 | def forward(self, *inputs): 12 | """ 13 | Forward pass logic 14 | 15 | :return: Model output 16 | """ 17 | raise NotImplementedError 18 | 19 | def __str__(self): 20 | """ 21 | Model prints with number of trainable parameters 22 | """ 23 | model_parameters = filter(lambda p: p.requires_grad, self.parameters()) 24 | params = sum([np.prod(p.size()) for p in model_parameters]) 25 | return super().__str__() + '\nTrainable parameters: {}'.format(params) 26 | -------------------------------------------------------------------------------- /main_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "TSN_RGB_cf", 3 | "n_gpu": 1, 4 | "loss_categorical": "combined_loss", 5 | "loss_continuous": "mse_loss", 6 | "metrics_categorical": ["average_precision", "roc_auc"], 7 | "metrics_continuous": ["r2", "mean_squared_error"], 8 | "lr_scheduler": { 9 | "type": "MultiStepLR", 10 | "args": { 11 | "milestones": [40], 12 | "gamma": 0.1 13 | } 14 | }, 15 | "trainer": { 16 | "epochs": 40, 17 | "save_dir": "log", 18 | "checkpoint_dir": "/gpu-data2/jpik/checkpoints", 19 | "save_period": 50, 20 | "verbosity": 2, 21 | "monitor": "on", 22 | "mnt_mode": "max", 23 | "mnt_metric": "Validation ERS", 24 | "check_enabled": true, 25 | "early_stop": 100, 26 | "tensorboard": false 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /logger/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import logging.config 3 | from pathlib import Path 4 | from utils import read_json 5 | 6 | def setup_logging(save_dir, log_config='logger/logger_config.json', default_level=logging.INFO): 7 | """ 8 | Setup logging configuration 9 | """ 10 | log_config = Path(log_config) 11 | if log_config.is_file(): 12 | config = read_json(log_config) 13 | # modify logging paths based on run config 14 | for _, handler in config['handlers'].items(): 15 | if 'filename' in handler: 16 | handler['filename'] = str(save_dir / handler['filename']) 17 | 18 | logging.config.dictConfig(config) 19 | else: 20 | print("Warning: logging configuration file is not found in {}.".format(log_config)) 21 | logging.basicConfig(level=default_level) 22 | -------------------------------------------------------------------------------- /model/ops/utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | from sklearn.metrics import confusion_matrix 4 | 5 | 6 | def get_grad_hook(name): 7 | def hook(m, grad_in, grad_out): 8 | print((name, grad_out[0].data.abs().mean(), grad_in[0].data.abs().mean())) 9 | print((grad_out[0].size())) 10 | print((grad_in[0].size())) 11 | 12 | print((grad_out[0])) 13 | print((grad_in[0])) 14 | 15 | return hook 16 | 17 | 18 | def softmax(scores): 19 | es = np.exp(scores - scores.max(axis=-1)[..., None]) 20 | return es / es.sum(axis=-1)[..., None] 21 | 22 | 23 | def log_add(log_a, log_b): 24 | return log_a + np.log(1 + np.exp(log_b - log_a)) 25 | 26 | 27 | def class_accuracy(prediction, label): 28 | cf = confusion_matrix(prediction, label) 29 | cls_cnt = cf.sum(axis=1) 30 | cls_hit = np.diag(cf) 31 | 32 | cls_acc = cls_hit / cls_cnt.astype(float) 33 | 34 | mean_cls_acc = cls_acc.mean() 35 | 36 | return cls_acc, mean_cls_acc -------------------------------------------------------------------------------- /logger/logger_config.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "version": 1, 4 | "disable_existing_loggers": false, 5 | "formatters": { 6 | "simple": {"format": "%(message)s"}, 7 | "datetime": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} 8 | }, 9 | "handlers": { 10 | "console": { 11 | "class": "logging.StreamHandler", 12 | "level": "DEBUG", 13 | "formatter": "simple", 14 | "stream": "ext://sys.stdout" 15 | }, 16 | "info_file_handler": { 17 | "class": "logging.handlers.RotatingFileHandler", 18 | "level": "INFO", 19 | "formatter": "datetime", 20 | "filename": "info.log", 21 | "maxBytes": 10485760, 22 | "backupCount": 20, "encoding": "utf8" 23 | } 24 | }, 25 | "root": { 26 | "level": "INFO", 27 | "handlers": [ 28 | "console", 29 | "info_file_handler" 30 | ] 31 | } 32 | } -------------------------------------------------------------------------------- /model/loss.py: -------------------------------------------------------------------------------- 1 | import torch.nn.functional as F 2 | import torch.nn as nn 3 | import torch 4 | from torch.autograd import Variable, Function 5 | 6 | def nll_loss(output, target): 7 | return F.nll_loss(output, target) 8 | 9 | 10 | def bce_loss(output, target): 11 | 12 | t = target.clone().detach() 13 | 14 | t[t >= 0.5] = 1 # threshold to get binary labels 15 | t[t < 0.5] = 0 16 | 17 | loss = F.binary_cross_entropy_with_logits(output, t) 18 | return loss 19 | 20 | 21 | def combined_loss(output, target): 22 | l = F.mse_loss(torch.sigmoid(output), target) 23 | 24 | l += bce_loss(output, target) 25 | 26 | return l 27 | 28 | 29 | def mse_loss(output, target): 30 | return F.mse_loss(output, target) 31 | 32 | 33 | def mse_center_loss(output, target, labels): 34 | t = labels.clone().detach() 35 | 36 | t[t >= 0.5] = 1 # threshold to get binary labels 37 | t[t < 0.5] = 0 38 | 39 | target = target[0,:26] 40 | 41 | positive_centers = [] 42 | for i in range(output.size(0)): 43 | p = target[t[i, :] == 1] 44 | if p.size(0) == 0: 45 | positive_center = torch.zeros(300).cuda() 46 | else: 47 | positive_center = torch.mean(p, dim=0) 48 | 49 | positive_centers.append(positive_center) 50 | 51 | positive_centers = torch.stack(positive_centers,dim=0) 52 | loss = F.mse_loss(output, positive_centers) 53 | 54 | return loss -------------------------------------------------------------------------------- /model/ops/basic_ops.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import math 3 | import warnings 4 | warnings.filterwarnings("ignore") 5 | 6 | 7 | class Identity(torch.nn.Module): 8 | def forward(self, input): 9 | return input 10 | 11 | 12 | class SegmentConsensus(torch.autograd.Function): 13 | 14 | @staticmethod 15 | def forward(ctx, input, consensus_type, dim): 16 | 17 | ctx.shape = input.size() 18 | ctx.consensus_type = consensus_type 19 | ctx.dim = dim 20 | 21 | if consensus_type == 'avg': 22 | output = input.mean(dim, keepdim=True) 23 | elif consensus_type == 'max': 24 | output = input.max(dim, keepdim=True) 25 | elif consensus_type == 'identity': 26 | output = input 27 | else: 28 | output = None 29 | 30 | return output 31 | 32 | @staticmethod 33 | def backward(ctx, grad_output): 34 | 35 | if ctx.consensus_type == 'avg': 36 | grad_in = grad_output.expand(ctx.shape) / float(ctx.shape[ctx.dim]) 37 | elif ctx.consensus_type == 'identity': 38 | grad_in = grad_output 39 | else: 40 | grad_in = None 41 | 42 | return grad_in, None, None 43 | 44 | 45 | class ConsensusModule(torch.nn.Module): 46 | 47 | def __init__(self, consensus_type, dim=1): 48 | super(ConsensusModule, self).__init__() 49 | self.consensus_type = consensus_type if consensus_type != 'rnn' else 'identity' 50 | self.dim = dim 51 | 52 | def forward(self, input): 53 | return SegmentConsensus.apply(input, self.consensus_type, self.dim) -------------------------------------------------------------------------------- /model/metric.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import sklearn.metrics 3 | import warnings 4 | 5 | def accuracy(output, target): 6 | with torch.no_grad(): 7 | pred = torch.argmax(output, dim=1) 8 | assert pred.shape[0] == len(target) 9 | correct = 0 10 | correct += torch.sum(pred == target).item() 11 | return correct / len(target) 12 | 13 | 14 | def top_k_acc(output, target, k=3): 15 | with torch.no_grad(): 16 | pred = torch.topk(output, k, dim=1)[1] 17 | assert pred.shape[0] == len(target) 18 | correct = 0 19 | for i in range(k): 20 | correct += torch.sum(pred[:, i] == target).item() 21 | return correct / len(target) 22 | 23 | 24 | def average_precision(output, target): 25 | return sklearn.metrics.average_precision_score(target, output, average=None) 26 | 27 | 28 | def multilabel_confusion_matrix(output, target): 29 | # with warnings.catch_warnings(): 30 | # warnings.simplefilter("ignore") 31 | return sklearn.metrics.multilabel_confusion_matrix(target, output) 32 | 33 | 34 | def roc_auc(output, target): 35 | # print(np.sum(target.cpu().detach().numpy(),axis=1),np.sum(target.cpu().detach().numpy(),axis=0)) 36 | # print(output.size()) 37 | return sklearn.metrics.roc_auc_score(target, output, average=None) 38 | 39 | 40 | def mean_squared_error(output, target): 41 | return sklearn.metrics.mean_squared_error(target, output, multioutput='raw_values') 42 | 43 | 44 | def r2(output, target): 45 | return sklearn.metrics.r2_score(target, output, multioutput='raw_values') 46 | 47 | 48 | def ERS(mR2, mAP, mRA): 49 | return 1/2 * (mR2 + 1/2 * (mAP + mRA)) -------------------------------------------------------------------------------- /base/base_data_loader.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from torch.utils.data import DataLoader 3 | from torch.utils.data.dataloader import default_collate 4 | from torch.utils.data.sampler import SubsetRandomSampler 5 | 6 | 7 | class BaseDataLoader(DataLoader): 8 | """ 9 | Base class for all data loaders 10 | """ 11 | def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate): 12 | self.validation_split = validation_split 13 | self.shuffle = shuffle 14 | 15 | self.batch_idx = 0 16 | self.n_samples = len(dataset) 17 | 18 | self.sampler, self.valid_sampler = self._split_sampler(self.validation_split) 19 | 20 | self.init_kwargs = { 21 | 'dataset': dataset, 22 | 'batch_size': batch_size, 23 | 'shuffle': self.shuffle, 24 | 'collate_fn': collate_fn, 25 | 'num_workers': num_workers 26 | } 27 | super().__init__(sampler=self.sampler, **self.init_kwargs) 28 | 29 | def _split_sampler(self, split): 30 | if split == 0.0: 31 | return None, None 32 | 33 | idx_full = np.arange(self.n_samples) 34 | 35 | np.random.seed(0) 36 | np.random.shuffle(idx_full) 37 | 38 | if isinstance(split, int): 39 | assert split > 0 40 | assert split < self.n_samples, "validation set size is configured to be larger than entire dataset." 41 | len_valid = split 42 | else: 43 | len_valid = int(self.n_samples * split) 44 | 45 | valid_idx = idx_full[0:len_valid] 46 | train_idx = np.delete(idx_full, np.arange(0, len_valid)) 47 | 48 | train_sampler = SubsetRandomSampler(train_idx) 49 | valid_sampler = SubsetRandomSampler(valid_idx) 50 | 51 | # turn off shuffle option which is mutually exclusive with sampler 52 | self.shuffle = False 53 | self.n_samples = len(train_idx) 54 | 55 | return train_sampler, valid_sampler 56 | 57 | def split_validation(self): 58 | if self.valid_sampler is None: 59 | return None 60 | else: 61 | return DataLoader(sampler=self.valid_sampler, **self.init_kwargs) 62 | -------------------------------------------------------------------------------- /logger/visualization.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | from datetime import datetime 3 | import numpy as np 4 | import os 5 | 6 | 7 | class TensorboardWriter(): 8 | 9 | def __init__(self, log_dir, logger, enabled): 10 | 11 | self.writer = None 12 | self.selected_module = "" 13 | self.log_dir = log_dir 14 | if enabled: 15 | log_dir = str(log_dir) 16 | 17 | # Retrieve vizualization writer. 18 | succeeded = False 19 | for module in ["torch.utils.tensorboard", "tensorboardX"]: 20 | try: 21 | self.writer = importlib.import_module(module).SummaryWriter(log_dir) 22 | succeeded = True 23 | break 24 | except ImportError: 25 | succeeded = False 26 | self.selected_module = module 27 | 28 | if not succeeded: 29 | message = "Warning: visualization (Tensorboard) is configured to use, but currently not installed on " \ 30 | "this machine. Please install TensorboardX with 'pip install tensorboardx', upgrade PyTorch to " \ 31 | "version >= 1.1 to use 'torch.utils.tensorboard' or turn off the option in the 'config.json' file." 32 | logger.warning(message) 33 | 34 | self.step = 0 35 | self.mode = '' 36 | 37 | self.tb_writer_ftns = { 38 | 'add_scalar', 'add_scalars', 'add_image', 'add_images', 'add_audio', 39 | 'add_text', 'add_histogram', 'add_pr_curve', 'add_embedding', 'add_figure' 40 | } 41 | self.tag_mode_exceptions = {'add_histogram', 'add_embedding'} 42 | self.timer = datetime.now() 43 | 44 | 45 | def save_results(self, output, name): 46 | np.save(os.path.join(self.log_dir,"%s_%d"%(name, self.step)), output) 47 | 48 | 49 | def set_step(self, step, mode='train'): 50 | self.mode = mode 51 | self.step = step 52 | if step == 0: 53 | self.timer = datetime.now() 54 | else: 55 | duration = datetime.now() - self.timer 56 | self.add_scalar('steps_per_sec', 1 / duration.total_seconds()) 57 | self.timer = datetime.now() 58 | 59 | 60 | def __getattr__(self, name): 61 | """ 62 | If visualization is configured to use: 63 | return add_data() methods of tensorboard with additional information (step, tag) added. 64 | Otherwise: 65 | return a blank function handle that does nothing 66 | """ 67 | if name in self.tb_writer_ftns: 68 | add_data = getattr(self.writer, name, None) 69 | 70 | def wrapper(tag, data, *args, **kwargs): 71 | if add_data is not None: 72 | # add mode(train/valid) tag 73 | if name not in self.tag_mode_exceptions: 74 | tag = '{}/{}'.format(tag, self.mode) 75 | add_data(tag, data, self.step, *args, **kwargs) 76 | return wrapper 77 | else: 78 | # default action for returning methods defined in this class, set_step() for instance. 79 | try: 80 | attr = object.__getattr__(name) 81 | except AttributeError: 82 | raise AttributeError("type object '{}' has no attribute '{}'".format(self.selected_module, name)) 83 | return attr 84 | -------------------------------------------------------------------------------- /model/places365_SUN_model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torchvision.models as models 3 | from torch.nn import functional as F 4 | import os 5 | import numpy as np 6 | import cv2 7 | 8 | 9 | # hacky way to deal with the Pytorch 1.0 update 10 | def recursion_change_bn(module): 11 | if isinstance(module, torch.nn.BatchNorm2d): 12 | module.track_running_stats = 1 13 | else: 14 | for i, (name, module1) in enumerate(module._modules.items()): 15 | module1 = recursion_change_bn(module1) 16 | return module 17 | 18 | 19 | def load_labels(): 20 | 21 | # prepare all the labels 22 | # scene category relevant 23 | file_name_category = 'categories_places365.txt' 24 | if not os.access(file_name_category, os.W_OK): 25 | synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/categories_places365.txt' 26 | os.system('wget ' + synset_url) 27 | classes = list() 28 | with open(file_name_category) as class_file: 29 | for line in class_file: 30 | classes.append(line.strip().split(' ')[0][3:]) 31 | classes = tuple(classes) 32 | 33 | # indoor and outdoor relevant 34 | file_name_IO = 'IO_places365.txt' 35 | if not os.access(file_name_IO, os.W_OK): 36 | synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/IO_places365.txt' 37 | os.system('wget ' + synset_url) 38 | with open(file_name_IO) as f: 39 | lines = f.readlines() 40 | labels_IO = [] 41 | for line in lines: 42 | items = line.rstrip().split() 43 | labels_IO.append(int(items[-1]) -1) # 0 is indoor, 1 is outdoor 44 | labels_IO = np.array(labels_IO) 45 | 46 | # scene attribute relevant 47 | file_name_attribute = 'labels_sunattribute.txt' 48 | if not os.access(file_name_attribute, os.W_OK): 49 | synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/labels_sunattribute.txt' 50 | os.system('wget ' + synset_url) 51 | with open(file_name_attribute) as f: 52 | lines = f.readlines() 53 | labels_attribute = [item.rstrip() for item in lines] 54 | file_name_W = 'W_sceneattribute_wideresnet18.npy' 55 | if not os.access(file_name_W, os.W_OK): 56 | synset_url = 'http://places2.csail.mit.edu/models_places365/W_sceneattribute_wideresnet18.npy' 57 | os.system('wget ' + synset_url) 58 | W_attribute = np.load(file_name_W) 59 | 60 | return classes, labels_IO, labels_attribute, W_attribute 61 | 62 | 63 | def load_model(): 64 | 65 | # this model has a last conv feature map as 14x14 66 | model_file = 'wideresnet18_places365.pth.tar' 67 | if not os.access(model_file, os.W_OK): 68 | os.system('wget http://places2.csail.mit.edu/models_places365/' + model_file) 69 | os.system('wget https://raw.githubusercontent.com/csailvision/places365/master/wideresnet.py') 70 | 71 | import wideresnet 72 | model = wideresnet.resnet18(num_classes=365) 73 | checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage) 74 | state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()} 75 | model.load_state_dict(state_dict) 76 | 77 | # hacky way to deal with the upgraded batchnorm2D and avgpool layers... 78 | for i, (name, module) in enumerate(model._modules.items()): 79 | module = recursion_change_bn(model) 80 | model.avgpool = torch.nn.AvgPool2d(kernel_size=14, stride=1, padding=0) 81 | model.eval() 82 | 83 | # the following is deprecated, everything is migrated to python36 84 | ## if you encounter the UnicodeDecodeError when use python3 to load the model, add the following line will fix it. Thanks to @soravux 85 | #from functools import partial 86 | #import pickle 87 | #pickle.load = partial(pickle.load, encoding="latin1") 88 | #pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1") 89 | #model = torch.load(model_file, map_location=lambda storage, loc: storage, pickle_module=pickle) 90 | return model -------------------------------------------------------------------------------- /utils/util.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pandas as pd 3 | from pathlib import Path 4 | from itertools import repeat 5 | from collections import OrderedDict 6 | import cv2 7 | import matplotlib as mpl 8 | 9 | mpl.use('Agg') 10 | 11 | import matplotlib.pyplot as plt 12 | 13 | import matplotlib.animation as animation 14 | def ensure_dir(dirname): 15 | dirname = Path(dirname) 16 | if not dirname.is_dir(): 17 | dirname.mkdir(parents=True, exist_ok=False) 18 | 19 | def read_json(fname): 20 | fname = Path(fname) 21 | with fname.open('rt') as handle: 22 | return json.load(handle, object_hook=OrderedDict) 23 | 24 | def write_json(content, fname): 25 | fname = Path(fname) 26 | with fname.open('wt') as handle: 27 | json.dump(content, handle, indent=4, sort_keys=False) 28 | 29 | def inf_loop(data_loader): 30 | ''' wrapper function for endless data loader. ''' 31 | for loader in repeat(data_loader): 32 | yield from loader 33 | 34 | class MetricTracker: 35 | def __init__(self, *keys, writer=None): 36 | self.writer = writer 37 | self._data = pd.DataFrame(index=keys, columns=['total', 'counts', 'average']) 38 | self.reset() 39 | 40 | def reset(self): 41 | for col in self._data.columns: 42 | self._data[col].values[:] = 0 43 | 44 | def update(self, key, value, n=1): 45 | if self.writer is not None: 46 | self.writer.add_scalar(key, value) 47 | self._data.total[key] += value * n 48 | self._data.counts[key] += n 49 | self._data.average[key] = self._data.total[key] / self._data.counts[key] 50 | 51 | def avg(self, key): 52 | return self._data.average[key] 53 | 54 | def result(self): 55 | return dict(self._data.average) 56 | 57 | import matplotlib.pyplot as plt 58 | import matplotlib.animation as animation 59 | import numpy as np 60 | 61 | def visualize_skeleton_openpose_18(joints, filename="fig.png"): 62 | joints_edges = [[0,1], [1,2], [2,3], [3,4], [1,5], [5,6], [6,7], [1,8], [8,9], 63 | [9,10], [1,11], [11,12], [12,13], [0,14],[14,16], [0,15], [15,17]] 64 | 65 | joints[joints[:,:,2]<0.1] = np.nan 66 | joints[np.isnan(joints[:,:,2])] = np.nan 67 | 68 | # ani = animation.FuncAnimation(fig, update_plot, frames=range(len(sequence)), 69 | # fargs=(sequence, scat)) 70 | 71 | # plt.show() 72 | 73 | from celluloid import Camera 74 | 75 | fig = plt.figure() 76 | ax = fig.add_subplot(111) 77 | plt.gca().invert_yaxis() 78 | 79 | camera = Camera(fig) 80 | for frame in range(0,joints.shape[0]): 81 | 82 | scat = ax.scatter(joints[frame, :, 0], joints[frame, :, 1]) 83 | for edge in joints_edges: 84 | ax.plot((joints[frame, edge[0], 0], joints[frame, edge[1], 0]), 85 | (joints[frame, edge[0], 1], joints[frame, edge[1], 1])) 86 | 87 | camera.snap() 88 | 89 | animation = camera.animate(interval=30) 90 | plt.close() 91 | return animation 92 | 93 | 94 | def make_barplot(y, c, label): 95 | 96 | def autolabel(rects): 97 | """Attach a text label above each bar in *rects*, displaying its height.""" 98 | for rect in rects: 99 | height = rect.get_height() 100 | ax.annotate('{:.02f}'.format(height), 101 | xy=(rect.get_x() + rect.get_width() / 2, height), 102 | xytext=(0, 3), # 3 points vertical offset 103 | textcoords="offset points", 104 | ha='center', va='bottom') 105 | 106 | x = np.arange(len(c)) # the label locations 107 | 108 | width = 0.35 109 | fig, ax = plt.subplots(figsize=(8,6)) 110 | rects1 = ax.bar(x, y, width, label=label) 111 | 112 | autolabel(rects1) 113 | 114 | plt.xticks(rotation=90) 115 | 116 | ax.set_xticks(x) 117 | ax.set_xticklabels(c) 118 | plt.tight_layout() 119 | plt.close() 120 | 121 | return fig 122 | 123 | 124 | features_blobs = None 125 | 126 | def hook_feature(module, input, output): 127 | global features_blobs 128 | features_blobs = np.squeeze(output.data.cpu().numpy()) 129 | 130 | def returnCAM(feature_conv, weight_softmax, class_idx): 131 | # generate the class activation maps upsample to 256x256 132 | size_upsample = (256, 256) 133 | nc, h, w = feature_conv.shape 134 | output_cam = [] 135 | for idx in class_idx: 136 | cam = weight_softmax[class_idx].dot(feature_conv.reshape((nc, h * w))) 137 | cam = cam.reshape(h, w) 138 | cam = cam - np.min(cam) 139 | cam_img = cam / np.max(cam) 140 | cam_img = np.uint8(255 * cam_img) 141 | output_cam.append(cv2.resize(cam_img, size_upsample)) 142 | return output_cam 143 | 144 | 145 | def setup_cam(model): 146 | features_names = ['layer4'] # this is the last conv layer of the resnet 147 | for name in features_names: 148 | model.module.base_model._modules.get(name).register_forward_hook(hook_feature) 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leveraging Semantic Scene Characteristics and Multi-Stream Convolutional Architectures in a Contextual Approach for Video-Based Visual Emotion Recognition in the Wild 2 | 3 | ![Model](https://github.com/GiannisPikoulis/FG2021-BoLD/blob/master/model.png?raw=true) 4 | 5 | Code for reproducing our proposed state-of-the-art model, for categorical and continuous emotion recognition on the basis of the newly assembled and challenging Body Language Dataset (BoLD), as submitted to the 16th IEEE International Conference on Automatic Face and Gesture Recognition (FG 2021). 6 | 7 | ### Preparation 8 | 9 | * Download the [BoLD dataset](https://cydar.ist.psu.edu/emotionchallenge/index.php). 10 | * Use [https://github.com/yjxiong/temporal-segment-networks](https://github.com/yjxiong/temporal-segment-networks) in order to extract RGB and Optical Flow for the dataset. 11 | * Change the directories in "dataset.py", "skeleton_dataset.py" and paths for pre-trained weights in "models.py" files. 12 | 13 | ### Training 14 | 15 | Train an Temporal Segment Network using the RGB modality (TSN-RGB) and only the body stream, on the BoLD dataset: 16 | 17 | ``` 18 | python train_tsn.py --config main_config.json --exp_name TSN_RGB_b --modality RGB --device 0 --rgb_body 19 | ``` 20 | 21 | Add context branch: 22 | 23 | ``` 24 | python train_tsn.py --config main_config.json --exp_name TSN_RGB_bc --modality RGB --device 0 --context --rgb_body --rgb_context 25 | ``` 26 | 27 | Add visual embedding loss: 28 | 29 | ``` 30 | python train_tsn.py --config main_config.json --exp_name TSN_RGB_bc_embed --modality RGB --device 0 --context --rgb_body --rgb_context --embed 31 | ``` 32 | 33 | Initialize body stream with ImageNet pre-trained weights: 34 | 35 | ``` 36 | python train_tsn.py --config main_config.json --exp_name TSN_RGB_bc_embed --modality RGB --device 0 --context --rgb_body --rgb_context --embed --pretrained_imagenet 37 | ``` 38 | 39 | Change modality to Optical Flow (all streams initialized with ImageNet pre-trained weights): 40 | 41 | ``` 42 | python train_tsn.py --config main_config.json --exp_name TSN_Flow_bc_embed --modality Flow --device 0 --context --flow_body --flow_context --embed --pretrained_imagenet 43 | ``` 44 | 45 | ### Pre-trained Models 46 | 47 | We also provide weights for a TSN-RGB model with body, context, face, scenes and attributes streams, embedding loss and partial batch normalization (0.2590 validation ERS), a TSN-Flow model with body, context and face streams, embedding loss and partial batch normalization (0.2408 validation ERS) and a fine-tuned ST-GCN model with spatial labeling strategy and pre-training on Kinetics (0.2237 validation ERS). Their weighted averaged late fusion achieves an ERS of 0.2882 on the validation set. You can download the pre-trained models [here](https://drive.google.com/drive/folders/18CAU2WX61BRB2dK6ABKM7R1mDA8iR3Vz?usp=sharing). 48 | 49 | Moreover, all Places365 and SUN pre-trained models that were utilized in our experiments can be found [here](https://github.com/CSAILVision/places365). ImageNet pre-trained weights are provided by [PyTorch](https://pytorch.org/vision/stable/models.html). Lastly, we do not intend to release our AffectNet pre-trained ResNet-18 and ResNet-50 variants. 50 | 51 | ### Inference 52 | 53 | Run inference on the BoLD test set (using the provided pre-trained models): 54 | 55 | ``` 56 | python infer_tsn.py --modality RGB --device 0 --context --rgb_body --rgb_context --rgb_face --scenes --attributes --context --embed --partial_bn --checkpoint {path to .pth checkpoint file} --save_outputs --output_dir {directory to save outputs to} --exp_name some_name --mode test 57 | ``` 58 | 59 | ### Citation 60 | 61 | If you use our code for your research, consider citing the following papers: 62 | ``` 63 | @inproceedings{pikoulis2021leveraging, 64 | author={Pikoulis, Ioannis and Filntisis, Panagiotis P. and Maragos, Petros}, 65 | booktitle={2021 16th IEEE International Conference on Automatic Face and Gesture Recognition (FG 2021)}, 66 | title={Leveraging Semantic Scene Characteristics and Multi-Stream Convolutional Architectures in a Contextual Approach for Video-Based Visual Emotion Recognition in the Wild}, 67 | year={2021}, 68 | volume={}, 69 | number={}, 70 | doi={10.1109/FG52635.2021.9666957} 71 | } 72 | 73 | @inproceedings{NTUA_BEEU, 74 | title={Emotion Understanding in Videos Through Body, Context, and Visual-Semantic Embedding Loss}, 75 | author={Filntisis, Panagiotis Paraskevas and Efthymiou, Niki and Potamianos, Gerasimos and Maragos, Petros}, 76 | booktitle={ECCV Workshop on Bodily Expressed Emotion Understanding}, 77 | year={2020} 78 | } 79 | ``` 80 | ### Acknowlegements 81 | 82 | * [https://github.com/filby89/NTUA-BEEU-eccv2020](https://github.com/filby89/NTUA-BEEU-eccv2020) 83 | * [https://github.com/victoresque/pytorch-template](https://github.com/victoresque/pytorch-template) 84 | * [https://github.com/yjxiong/tsn-pytorch](https://github.com/yjxiong/tsn-pytorch) 85 | * [https://github.com/yysijie/st-gcn](https://github.com/yysijie/st-gcn) 86 | * [https://github.com/CSAILVision/places365](https://github.com/CSAILVision/places365) 87 | 88 | ### Contact 89 | 90 | For questions feel free to open an issue. 91 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # This file may be used to create an environment using: 2 | # $ conda create --name --file 3 | # platform: linux-64 4 | _libgcc_mutex=0.1=conda_forge 5 | _openmp_mutex=4.5=1_gnu 6 | absl-py=0.13.0=pyhd8ed1ab_0 7 | aiohttp=3.7.4.post0=py37h5e8e339_0 8 | alsa-lib=1.2.3=h516909a_0 9 | async-timeout=3.0.1=py_1000 10 | attrs=21.2.0=pyhd8ed1ab_0 11 | blas=1.0=mkl 12 | blinker=1.4=py_1 13 | brotlipy=0.7.0=py37h5e8e339_1001 14 | bzip2=1.0.8=h7f98852_4 15 | c-ares=1.17.1=h7f98852_1 16 | ca-certificates=2021.5.30=ha878542_0 17 | cachetools=4.2.2=pyhd8ed1ab_0 18 | cairo=1.16.0=h6cf1ce9_1008 19 | certifi=2021.5.30=py37h89c1867_0 20 | cffi=1.14.6=py37hc58025e_0 21 | chardet=4.0.0=py37h89c1867_1 22 | charset-normalizer=2.0.0=pyhd8ed1ab_0 23 | click=8.0.1=py37h89c1867_0 24 | cryptography=3.4.7=py37h5d9358c_0 25 | cudatoolkit=10.2.89=h8f6ccaa_8 26 | cycler=0.10.0=py_2 27 | dataclasses=0.8=pyhc8e2a94_1 28 | dbus=1.13.6=h48d8840_2 29 | expat=2.4.1=h9c3ff4c_0 30 | ffmpeg=4.3.1=hca11adc_2 31 | fontconfig=2.13.1=hba837de_1005 32 | freetype=2.10.4=h0708190_1 33 | gettext=0.19.8.1=h0b5b191_1005 34 | glib=2.68.3=h9c3ff4c_0 35 | glib-tools=2.68.3=h9c3ff4c_0 36 | gmp=6.2.1=h58526e2_0 37 | gnutls=3.6.13=h85f3911_1 38 | google-auth=1.33.1=pyh6c4a22f_0 39 | google-auth-oauthlib=0.4.1=py_2 40 | graphite2=1.3.13=h58526e2_1001 41 | grpcio=1.38.1=py37hb27c1af_0 42 | gst-plugins-base=1.18.4=hf529b03_2 43 | gstreamer=1.18.4=h76c114f_2 44 | harfbuzz=2.8.2=h83ec7ef_0 45 | hdf5=1.10.6=nompi_h3c11f04_101 46 | icu=68.1=h58526e2_0 47 | idna=3.1=pyhd3deb0d_0 48 | importlib-metadata=4.6.1=py37h89c1867_0 49 | intel-openmp=2021.3.0=h06a4308_3350 50 | jasper=1.900.1=h07fcdf6_1006 51 | jbig=2.1=h7f98852_2003 52 | joblib=0.17.0=py_0 53 | jpeg=9d=h36c2ea0_0 54 | kiwisolver=1.3.1=py37h2527ec5_1 55 | krb5=1.19.1=hcc1bbae_0 56 | lame=3.100=h7f98852_1001 57 | lcms2=2.12=hddcbb42_0 58 | ld_impl_linux-64=2.36.1=hea4e1c9_1 59 | lerc=2.2.1=h9c3ff4c_0 60 | libblas=3.9.0=9_mkl 61 | libcblas=3.9.0=9_mkl 62 | libclang=11.1.0=default_ha53f305_1 63 | libdeflate=1.7=h7f98852_5 64 | libedit=3.1.20191231=he28a2e2_2 65 | libevent=2.1.10=hcdb4288_3 66 | libffi=3.3=h58526e2_2 67 | libgcc-ng=11.1.0=hc902ee8_0 68 | libgfortran-ng=7.3.0=hdf63c60_0 69 | libglib=2.68.3=h3e27bee_0 70 | libgomp=11.1.0=hc902ee8_0 71 | libiconv=1.16=h516909a_0 72 | liblapack=3.9.0=9_mkl 73 | liblapacke=3.9.0=9_mkl 74 | libllvm11=11.1.0=hf817b99_2 75 | libogg=1.3.4=h7f98852_1 76 | libopencv=4.5.2=py37h8945300_0 77 | libopus=1.3.1=h7f98852_1 78 | libpng=1.6.37=h21135ba_2 79 | libpq=13.3=hd57d9b9_0 80 | libprotobuf=3.15.8=h780b84a_0 81 | libstdcxx-ng=11.1.0=h56837e0_0 82 | libtiff=4.3.0=hf544144_1 83 | libuuid=2.32.1=h7f98852_1000 84 | libvorbis=1.3.7=h9c3ff4c_0 85 | libwebp-base=1.2.0=h7f98852_2 86 | libxcb=1.13=h7f98852_1003 87 | libxkbcommon=1.0.3=he3ba5ed_0 88 | libxml2=2.9.12=h72842e0_0 89 | lz4-c=1.9.3=h9c3ff4c_0 90 | markdown=3.3.4=pyhd8ed1ab_0 91 | matplotlib=3.4.2=py37h89c1867_0 92 | matplotlib-base=3.4.2=py37hdd32ed1_0 93 | mkl=2021.3.0=h06a4308_520 94 | mkl-service=2.4.0=py37h5e8e339_0 95 | mkl_fft=1.3.0=py37h42c9631_2 96 | mkl_random=1.2.2=py37h219a48f_0 97 | multidict=5.1.0=py37h5e8e339_1 98 | mysql-common=8.0.25=ha770c72_2 99 | mysql-libs=8.0.25=hfa10184_2 100 | ncurses=6.2=h58526e2_4 101 | nettle=3.6=he412f7d_0 102 | ninja=1.10.2=h4bd325d_0 103 | nspr=4.30=h9c3ff4c_0 104 | nss=3.67=hb5efdd6_0 105 | numpy=1.20.3=py37hf144106_0 106 | numpy-base=1.20.3=py37h74d4b33_0 107 | oauthlib=3.1.1=pyhd8ed1ab_0 108 | olefile=0.46=pyh9f0ad1d_1 109 | opencv=4.5.2=py37h89c1867_0 110 | openh264=2.1.1=h780b84a_0 111 | openjpeg=2.4.0=hb52868f_1 112 | openssl=1.1.1k=h7f98852_0 113 | pandas=1.1.3=py37he6710b0_0 114 | pcre=8.45=h9c3ff4c_0 115 | pillow=8.3.1=py37h0f21c89_0 116 | pip=21.1.3=pyhd8ed1ab_0 117 | pixman=0.40.0=h36c2ea0_0 118 | protobuf=3.15.8=py37hcd2ae1e_0 119 | pthread-stubs=0.4=h36c2ea0_1001 120 | py-opencv=4.5.2=py37h085eea5_0 121 | pyasn1=0.4.8=py_0 122 | pyasn1-modules=0.2.7=py_0 123 | pycparser=2.20=pyh9f0ad1d_2 124 | pyjwt=2.1.0=pyhd8ed1ab_0 125 | pyopenssl=20.0.1=pyhd8ed1ab_0 126 | pyparsing=2.4.7=pyh9f0ad1d_0 127 | pyqt=5.12.3=py37h89c1867_7 128 | pyqt-impl=5.12.3=py37he336c9b_7 129 | pyqt5-sip=4.19.18=py37hcd2ae1e_7 130 | pyqtchart=5.12=py37he336c9b_7 131 | pyqtwebengine=5.12.1=py37he336c9b_7 132 | pysocks=1.7.1=py37h89c1867_3 133 | python=3.7.8=hffdb5ce_3_cpython 134 | python-dateutil=2.8.2=pyhd8ed1ab_0 135 | python_abi=3.7=2_cp37m 136 | pytorch=1.6.0=py3.7_cuda10.2.89_cudnn7.6.5_0 137 | pytz=2020.1=py_0 138 | pyu2f=0.1.5=pyhd8ed1ab_0 139 | qt=5.12.9=hda022c4_4 140 | readline=8.1=h46c0cb4_0 141 | requests=2.26.0=pyhd8ed1ab_0 142 | requests-oauthlib=1.3.0=pyh9f0ad1d_0 143 | rsa=4.7.2=pyh44b312d_0 144 | scikit-learn=0.23.2=py37h0573a6f_0 145 | scipy=1.6.2=py37had2a1c9_1 146 | setuptools=49.6.0=py37h89c1867_3 147 | six=1.16.0=pyh6c4a22f_0 148 | sqlite=3.36.0=h9cd32fc_0 149 | tensorboard=2.5.0=pyhd8ed1ab_0 150 | tensorboard-data-server=0.6.0=py37h7f0c10b_0 151 | tensorboard-plugin-wit=1.8.0=pyh44b312d_0 152 | tensorboardx=2.2=pyhd8ed1ab_0 153 | threadpoolctl=2.1.0=pyh5ca1d4c_0 154 | tk=8.6.10=h21135ba_1 155 | torchvision=0.7.0=py37_cu102 156 | tornado=6.1=py37h5e8e339_1 157 | typing-extensions=3.10.0.0=hd8ed1ab_0 158 | typing_extensions=3.10.0.0=pyha770c72_0 159 | urllib3=1.26.6=pyhd8ed1ab_0 160 | werkzeug=2.0.1=pyhd8ed1ab_0 161 | wheel=0.36.2=pyhd3deb0d_0 162 | x264=1!161.3030=h7f98852_1 163 | xorg-kbproto=1.0.7=h7f98852_1002 164 | xorg-libice=1.0.10=h7f98852_0 165 | xorg-libsm=1.2.3=hd9c2040_1000 166 | xorg-libx11=1.7.2=h7f98852_0 167 | xorg-libxau=1.0.9=h7f98852_0 168 | xorg-libxdmcp=1.1.3=h7f98852_0 169 | xorg-libxext=1.3.4=h7f98852_1 170 | xorg-libxrender=0.9.10=h7f98852_1003 171 | xorg-renderproto=0.11.1=h7f98852_1002 172 | xorg-xextproto=7.3.0=h7f98852_1002 173 | xorg-xproto=7.0.31=h7f98852_1007 174 | xz=5.2.5=h516909a_1 175 | yarl=1.6.3=py37h5e8e339_2 176 | zipp=3.5.0=pyhd8ed1ab_0 177 | zlib=1.2.11=h516909a_1010 178 | zstd=1.5.0=ha95c52a_0 -------------------------------------------------------------------------------- /skeleton_dataset.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data as data 2 | import cv2 3 | import os 4 | import numpy as np 5 | from numpy.random import randint 6 | import pandas as pd 7 | import torch 8 | import torchvision.transforms.functional as tF 9 | from tools.tools import * 10 | 11 | 12 | def rreplace(s, old, new, occurrence): 13 | li = s.rsplit(old, occurrence) 14 | return new.join(li) 15 | 16 | 17 | class VideoRecord(object): 18 | 19 | def __init__(self, row): 20 | self._data = row 21 | 22 | @property 23 | def path(self): 24 | return self._data[0] 25 | 26 | @property 27 | def num_frames(self): 28 | return int(self._data[1]) 29 | 30 | @property 31 | def min_frame(self): 32 | return int(self._data[2]) 33 | 34 | @property 35 | def max_frame(self): 36 | return int(self._data[3]) 37 | 38 | 39 | class SkeletonDataset(data.Dataset): 40 | 41 | def __init__(self, mode, 42 | normalize=True, 43 | centralize=False, 44 | random_choose=False, 45 | random_move=False, 46 | random_shift=False): 47 | 48 | self.bold_path = "/gpu-data2/jpik/BoLD/BOLD_public" 49 | self.test_mode = (mode=='test') 50 | self.mode = mode 51 | 52 | self.categorical_emotions = ["Peace", "Affection", "Esteem", "Anticipation", "Engagement", "Confidence", "Happiness", 53 | "Pleasure", "Excitement", "Surprise", "Sympathy", "Doubt/Confusion", "Disconnect", 54 | "Fatigue", "Embarrassment", "Yearning", "Disapproval", "Aversion", "Annoyance", "Anger", 55 | "Sensitivity", "Sadness", "Disquietment", "Fear", "Pain", "Suffering"] 56 | 57 | self.continuous_emotions = ["Valence", "Arousal", "Dominance"] 58 | 59 | self.attributes = ["Gender", "Age", "Ethnicity"] 60 | 61 | header = ["video", "person_id", "min_frame", "max_frame"] + self.categorical_emotions + self.continuous_emotions + self.attributes + ["annotation_confidence"] 62 | 63 | if not self.test_mode: 64 | self.df = pd.read_csv(os.path.join(self.bold_path, "annotations/{}.csv".format(mode)), names=header) 65 | else: 66 | self.df = pd.read_csv(os.path.join(self.bold_path, "annotations/test_meta.csv"), names=header) 67 | 68 | self.df["joints_path"] = self.df["video"].apply(rreplace,args=[".mp4",".npy",1]) 69 | self.video_list = self.df["video"] 70 | 71 | self.random_choose = random_choose 72 | self.random_move = random_move 73 | self.random_shift = random_shift 74 | self.normalize = normalize 75 | self.centralize = centralize 76 | self.T = 297 # max joint sequence length 77 | 78 | """ 79 | Max joint coordinates per dimension, 80 | per frame, as found within each fold of the 81 | BoLD dataset. 82 | Change paths accordingly. 83 | """ 84 | if mode == "train": 85 | self.max_x = np.load("/home/jpik/NTUA-BEEU-eccv2020-master/BOLD_train_max_x_joint.npy") 86 | self.max_y = np.load("/home/jpik/NTUA-BEEU-eccv2020-master/BOLD_train_max_y_joint.npy") 87 | elif mode == "val": 88 | self.max_x = np.load("/home/jpik/NTUA-BEEU-eccv2020-master/BOLD_val_max_x_joint.npy") 89 | self.max_y = np.load("/home/jpik/NTUA-BEEU-eccv2020-master/BOLD_val_max_y_joint.npy") 90 | elif mode == 'test': 91 | self.max_x = np.load("/home/jpik/NTUA-BEEU-eccv2020-master/BOLD_test_max_x_joint.npy") 92 | self.max_y = np.load("/home/jpik/NTUA-BEEU-eccv2020-master/BOLD_test_max_y_joint.npy") 93 | 94 | 95 | def joints(self, index): 96 | 97 | sample = self.df.iloc[index] 98 | joints_path = os.path.join(self.bold_path, "joints", sample["joints_path"]) 99 | joints18 = np.load(joints_path) 100 | joints18[:,0] -= joints18[0,0] 101 | return joints18 102 | 103 | 104 | def _load_joints(self, directory, idx, index): 105 | 106 | joints = self.joints(index) 107 | 108 | poi_joints = joints[joints[:, 0] + 1 == idx] 109 | sample = self.df.iloc[index] 110 | poi_joints = poi_joints[(poi_joints[:, 1] == sample["person_id"]), 2:] 111 | 112 | if poi_joints.size == 0: 113 | poi_joints = np.zeros((18,3)) 114 | else: 115 | poi_joints = poi_joints.reshape((18,3)) 116 | 117 | poi_joints[poi_joints[:,2]<0.1] = np.nan 118 | poi_joints[np.isnan(poi_joints[:,2])] = np.nan 119 | 120 | return poi_joints 121 | 122 | 123 | def __getitem__(self, index): 124 | 125 | sample = self.df.iloc[index] 126 | 127 | fname = os.path.join(self.bold_path,"videos",self.df.iloc[index]["video"]) 128 | 129 | capture = cv2.VideoCapture(fname) 130 | 131 | frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))-1 132 | 133 | capture.release() 134 | 135 | record_path = os.path.join(self.bold_path,"test_raw",sample["video"][4:-4]) 136 | 137 | record = VideoRecord([record_path, frame_count, sample["min_frame"], sample["max_frame"]]) 138 | 139 | return self.get(record, index) 140 | 141 | 142 | def get(self, record, index): 143 | 144 | joints = list() 145 | 146 | for ind in range(1, record.num_frames): 147 | p = int(ind) 148 | j = self._load_joints(record.path, p, index) 149 | j[np.isnan(j)] = 0 150 | 151 | if self.normalize: 152 | j[:,0] = j[:,0]/float(self.max_x[index]) 153 | j[:,1] = j[:,1]/float(self.max_y[index]) 154 | 155 | if self.centralize: 156 | j[:,0] = j[:,0]-0.5 157 | j[:,1] = j[:,1]-0.5 158 | 159 | joints.append(np.transpose(j)) 160 | 161 | if not self.test_mode: 162 | categorical = self.df.iloc[index][self.categorical_emotions] 163 | continuous = self.df.iloc[index][self.continuous_emotions] 164 | continuous = continuous/10.0 # normalize to 0 - 1 165 | 166 | joints = np.stack(joints, axis=1) 167 | joints = np.array(np.expand_dims(joints, axis=-1)) 168 | 169 | if self.random_shift: 170 | joints = random_shift(joints) 171 | if self.random_choose: 172 | joints = random_choose(joints, self.T) 173 | else: 174 | joints = auto_padding(joints, self.T, random_pad=(self.mode=="train")) 175 | if self.random_move: 176 | joints = random_move(joints) 177 | 178 | if self.mode != 'test': 179 | return torch.tensor(joints).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float() 180 | else: 181 | return torch.tensor(joints).float() 182 | 183 | 184 | def __len__(self): 185 | return len(self.df) -------------------------------------------------------------------------------- /tools/tools.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import random 3 | 4 | def downsample(data_numpy, step, random_sample=True): 5 | # input: C,T,V,M 6 | begin = np.random.randint(step) if random_sample else 0 7 | return data_numpy[:, begin::step, :, :] 8 | 9 | 10 | def temporal_slice(data_numpy, step): 11 | # input: C,T,V,M 12 | C, T, V, M = data_numpy.shape 13 | return data_numpy.reshape(C, T / step, step, V, M).transpose( 14 | (0, 1, 3, 2, 4)).reshape(C, T / step, V, step * M) 15 | 16 | 17 | def mean_subtractor(data_numpy, mean): 18 | # input: C,T,V,M 19 | # naive version 20 | if mean == 0: 21 | return 22 | C, T, V, M = data_numpy.shape 23 | valid_frame = (data_numpy != 0).sum(axis=3).sum(axis=2).sum(axis=0) > 0 24 | begin = valid_frame.argmax() 25 | end = len(valid_frame) - valid_frame[::-1].argmax() 26 | data_numpy[:, :end, :, :] = data_numpy[:, :end, :, :] - mean 27 | return data_numpy 28 | 29 | 30 | def auto_padding(data_numpy, size, random_pad=False): 31 | C, T, V, M = data_numpy.shape 32 | if T < size: 33 | begin = random.randint(0, size - T) if random_pad else 0 34 | data_numpy_paded = np.zeros((C, size, V, M)) 35 | data_numpy_paded[:, begin:begin + T, :, :] = data_numpy 36 | return data_numpy_paded 37 | else: 38 | return data_numpy 39 | 40 | 41 | def random_choose(data_numpy, size, auto_pad=True): 42 | # input: C,T,V,M 43 | C, T, V, M = data_numpy.shape 44 | if T == size: 45 | return data_numpy 46 | elif T < size: 47 | if auto_pad: 48 | return auto_padding(data_numpy, size, random_pad=True) 49 | else: 50 | return data_numpy 51 | else: 52 | begin = random.randint(0, T - size) 53 | return data_numpy[:, begin:begin + size, :, :] 54 | 55 | 56 | def random_move(data_numpy, 57 | angle_candidate=[-10., -5., 0., 5., 10.], 58 | scale_candidate=[0.9, 1.0, 1.1], 59 | transform_candidate=[-0.2, -0.1, 0.0, 0.1, 0.2], 60 | move_time_candidate=[1]): 61 | # input: C,T,V,M 62 | C, T, V, M = data_numpy.shape 63 | move_time = random.choice(move_time_candidate) 64 | node = np.arange(0, T, T * 1.0 / move_time).round().astype(int) 65 | node = np.append(node, T) 66 | num_node = len(node) 67 | 68 | A = np.random.choice(angle_candidate, num_node) 69 | S = np.random.choice(scale_candidate, num_node) 70 | T_x = np.random.choice(transform_candidate, num_node) 71 | T_y = np.random.choice(transform_candidate, num_node) 72 | 73 | a = np.zeros(T) 74 | s = np.zeros(T) 75 | t_x = np.zeros(T) 76 | t_y = np.zeros(T) 77 | 78 | # linspace 79 | for i in range(num_node - 1): 80 | a[node[i]:node[i + 1]] = np.linspace( 81 | A[i], A[i + 1], node[i + 1] - node[i]) * np.pi / 180 82 | s[node[i]:node[i + 1]] = np.linspace(S[i], S[i + 1], 83 | node[i + 1] - node[i]) 84 | t_x[node[i]:node[i + 1]] = np.linspace(T_x[i], T_x[i + 1], 85 | node[i + 1] - node[i]) 86 | t_y[node[i]:node[i + 1]] = np.linspace(T_y[i], T_y[i + 1], 87 | node[i + 1] - node[i]) 88 | 89 | theta = np.array([[np.cos(a) * s, -np.sin(a) * s], 90 | [np.sin(a) * s, np.cos(a) * s]]) 91 | 92 | # perform transformation 93 | for i_frame in range(T): 94 | xy = data_numpy[0:2, i_frame, :, :] 95 | new_xy = np.dot(theta[:, :, i_frame], xy.reshape(2, -1)) 96 | new_xy[0] += t_x[i_frame] 97 | new_xy[1] += t_y[i_frame] 98 | data_numpy[0:2, i_frame, :, :] = new_xy.reshape(2, V, M) 99 | 100 | return data_numpy 101 | 102 | 103 | def random_shift(data_numpy): 104 | # input: C,T,V,M 105 | C, T, V, M = data_numpy.shape 106 | data_shift = np.zeros(data_numpy.shape) 107 | valid_frame = (data_numpy != 0).sum(axis=3).sum(axis=2).sum(axis=0) > 0 108 | begin = valid_frame.argmax() 109 | end = len(valid_frame) - valid_frame[::-1].argmax() 110 | 111 | size = end - begin 112 | bias = random.randint(0, T - size) 113 | data_shift[:, bias:bias + size, :, :] = data_numpy[:, begin:end, :, :] 114 | 115 | return data_shift 116 | 117 | 118 | def openpose_match(data_numpy): 119 | C, T, V, M = data_numpy.shape 120 | assert (C == 3) 121 | score = data_numpy[2, :, :, :].sum(axis=1) 122 | # the rank of body confidence in each frame (shape: T-1, M) 123 | rank = (-score[0:T - 1]).argsort(axis=1).reshape(T - 1, M) 124 | 125 | # data of frame 1 126 | xy1 = data_numpy[0:2, 0:T - 1, :, :].reshape(2, T - 1, V, M, 1) 127 | # data of frame 2 128 | xy2 = data_numpy[0:2, 1:T, :, :].reshape(2, T - 1, V, 1, M) 129 | # square of distance between frame 1&2 (shape: T-1, M, M) 130 | distance = ((xy2 - xy1)**2).sum(axis=2).sum(axis=0) 131 | 132 | # match pose 133 | forward_map = np.zeros((T, M), dtype=int) - 1 134 | forward_map[0] = range(M) 135 | for m in range(M): 136 | choose = (rank == m) 137 | forward = distance[choose].argmin(axis=1) 138 | for t in range(T - 1): 139 | distance[t, :, forward[t]] = np.inf 140 | forward_map[1:][choose] = forward 141 | assert (np.all(forward_map >= 0)) 142 | 143 | # string data 144 | for t in range(T - 1): 145 | forward_map[t + 1] = forward_map[t + 1][forward_map[t]] 146 | 147 | # generate data 148 | new_data_numpy = np.zeros(data_numpy.shape) 149 | for t in range(T): 150 | new_data_numpy[:, t, :, :] = data_numpy[:, t, :, forward_map[ 151 | t]].transpose(1, 2, 0) 152 | data_numpy = new_data_numpy 153 | 154 | # score sort 155 | trace_score = data_numpy[2, :, :, :].sum(axis=1).sum(axis=0) 156 | rank = (-trace_score).argsort() 157 | data_numpy = data_numpy[:, :, :, rank] 158 | 159 | return data_numpy 160 | 161 | 162 | def top_k_by_category(label, score, top_k): 163 | instance_num, class_num = score.shape 164 | rank = score.argsort() 165 | hit_top_k = [[] for i in range(class_num)] 166 | for i in range(instance_num): 167 | l = label[i] 168 | hit_top_k[l].append(l in rank[i, -top_k:]) 169 | 170 | accuracy_list = [] 171 | for hit_per_category in hit_top_k: 172 | if hit_per_category: 173 | accuracy_list.append(sum(hit_per_category) * 1.0 / len(hit_per_category)) 174 | else: 175 | accuracy_list.append(0.0) 176 | return accuracy_list 177 | 178 | 179 | def calculate_recall_precision(label, score): 180 | instance_num, class_num = score.shape 181 | rank = score.argsort() 182 | confusion_matrix = np.zeros([class_num, class_num]) 183 | 184 | for i in range(instance_num): 185 | true_l = label[i] 186 | pred_l = rank[i, -1] 187 | confusion_matrix[true_l][pred_l] += 1 188 | 189 | precision = [] 190 | recall = [] 191 | 192 | for i in range(class_num): 193 | true_p = confusion_matrix[i][i] 194 | false_n = sum(confusion_matrix[i, :]) - true_p 195 | false_p = sum(confusion_matrix[:, i]) - true_p 196 | precision.append(true_p * 1.0 / (true_p + false_p)) 197 | recall.append(true_p * 1.0 / (true_p + false_n)) 198 | 199 | return precision, recall -------------------------------------------------------------------------------- /parse_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | from pathlib import Path 4 | from functools import reduce, partial 5 | from operator import getitem 6 | from datetime import datetime 7 | from logger import setup_logging 8 | from utils import read_json, write_json 9 | 10 | 11 | class ConfigParser: 12 | 13 | def __init__(self, config, resume=None, modification=None, run_id=None): 14 | """ 15 | class to parse configuration json file. Handles hyperparameters for training, initializations of modules, checkpoint saving 16 | and logging module. 17 | :param config: Dict containing configurations, hyperparameters for training. contents of `config.json` file for example. 18 | :param resume: String, path to the checkpoint being loaded. 19 | :param modification: Dict keychain:value, specifying position values to be replaced from config dict. 20 | :param run_id: Unique Identifier for training processes. Used to save checkpoints and training log. Timestamp is being used as default 21 | """ 22 | # load config file and apply modification 23 | self._config = _update_config(config, modification) 24 | self.resume = resume 25 | 26 | # set save_dir where trained model and log will be saved. 27 | save_dir = Path(self.config['trainer']['save_dir']) 28 | check_dir = Path(self.config['trainer']['checkpoint_dir']) 29 | 30 | exper_name = self.config['name'] 31 | if run_id is None: # use timestamp as default run-id 32 | run_id = datetime.now().strftime(r'%m%d_%H%M%S') 33 | 34 | self._save_dir = save_dir / 'models' / exper_name / run_id 35 | self._log_dir = save_dir / 'log' / exper_name / run_id 36 | self._checkpoint_dir = check_dir / exper_name / run_id 37 | 38 | # make directory for saving checkpoints and log. 39 | exist_ok = run_id == '' 40 | self.save_dir.mkdir(parents=True, exist_ok=exist_ok) 41 | self.log_dir.mkdir(parents=True, exist_ok=exist_ok) 42 | if config['trainer']['check_enabled']: 43 | self.checkpoint_dir.mkdir(parents=True, exist_ok=exist_ok) 44 | 45 | # save updated config file to the checkpoint dir 46 | write_json(self.config, self.save_dir / 'config.json') 47 | 48 | # configure logging module 49 | setup_logging(self.log_dir) 50 | self.log_levels = { 51 | 0: logging.WARNING, 52 | 1: logging.INFO, 53 | 2: logging.DEBUG 54 | } 55 | 56 | 57 | @classmethod 58 | def from_args(cls, args, options=''): 59 | """ 60 | Initialize this class from some cli arguments. Used in train, test. 61 | """ 62 | for opt in options: 63 | if hasattr(opt, 'nargs'): 64 | args.add_argument(*opt.flags, default=None, type=opt.type, nargs=opt.nargs) 65 | else: 66 | args.add_argument(*opt.flags, default=None, type=opt.type) 67 | if not isinstance(args, tuple): 68 | args = args.parse_args() 69 | 70 | if args.device is not None: 71 | os.environ["CUDA_VISIBLE_DEVICES"] = args.device 72 | if args.resume is not None: 73 | resume = Path(args.resume) 74 | cfg_fname = resume.parent / 'config.json' 75 | else: 76 | msg_no_cfg = "Configuration file need to be specified. Add '--config config.json', for example." 77 | assert args.config is not None, msg_no_cfg 78 | resume = None 79 | cfg_fname = Path(args.config) 80 | 81 | config = read_json(cfg_fname) 82 | if args.config and resume: 83 | # update new config for fine-tuning 84 | config.update(read_json(args.config)) 85 | 86 | # parse custom cli options into dictionary 87 | modification = {opt.target : getattr(args, _get_opt_name(opt.flags)) for opt in options} 88 | print(modification) 89 | return cls(config, resume, modification) 90 | 91 | 92 | def init_obj(self, name, module, *args, **kwargs): 93 | """ 94 | Finds a function handle with the name given as 'type' in config, and returns the 95 | instance initialized with corresponding arguments given. 96 | 97 | `object = config.init_obj('name', module, a, b=1)` 98 | is equivalent to 99 | `object = module.name(a, b=1)` 100 | """ 101 | module_name = self[name]['type'] 102 | module_args = dict(self[name]['args']) 103 | assert all([k not in module_args for k in kwargs]), 'Overwriting kwargs given in config file is not allowed' 104 | module_args.update(kwargs) 105 | return getattr(module, module_name)(*args, **module_args) 106 | 107 | 108 | def init_ftn(self, name, module, *args, **kwargs): 109 | """ 110 | Finds a function handle with the name given as 'type' in config, and returns the 111 | function with given arguments fixed with functools.partial. 112 | 113 | `function = config.init_ftn('name', module, a, b=1)` 114 | is equivalent to 115 | `function = lambda *args, **kwargs: module.name(a, *args, b=1, **kwargs)`. 116 | """ 117 | module_name = self[name]['type'] 118 | module_args = dict(self[name]['args']) 119 | assert all([k not in module_args for k in kwargs]), 'Overwriting kwargs given in config file is not allowed' 120 | module_args.update(kwargs) 121 | return partial(getattr(module, module_name), *args, **module_args) 122 | 123 | 124 | def __getitem__(self, name): 125 | """Access items like ordinary dict.""" 126 | return self.config[name] 127 | 128 | 129 | def get_logger(self, name, verbosity=2): 130 | msg_verbosity = 'verbosity option {} is invalid. Valid options are {}.'.format(verbosity, self.log_levels.keys()) 131 | assert verbosity in self.log_levels, msg_verbosity 132 | logger = logging.getLogger(name) 133 | logger.setLevel(self.log_levels[verbosity]) 134 | return logger 135 | 136 | 137 | # setting read-only attributes 138 | @property 139 | def config(self): 140 | return self._config 141 | 142 | 143 | @property 144 | def save_dir(self): 145 | return self._save_dir 146 | 147 | 148 | @property 149 | def log_dir(self): 150 | return self._log_dir 151 | 152 | @property 153 | def checkpoint_dir(self): 154 | return self._checkpoint_dir 155 | 156 | 157 | # helper functions to update config dict with custom cli options 158 | def _update_config(config, modification): 159 | if modification is None: 160 | return config 161 | 162 | for k, v in modification.items(): 163 | if v is not None: 164 | _set_by_path(config, k, v) 165 | return config 166 | 167 | 168 | def _get_opt_name(flags): 169 | for flg in flags: 170 | if flg.startswith('--'): 171 | return flg.replace('--', '') 172 | return flags[0].replace('--', '') 173 | 174 | 175 | def _set_by_path(tree, keys, value): 176 | """Set a value in a nested object in tree by sequence of keys.""" 177 | keys = keys.split(';') 178 | _get_by_path(tree, keys[:-1])[keys[-1]] = value 179 | 180 | 181 | def _get_by_path(tree, keys): 182 | """Access a nested object in tree by sequence of keys.""" 183 | return reduce(getitem, keys, tree) -------------------------------------------------------------------------------- /base/base_trainer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from abc import abstractmethod 3 | import numpy as np 4 | from logger import TensorboardWriter 5 | 6 | class BaseTrainer: 7 | """ 8 | Base class for all trainers 9 | """ 10 | def __init__(self, model, optimizer, config): 11 | 12 | self.config = config 13 | self.logger = config.get_logger('trainer', config['trainer']['verbosity']) 14 | 15 | # setup GPU device if available, move model into configured device 16 | self.device, device_ids = self._prepare_device(config['n_gpu']) 17 | self.model = model.to(self.device) 18 | if len(device_ids) > 1: 19 | self.model = torch.nn.DataParallel(model, device_ids=device_ids) 20 | 21 | self.epochs = config['trainer']['epochs'] 22 | self.save_period = config['trainer']['save_period'] 23 | self.monitor = config['trainer']['monitor'] 24 | self.check_enabled = config['trainer']['check_enabled'] 25 | 26 | # configuration to monitor model performance and save best 27 | if self.monitor == 'off': 28 | self.mnt_mode = 'off' 29 | self.mnt_best = 0 30 | else: 31 | self.mnt_mode = config['trainer']['mnt_mode'] 32 | assert self.mnt_mode in ['min', 'max'] 33 | self.mnt_metric = config['trainer']['mnt_metric'] 34 | self.mnt_best = np.Inf if self.mnt_mode == 'min' else -np.Inf 35 | self.early_stop = config['trainer']['early_stop'] 36 | 37 | self.start_epoch = 1 38 | 39 | # setup visualization writer instance 40 | self.writer = TensorboardWriter(config.log_dir, self.logger, config['trainer']['tensorboard']) 41 | 42 | if config.resume is not None: 43 | self._resume_checkpoint(config.resume) 44 | 45 | 46 | @abstractmethod 47 | def _train_epoch(self, epoch): 48 | """ 49 | Training logic for an epoch 50 | 51 | :param epoch: Current epoch number 52 | """ 53 | raise NotImplementedError 54 | 55 | 56 | def train(self): 57 | """ 58 | Full training logic 59 | """ 60 | epochs_no_improve = 0 61 | best_epoch = None 62 | for epoch in range(self.start_epoch, self.epochs + 1): 63 | 64 | result = self._train_epoch(epoch) 65 | 66 | # save logged informations into log dict 67 | log = {'epoch': epoch} 68 | log.update(result) 69 | 70 | # print logged informations to the screen 71 | for key, value in log.items(): 72 | self.logger.info('{:15s}: {}'.format(str(key), value)) 73 | 74 | # evaluate model performance according to configured metric, save best checkpoint as model_best 75 | best = False 76 | if self.mnt_mode != 'off': 77 | try: 78 | # check whether model performance improved or not, according to specified metric(mnt_metric) 79 | improved = (self.mnt_mode == 'min' and log[self.mnt_metric] <= self.mnt_best) or \ 80 | (self.mnt_mode == 'max' and log[self.mnt_metric] >= self.mnt_best) 81 | except KeyError: 82 | self.logger.warning("Warning: Metric '{}' is not found. " 83 | "Model performance monitoring is disabled.".format(self.mnt_metric)) 84 | self.mnt_mode = 'off' 85 | improved = False 86 | 87 | if improved: 88 | self.mnt_best = log[self.mnt_metric] 89 | epochs_no_improve = 0 90 | best_epoch = epoch 91 | best = True 92 | if self.check_enabled: 93 | self._save_checkpoint(epoch, save_best=best) 94 | else: 95 | epochs_no_improve += 1 96 | 97 | if epochs_no_improve > self.early_stop: 98 | self.logger.info("Validation performance didn\'t improve for {} epochs. " 99 | "Training stops.".format(self.early_stop)) 100 | break 101 | 102 | self.logger.info("Current best epoch: {}\n".format(best_epoch)) 103 | 104 | if self.check_enabled: 105 | if epoch % self.save_period == 0 and not best: 106 | self._save_checkpoint(epoch, save_best=False) 107 | 108 | 109 | def _prepare_device(self, n_gpu_use): 110 | """ 111 | setup GPU device if available, move model into configured device 112 | """ 113 | n_gpu = torch.cuda.device_count() 114 | if n_gpu_use > 0 and n_gpu == 0: 115 | self.logger.warning("Warning: There\'s no GPU available on this machine," 116 | "training will be performed on CPU.") 117 | n_gpu_use = 0 118 | if n_gpu_use > n_gpu: 119 | self.logger.warning("Warning: The number of GPU\'s configured to use is {}, but only {} are available " 120 | "on this machine.".format(n_gpu_use, n_gpu)) 121 | n_gpu_use = n_gpu 122 | device = torch.device('cuda:0' if n_gpu_use > 0 else 'cpu') 123 | list_ids = list(range(n_gpu_use)) 124 | return device, list_ids 125 | 126 | 127 | def _save_checkpoint(self, epoch, save_best=False): 128 | """ 129 | Saving checkpoints 130 | 131 | :param epoch: current epoch number 132 | :param log: logging information of the epoch 133 | :param save_best: if True, rename the saved checkpoint to 'model_best.pth' 134 | """ 135 | arch = type(self.model).__name__ 136 | state = { 137 | 'arch': arch, 138 | 'epoch': epoch, 139 | 'state_dict': self.model.state_dict(), 140 | 'optimizer': self.optimizer.state_dict(), 141 | 'monitor_best': self.mnt_best, 142 | 'config': self.config 143 | } 144 | filename = str(self.config.checkpoint_dir / 'checkpoint-epoch-{}.pth'.format(epoch)) 145 | torch.save(state, filename) 146 | self.logger.info("Saving checkpoint: {}".format(filename)) 147 | if save_best: 148 | best_path = str(self.config.checkpoint_dir / 'model_best.pth') 149 | torch.save(state, best_path) 150 | self.logger.info("Saving current best: {}".format(best_path)) 151 | 152 | 153 | def _resume_checkpoint(self, resume_path): 154 | """ 155 | Resume from saved checkpoints 156 | 157 | :param resume_path: Checkpoint path to be resumed 158 | """ 159 | resume_path = str(resume_path) 160 | self.logger.info("Loading checkpoint: {}".format(resume_path)) 161 | checkpoint = torch.load(resume_path) 162 | self.start_epoch = checkpoint['epoch'] + 1 163 | self.mnt_best = checkpoint['monitor_best'] 164 | 165 | # load architecture params from checkpoint. 166 | if checkpoint['config']['arch'] != self.config['arch']: 167 | self.logger.warning("Warning: Architecture configuration given in config file is different from that of " 168 | "checkpoint. This may yield an exception while state_dict is being loaded.") 169 | self.model.load_state_dict(checkpoint['state_dict']) 170 | 171 | # load optimizer state from checkpoint only when optimizer type is not changed. 172 | if checkpoint['config']['optimizer']['type'] != self.config['optimizer']['type']: 173 | self.logger.warning("Warning: Optimizer type given in config file is different from that of checkpoint. " 174 | "Optimizer parameters not being resumed.") 175 | else: 176 | self.optimizer.load_state_dict(checkpoint['optimizer']) 177 | 178 | self.logger.info("Checkpoint loaded. Resume training from epoch {}".format(self.start_epoch)) 179 | -------------------------------------------------------------------------------- /train_stgcn.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import argparse 3 | import collections 4 | import os 5 | import torch 6 | import numpy as np 7 | import model.loss as module_loss 8 | import model.metric as module_metric 9 | from parse_config import ConfigParser 10 | from logger import setup_logging 11 | from trainer.trainer import Trainer 12 | from skeleton_dataset import SkeletonDataset 13 | from model.stgcn import * 14 | 15 | # fix random seeds for reproducibility 16 | SEED = 123 17 | torch.manual_seed(SEED) 18 | torch.backends.cudnn.deterministic = True 19 | torch.backends.cudnn.benchmark = False 20 | np.random.seed(SEED) 21 | 22 | 23 | def main(args, config): 24 | 25 | model = Model(in_channels=args.in_channels, num_class=args.num_classes, num_dim=args.num_dimensions, 26 | layout=args.layout, strategy=args.strategy, max_hop=args.max_hop, dilation=args.dilation, 27 | edge_importance_weighting=args.importance_weighting) 28 | 29 | logger = config.get_logger('train') 30 | 31 | if args.pretrained_kinetics: 32 | 33 | # 1) Load Kinetics pretrained weights. 34 | if not os.access('st_gcn.kinetics-6fa43f73.pth', os.W_OK): 35 | synset_url = 'https://raw.githubusercontent.com/open-mmlab/mmskeleton/master/checkpoints/st_gcn.kinetics-6fa43f73.pth' 36 | os.system('wget ' + synset_url) 37 | pretrained_dict = torch.load('st_gcn.kinetics-6fa43f73.pth') 38 | # 2) Get current model parameter dictionary. 39 | model_dict = model.state_dict() 40 | # 3) Filter out unnecessary keys. 41 | pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} 42 | # 4) Overwrite entries in the existing state dictionary. 43 | model_dict.update(pretrained_dict) 44 | # 5) Load pretrained weights in ST-GCN model. 45 | model.load_state_dict(model_dict) 46 | logger.info("Initialized ST-GCN with Kinetics pretrained weights...") 47 | 48 | logger.info("\nTotal number of network trainable parameters: {}".format(sum(p.numel() for p in model.parameters() if p.requires_grad))) 49 | logger.info(model) 50 | 51 | policies = model.get_optim_policies() 52 | 53 | train_dataset = SkeletonDataset(mode="train", normalize=args.normalize, 54 | centralize=args.centralize, random_choose=args.random_choose, 55 | random_move=args.random_move, random_shift=args.random_shift) 56 | 57 | train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.n_workers, pin_memory=True) 58 | 59 | val_dataset = SkeletonDataset(mode="val", normalize=args.normalize, 60 | centralize=args.centralize, random_choose=False, 61 | random_move=False, random_shift=False) 62 | 63 | val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.n_workers, pin_memory=True) 64 | 65 | optimizer = torch.optim.SGD(policies, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) 66 | lr_scheduler = config.init_obj('lr_scheduler', torch.optim.lr_scheduler, optimizer) 67 | 68 | # get function handles of loss and metrics 69 | criterion_categorical = getattr(module_loss, config['loss_categorical']) 70 | criterion_continuous = getattr(module_loss, config['loss_continuous']) 71 | 72 | metrics_categorical = [getattr(module_metric, met) for met in config['metrics_categorical']] 73 | metrics_continuous = [getattr(module_metric, met) for met in config['metrics_continuous']] 74 | 75 | trainer = Trainer(model, criterion_categorical, criterion_continuous, metrics_categorical, metrics_continuous, optimizer, 76 | config=config, train_dataloader=train_loader, val_dataloader=val_loader, lr_scheduler=lr_scheduler) 77 | 78 | trainer.train() 79 | logger.info('Best result: {}'.format(trainer.mnt_best)) 80 | 81 | 82 | if __name__ == '__main__': 83 | 84 | parser = argparse.ArgumentParser(description='PyTorch Template') 85 | 86 | # ========================= Runtime Configs ========================== 87 | parser.add_argument('--n_workers', default=4, type=int, help='number of data loading workers (default: %(default)s)') 88 | parser.add_argument('--config', default=None, type=str, help='config file path (default: %(default)s)') 89 | parser.add_argument('--resume', default=None, type=str, help='path to latest checkpoint (default: %(default)s)') 90 | parser.add_argument('--device', required=True, type=str, help='indices of GPUs to enable separated by commas') 91 | 92 | # ========================= Model Configs ========================== 93 | parser.add_argument('--layout', type=str, default="openpose", choices=["openpose", "ntu-rgb+d", "ntu_edge"], help="skeleton model layout (default: %(default)s)") 94 | parser.add_argument('--strategy', type=str, default="spatial", choices=["uniform", "distance", "spatial"], help='joint labeling strategy (default: %(default)s)') 95 | parser.add_argument('--in_channels', default=3, type=int, help='number of channels for joint sequences (default: %(default)s)') 96 | parser.add_argument('--max_hop', default=1, type=int, help='maximum limb sequence length between neighboring joints (default: %(default)s)') 97 | parser.add_argument('--dilation', default=1, type=int, help='controls the spacing between the kernel points (default: %(default)s)') 98 | parser.add_argument('--pretrained_kinetics', default=False, action="store_true", help='load Kinetics pretrained weights (default: %(default)s)') 99 | parser.add_argument('--importance_weighting', default=False, action="store_true", help='apply edge importance weighting in ST-GCN units (default: %(default)s)') 100 | 101 | # ========================= Learning Configs ========================== 102 | parser.add_argument('--batch_size', default=16, type=int, help='mini-batch size (default: %(default)s)') 103 | parser.add_argument('--lr', default=0.005, type=float, help='initial learning rate (default: %(default)s)') 104 | parser.add_argument('--momentum', default=0.9, type=float, help='momentum (default: %(default)s)') 105 | parser.add_argument('--weight_decay', default=1e-5, type=float, help='weight decay (default: %(default)s)') 106 | parser.add_argument('--num_classes', type=int, default=26, help='number of emotional classes (default: %(default)s)') 107 | parser.add_argument('--num_dimensions', type=int, default=3, help='number of emotional dimensions (default: %(default)s)') 108 | parser.add_argument('--normalize', default=False, action="store_true", help='normalize 2D joint coordinates in the range [0, 1] (default: %(default)s)') 109 | parser.add_argument('--centralize', default=False, action="store_true", help='normalize 2D joint coordinates in the range [-0.5, 0.5] (default: %(default)s)') 110 | 111 | # ========================= Data Augmentation Configs ========================== 112 | parser.add_argument('--random_move', default=False, action="store_true", help='if true, perform randomly but continuously changed transformation to input sequence (default: %(default)s)') 113 | parser.add_argument('--random_choose', default=False, action="store_true", help='if true, randomly choose a portion of the input sequence (default: %(default)s)') 114 | parser.add_argument('--random_shift', default=False, action="store_true", help='if true, randomly pad zeros at the begining or end of sequence (default: %(default)s)') 115 | 116 | # custom cli options to modify configuration from default values given in json file. 117 | custom_name = collections.namedtuple('custom_name', 'flags type target help') 118 | custom_epochs = collections.namedtuple('custom_epochs', 'flags type target help') 119 | custom_milestones = collections.namedtuple('custom_milestones', 'flags type nargs target help') 120 | 121 | options = [custom_name(['--exp_name'], type=str, target='name', help="custom experiment name (overwrites 'name' value from the configuration file"), 122 | custom_epochs(['--epochs'], type=int, target='trainer;epochs', help="custom number of epochs (overwrites 'trainer->epochs' value from the configuration file"), 123 | custom_milestones(['--milestones'], type=int, nargs='+', target='lr_scheduler;args;milestones', help="custom milestones for scheduler (overwrites 'lr_scheduler->args->milestones' value from the configuration file")] 124 | 125 | config = ConfigParser.from_args(parser, options) 126 | 127 | try: 128 | args = parser.parse_args() 129 | except: 130 | parser.print_help() 131 | sys.exit(0) 132 | 133 | if args.pretrained_kinetics and (args.strategy != 'spatial' or args.dilation != 1 or args.max_hop != 1): 134 | raise ValueError("in order to load Kinetics pretrained weights, the spatial labeling strategy needs to be selected with max_hop=1 and dilation=1") 135 | 136 | main(args, config) -------------------------------------------------------------------------------- /infer_stgcn.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import time 3 | import os 4 | import sys 5 | import numpy as np 6 | import torchvision 7 | from tools.tools import * 8 | import model.metric as module_metric 9 | from skeleton_dataset import SkeletonDataset 10 | from model.stgcn import * 11 | from utils import MetricTracker 12 | from collections import OrderedDict 13 | 14 | SEED = 123 15 | torch.manual_seed(SEED) 16 | torch.backends.cudnn.deterministic = True 17 | torch.backends.cudnn.benchmark = False 18 | np.random.seed(SEED) 19 | 20 | 21 | def _prepare_device(n_gpu_use): 22 | """ 23 | setup GPU device if available, move model into configured device 24 | """ 25 | n_gpu = torch.cuda.device_count() 26 | if n_gpu_use > 0 and n_gpu == 0: 27 | print("Warning: There\'s no GPU available on this machine," 28 | "training will be performed on CPU.") 29 | n_gpu_use = 0 30 | if n_gpu_use > n_gpu: 31 | print("Warning: The number of GPU\'s configured to use is {}, but only {} are available " 32 | "on this machine.".format(n_gpu_use, n_gpu)) 33 | n_gpu_use = n_gpu 34 | device = torch.device('cuda:0' if n_gpu_use > 0 else 'cpu') 35 | list_ids = list(range(n_gpu_use)) 36 | return device, list_ids 37 | 38 | if __name__ == '__main__': 39 | # options 40 | parser = argparse.ArgumentParser(description="Run inference on BoLD with ST-GCN") 41 | 42 | parser.add_argument('--num_classes', type=int, default=26, help='number of emotional classes (default: %(default)s)') 43 | parser.add_argument('--num_dimensions', type=int, default=3, help='number of emotional dimensions (default: %(default)s)') 44 | 45 | parser.add_argument('--batch_size', default=16, type=int, help='mini-batch size (default: %(default)s)') 46 | parser.add_argument('--in_channels', default=3, type=int, help='number of channels for joint sequences (default: %(default)s)') 47 | parser.add_argument('--layout', type=str, default="openpose", choices=["openpose", "ntu-rgb+d", "ntu_edge"], help="skeleton model layout (default: %(default)s)") 48 | parser.add_argument('--strategy', type=str, default="spatial", choices=["uniform", "distance", "spatial"], help='joint labeling strategy (default: %(default)s)') 49 | parser.add_argument('--max_hop', default=1, type=int, help='maximum limb sequence length between neighboring joints (default: %(default)s)') 50 | parser.add_argument('--dilation', default=1, type=int, help='controls the spacing between the kernel points (default: %(default)s)') 51 | parser.add_argument('--importance_weighting', default=False, action="store_true", help='apply edge importance weighting in ST-GCN units (default: %(default)s)') 52 | parser.add_argument('--normalize', default=False, action="store_true", help='normalize 2D joint coordinates in the range [0, 1] (default: %(default)s)') 53 | parser.add_argument('--centralize', default=False, action="store_true", help='normalize 2D joint coordinates in the range [-0.5, 0.5] (default: %(default)s)') 54 | 55 | parser.add_argument('--checkpoint', required=True, type=str, help='pretrained model checkpoint') 56 | parser.add_argument('--output_dir', required=True, type=str, help='directory where to store outputs') 57 | parser.add_argument('--exp_name', type=str, required=True, help='custom experiment name') 58 | 59 | parser.add_argument('--n_workers', default=4, type=int, help='number of data loading workers (default: %(default)s)') 60 | parser.add_argument('--device', required=True, type=str, help='indices of GPUs to enable separated by commas') 61 | parser.add_argument('--n_gpu', default=1, type=int, help='number of GPUs to use (default: %(default)s)') 62 | parser.add_argument('--mode', required=True, type=str, choices=['val', 'test'], help='type of inference to run (default: %(default)s)') 63 | parser.add_argument('--save_outputs', default=False, action="store_true", help='whether to save outputs produced during inference (default: %(default)s)') 64 | 65 | try: 66 | args = parser.parse_args() 67 | except: 68 | parser.print_help() 69 | sys.exit(0) 70 | 71 | os.environ["CUDA_VISIBLE_DEVICES"] = args.device 72 | 73 | model = Model(in_channels=args.in_channels, num_class=args.num_classes, num_dim=args.num_dimensions, 74 | layout=args.layout, strategy=args.strategy, max_hop=args.max_hop, dilation=args.dilation, 75 | edge_importance_weighting=args.importance_weighting) 76 | 77 | _outputs_categorical = [] 78 | _outputs_continuous = [] 79 | _targets_categorical = [] 80 | _targets_continuous = [] 81 | 82 | dataset = SkeletonDataset(mode=args.mode, normalize=args.normalize, 83 | centralize=args.centralize, random_choose=False, 84 | random_move=False, random_shift=False) 85 | 86 | print('\nSet: {}'.format(args.mode)) 87 | 88 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.n_workers, pin_memory=True) 89 | metrics = MetricTracker('ERS', 'mAP', 'mRA', 'mR2', 'mSE', writer=None) 90 | 91 | # Create directory to save predictions 92 | if not os.path.exists(os.path.join(args.output_dir, args.exp_name, args.mode)): 93 | os.makedirs(os.path.join(args.output_dir, args.exp_name, args.mode)) 94 | 95 | # Load checkpoint 96 | print('Checkpoint path: {}'.format(args.checkpoint)) 97 | checkpoint = torch.load(args.checkpoint) 98 | 99 | new_state_dict = OrderedDict() 100 | 101 | for k, v in checkpoint['state_dict'].items(): 102 | if k[:7] == 'module.': 103 | name = k[7:] # remove `module.` 104 | else: 105 | name = k 106 | new_state_dict[name] = v 107 | 108 | model.load_state_dict(new_state_dict) 109 | 110 | # setup GPU device if available, move model into configured device 111 | device, device_ids = _prepare_device(n_gpu_use=args.n_gpu) 112 | model = model.to(device) 113 | if len(device_ids) > 1: 114 | model = torch.nn.DataParallel(model, device_ids=device_ids) 115 | 116 | print("Total number of network trainable parameters: {}".format(sum(p.numel() for p in model.parameters() if p.requires_grad))) 117 | 118 | model.eval() 119 | 120 | with torch.set_grad_enabled(False): 121 | 122 | for batch_idx, batch_data in enumerate(dataloader): 123 | 124 | inputs = {} 125 | if args.mode != 'test': 126 | inputs['skeleton'] = batch_data[0].to(device) 127 | target_categorical = batch_data[1].to(device) 128 | target_continuous= batch_data[2].to(device) 129 | else: 130 | inputs['skeleton'] = batch_data.to(device) 131 | 132 | out = model(inputs) 133 | 134 | output_categorical = out['categorical'].cpu().detach().numpy() 135 | _outputs_categorical.append(output_categorical) 136 | if args.mode != 'test': 137 | targ_categorical = target_categorical.cpu().detach().numpy() 138 | _targets_categorical.append(targ_categorical) 139 | 140 | output_continuous = torch.sigmoid(out['continuous']).cpu().detach().numpy() 141 | _outputs_continuous.append(output_continuous) 142 | if args.mode != 'test': 143 | targ_continuous = target_continuous.cpu().detach().numpy() 144 | _targets_continuous.append(targ_continuous) 145 | 146 | out_cat = np.vstack(_outputs_categorical) 147 | if args.mode != 'test': 148 | target_cat = np.vstack(_targets_categorical) 149 | 150 | if args.mode != 'test': 151 | target_cat[target_cat >= 0.5] = 1 152 | target_cat[target_cat < 0.5] = 0 153 | _ap = module_metric.average_precision(out_cat, target_cat) 154 | _ra = module_metric.roc_auc(out_cat, target_cat) 155 | metrics.update("mAP", np.mean(_ap)) 156 | metrics.update("mRA", np.mean(_ra)) 157 | 158 | out_cont = np.vstack(_outputs_continuous) 159 | if args.mode != 'test': 160 | target_cont = np.vstack(_targets_continuous) 161 | 162 | if args.mode != 'test': 163 | mse = module_metric.mean_squared_error(out_cont, target_cont) 164 | _r2 = module_metric.r2(out_cont, target_cont) 165 | metrics.update("mR2", np.mean(_r2)) 166 | metrics.update("mSE", np.mean(mse)) 167 | metrics.update("ERS", module_metric.ERS(np.mean(_r2), np.mean(_ap), np.mean(_ra))) 168 | 169 | if args.mode != 'test': 170 | log = metrics.result() 171 | print('Printing {} performance metrics...'.format(args.mode)) 172 | print(log) 173 | 174 | if args.mode != 'test': 175 | if args.save_outputs: 176 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cat.npy'), out_cat) 177 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cont.npy'), out_cont) 178 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'target_cat.npy'), target_cat) 179 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'target_cont.npy'), target_cont) 180 | print('Done saving {} outputs and targets!'.format(args.mode)) 181 | else: 182 | combined = np.hstack((out_cont, out_cat)) 183 | if args.save_outputs: 184 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cat.npy'), out_cat) 185 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cont.npy'), out_cont) 186 | np.savetxt(os.path.join(args.output_dir, args.exp_name, args.mode, 'output.csv'), combined, delimiter=",", fmt='%1.6f') 187 | print('Done saving {} outputs!'.format(args.mode)) 188 | print('Done saving {} outputs!'.format(args.mode)) -------------------------------------------------------------------------------- /transforms.py: -------------------------------------------------------------------------------- 1 | import torchvision 2 | import random 3 | from PIL import Image, ImageOps 4 | import numpy as np 5 | import numbers 6 | import math 7 | import torch 8 | 9 | 10 | class GroupRandomCrop(object): 11 | def __init__(self, size): 12 | if isinstance(size, numbers.Number): 13 | self.size = (int(size), int(size)) 14 | else: 15 | self.size = size 16 | 17 | def __call__(self, img_group): 18 | 19 | w, h = img_group[0].size 20 | th, tw = self.size 21 | 22 | out_images = list() 23 | 24 | x1 = random.randint(0, w - tw) 25 | y1 = random.randint(0, h - th) 26 | 27 | for img in img_group: 28 | # assert(img.size[0] == w and img.size[1] == h) 29 | if w == tw and h == th: 30 | out_images.append(img) 31 | else: 32 | out_images.append(img.crop((x1, y1, x1 + tw, y1 + th))) 33 | 34 | return out_images 35 | 36 | 37 | class GroupCenterCrop(object): 38 | def __init__(self, size): 39 | self.worker = torchvision.transforms.CenterCrop(size) 40 | 41 | def __call__(self, img_group): 42 | return [self.worker(img) for img in img_group] 43 | 44 | 45 | class GroupRandomHorizontalFlip(object): 46 | """Randomly horizontally flips the given PIL.Image with a probability of 0.5 47 | """ 48 | def __init__(self, is_flow=False): 49 | self.is_flow = is_flow 50 | 51 | def __call__(self, img_group, is_flow=False): 52 | v = random.random() 53 | if v < 0.5: 54 | ret = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in img_group] 55 | if self.is_flow: 56 | for i in range(0, len(ret), 2): 57 | ret[i] = ImageOps.invert(ret[i]) # invert flow pixel values when flipping 58 | return ret 59 | else: 60 | return img_group 61 | 62 | 63 | class GroupNormalize(object): 64 | def __init__(self, mean, std): 65 | self.mean = mean 66 | self.std = std 67 | 68 | def __call__(self, tensor): 69 | rep_mean = self.mean * (tensor.size()[0]//len(self.mean)) 70 | rep_std = self.std * (tensor.size()[0]//len(self.std)) 71 | 72 | # TODO: make efficient 73 | for t, m, s in zip(tensor, rep_mean, rep_std): 74 | t.sub_(m).div_(s) 75 | 76 | return tensor 77 | 78 | 79 | class GroupScale(object): 80 | """ Rescales the input PIL.Image to the given 'size'. 81 | 'size' will be the size of the smaller edge. 82 | For example, if height > width, then image will be 83 | rescaled to (size * height / width, size) 84 | size: size of the smaller edge 85 | interpolation: Default: PIL.Image.BILINEAR 86 | """ 87 | 88 | def __init__(self, size, interpolation=Image.BILINEAR): 89 | self.worker = torchvision.transforms.Scale(size, interpolation) 90 | 91 | def __call__(self, img_group): 92 | return [self.worker(img) for img in img_group] 93 | 94 | 95 | class GroupOverSample(object): 96 | def __init__(self, crop_size, scale_size=None): 97 | self.crop_size = crop_size if not isinstance(crop_size, int) else (crop_size, crop_size) 98 | 99 | if scale_size is not None: 100 | self.scale_worker = GroupScale(scale_size) 101 | else: 102 | self.scale_worker = None 103 | 104 | def __call__(self, img_group): 105 | 106 | if self.scale_worker is not None: 107 | img_group = self.scale_worker(img_group) 108 | 109 | image_w, image_h = img_group[0].size 110 | crop_w, crop_h = self.crop_size 111 | 112 | offsets = GroupMultiScaleCrop.fill_fix_offset(False, image_w, image_h, crop_w, crop_h) 113 | oversample_group = list() 114 | for o_w, o_h in offsets: 115 | normal_group = list() 116 | flip_group = list() 117 | for i, img in enumerate(img_group): 118 | crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h)) 119 | normal_group.append(crop) 120 | flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT) 121 | 122 | if img.mode == 'L' and i % 2 == 0: 123 | flip_group.append(ImageOps.invert(flip_crop)) 124 | else: 125 | flip_group.append(flip_crop) 126 | 127 | oversample_group.extend(normal_group) 128 | oversample_group.extend(flip_group) 129 | return oversample_group 130 | 131 | 132 | class GroupMultiScaleCrop(object): 133 | 134 | def __init__(self, input_size, scales=None, max_distort=1, fix_crop=True, more_fix_crop=True): 135 | self.scales = scales if scales is not None else [1, .875, .75, .66] 136 | self.max_distort = max_distort 137 | self.fix_crop = fix_crop 138 | self.more_fix_crop = more_fix_crop 139 | self.input_size = input_size if not isinstance(input_size, int) else [input_size, input_size] 140 | self.interpolation = Image.BILINEAR 141 | 142 | def __call__(self, img_group): 143 | 144 | im_size = img_group[0].size 145 | 146 | crop_w, crop_h, offset_w, offset_h = self._sample_crop_size(im_size) 147 | crop_img_group = [img.crop((offset_w, offset_h, offset_w + crop_w, offset_h + crop_h)) for img in img_group] 148 | ret_img_group = [img.resize((self.input_size[0], self.input_size[1]), self.interpolation) 149 | for img in crop_img_group] 150 | return ret_img_group 151 | 152 | def _sample_crop_size(self, im_size): 153 | image_w, image_h = im_size[0], im_size[1] 154 | 155 | # find a crop size 156 | base_size = min(image_w, image_h) 157 | crop_sizes = [int(base_size * x) for x in self.scales] 158 | crop_h = [self.input_size[1] if abs(x - self.input_size[1]) < 3 else x for x in crop_sizes] 159 | crop_w = [self.input_size[0] if abs(x - self.input_size[0]) < 3 else x for x in crop_sizes] 160 | 161 | pairs = [] 162 | for i, h in enumerate(crop_h): 163 | for j, w in enumerate(crop_w): 164 | if abs(i - j) <= self.max_distort: 165 | pairs.append((w, h)) 166 | 167 | crop_pair = random.choice(pairs) 168 | if not self.fix_crop: 169 | w_offset = random.randint(0, image_w - crop_pair[0]) 170 | h_offset = random.randint(0, image_h - crop_pair[1]) 171 | else: 172 | w_offset, h_offset = self._sample_fix_offset(image_w, image_h, crop_pair[0], crop_pair[1]) 173 | 174 | return crop_pair[0], crop_pair[1], w_offset, h_offset 175 | 176 | def _sample_fix_offset(self, image_w, image_h, crop_w, crop_h): 177 | offsets = self.fill_fix_offset(self.more_fix_crop, image_w, image_h, crop_w, crop_h) 178 | return random.choice(offsets) 179 | 180 | @staticmethod 181 | def fill_fix_offset(more_fix_crop, image_w, image_h, crop_w, crop_h): 182 | w_step = (image_w - crop_w) // 4 183 | h_step = (image_h - crop_h) // 4 184 | 185 | ret = list() 186 | ret.append((0, 0)) # upper left 187 | ret.append((4 * w_step, 0)) # upper right 188 | ret.append((0, 4 * h_step)) # lower left 189 | ret.append((4 * w_step, 4 * h_step)) # lower right 190 | ret.append((2 * w_step, 2 * h_step)) # center 191 | 192 | if more_fix_crop: 193 | ret.append((0, 2 * h_step)) # center left 194 | ret.append((4 * w_step, 2 * h_step)) # center right 195 | ret.append((2 * w_step, 4 * h_step)) # lower center 196 | ret.append((2 * w_step, 0 * h_step)) # upper center 197 | 198 | ret.append((1 * w_step, 1 * h_step)) # upper left quarter 199 | ret.append((3 * w_step, 1 * h_step)) # upper right quarter 200 | ret.append((1 * w_step, 3 * h_step)) # lower left quarter 201 | ret.append((3 * w_step, 3 * h_step)) # lower righ quarter 202 | 203 | return ret 204 | 205 | 206 | class GroupRandomSizedCrop(object): 207 | """Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size 208 | and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio 209 | This is popularly used to train the Inception networks 210 | size: size of the smaller edge 211 | interpolation: Default: PIL.Image.BILINEAR 212 | """ 213 | def __init__(self, size, interpolation=Image.BILINEAR): 214 | self.size = size 215 | self.interpolation = interpolation 216 | 217 | def __call__(self, img_group): 218 | for attempt in range(10): 219 | area = img_group[0].size[0] * img_group[0].size[1] 220 | target_area = random.uniform(0.08, 1.0) * area 221 | aspect_ratio = random.uniform(3. / 4, 4. / 3) 222 | 223 | w = int(round(math.sqrt(target_area * aspect_ratio))) 224 | h = int(round(math.sqrt(target_area / aspect_ratio))) 225 | 226 | if random.random() < 0.5: 227 | w, h = h, w 228 | 229 | if w <= img_group[0].size[0] and h <= img_group[0].size[1]: 230 | x1 = random.randint(0, img_group[0].size[0] - w) 231 | y1 = random.randint(0, img_group[0].size[1] - h) 232 | found = True 233 | break 234 | else: 235 | found = False 236 | x1 = 0 237 | y1 = 0 238 | 239 | if found: 240 | out_group = list() 241 | for img in img_group: 242 | img = img.crop((x1, y1, x1 + w, y1 + h)) 243 | assert(img.size == (w, h)) 244 | out_group.append(img.resize((self.size, self.size), self.interpolation)) 245 | return out_group 246 | else: 247 | # Fallback 248 | scale = GroupScale(self.size, interpolation=self.interpolation) 249 | crop = GroupRandomCrop(self.size) 250 | return crop(scale(img_group)) 251 | 252 | 253 | class Stack(object): 254 | 255 | def __init__(self, roll=False): 256 | self.roll = roll 257 | 258 | def __call__(self, img_group): 259 | if img_group[0].mode == 'L': 260 | return np.concatenate([np.expand_dims(x, 2) for x in img_group], axis=2) 261 | elif img_group[0].mode == 'RGB': 262 | if self.roll: 263 | return np.concatenate([np.array(x)[:, :, ::-1] for x in img_group], axis=2) 264 | else: 265 | return np.concatenate(img_group, axis=2) 266 | 267 | 268 | class ToTorchFormatTensor(object): 269 | """ Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] 270 | to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] """ 271 | def __init__(self, div=True): 272 | self.div = div 273 | 274 | def __call__(self, pic): 275 | if isinstance(pic, np.ndarray): 276 | # handle numpy array 277 | img = torch.from_numpy(pic).permute(2, 0, 1).contiguous() 278 | else: 279 | # handle PIL Image 280 | img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) 281 | img = img.view(pic.size[1], pic.size[0], len(pic.mode)) 282 | # put it from HWC to CHW format 283 | # yikes, this transpose takes 80% of the loading time/CPU 284 | img = img.transpose(0, 1).transpose(0, 2).contiguous() 285 | return img.float().div(255) if self.div else img.float() 286 | 287 | 288 | class IdentityTransform(object): 289 | 290 | def __call__(self, data): 291 | return data 292 | 293 | 294 | if __name__ == "__main__": 295 | 296 | trans = torchvision.transforms.Compose([ 297 | GroupScale(256), 298 | GroupRandomCrop(224), 299 | Stack(), 300 | ToTorchFormatTensor(), 301 | GroupNormalize( 302 | mean=[.485, .456, .406], 303 | std=[.229, .224, .225] 304 | )] 305 | ) 306 | 307 | im = Image.open('../tensorflow-model-zoo.torch/lena_299.png') 308 | 309 | color_group = [im] * 3 310 | rst = trans(color_group) 311 | 312 | gray_group = [im.convert('L')] * 9 313 | gray_rst = trans(gray_group) 314 | 315 | trans2 = torchvision.transforms.Compose([ 316 | GroupRandomSizedCrop(256), 317 | Stack(), 318 | ToTorchFormatTensor(), 319 | GroupNormalize( 320 | mean=[.485, .456, .406], 321 | std=[.229, .224, .225]) 322 | ]) 323 | print(trans2(color_group)) -------------------------------------------------------------------------------- /trainer/trainer.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from torchvision.utils import make_grid 4 | from base import BaseTrainer 5 | from utils import inf_loop, MetricTracker, make_barplot 6 | import matplotlib as mpl 7 | import random 8 | import torch.nn.functional as F 9 | 10 | mpl.use('Agg') 11 | import matplotlib.pyplot as plt 12 | import model.metric 13 | import model.loss 14 | 15 | 16 | class Trainer(BaseTrainer): 17 | 18 | def __init__(self, model, criterion_categorical, criterion_continuous, metric_categorical, metric_continuous, optimizer, 19 | config, train_dataloader, val_dataloader, lr_scheduler=None, len_epoch=None, embed=False): 20 | 21 | super().__init__(model, optimizer, config) 22 | 23 | if model.num_rgb_mods > 0: 24 | self.rgb_body = model.rgb_body 25 | self.rgb_context = model.rgb_context 26 | self.rgb_face = model.rgb_face 27 | self.mod = 'RGB' 28 | elif model.num_flow_mods > 0: 29 | self.flow_body = model.flow_body 30 | self.flow_context = model.flow_context 31 | self.flow_face = model.flow_face 32 | self.mod = 'Flow' 33 | elif model.num_diff_mods > 0: 34 | self.rgbdiff_body = model.rgbdiff_body 35 | self.rgbdiff_context = model.rgbdiff_context 36 | self.rgbdiff_face = model.rgbdiff_face 37 | self.mod = 'RGBDiff' 38 | elif model.num_depth_mods > 0: 39 | self.mod = 'Depth' 40 | else: 41 | self.mod = 'Skeleton' 42 | 43 | self.config = config 44 | self.train_dataloader = train_dataloader 45 | self.val_dataloader = val_dataloader 46 | self.do_validation = self.val_dataloader is not None 47 | self.optimizer = optimizer 48 | self.lr_scheduler = lr_scheduler 49 | self.embed = embed 50 | 51 | if len_epoch is None: 52 | # epoch-based training 53 | self.len_epoch = len(self.train_dataloader) 54 | else: 55 | # iteration-based training 56 | self.train_dataloader = inf_loop(train_dataloader) 57 | self.len_epoch = len_epoch 58 | 59 | self.log_step = int(self.len_epoch / 10) 60 | 61 | self.metric_categorical = metric_categorical 62 | self.metric_continuous = metric_continuous 63 | 64 | self.criterion_continuous = criterion_continuous 65 | self.criterion_categorical = criterion_categorical 66 | 67 | self.categorical_class_metrics = [_class + "_" + m.__name__ for _class in val_dataloader.dataset.categorical_emotions for m in self.metric_categorical] 68 | 69 | self.continuous_class_metrics = [_class + "_" + m.__name__ for _class in val_dataloader.dataset.continuous_emotions for m in self.metric_continuous] 70 | 71 | self.train_metrics = MetricTracker('Loss', 'Categorical Loss', 'Continuous Loss', 'Embedding Loss', 'mAP', 'mRA', 'mR2', 'mSE', 'ERS', writer=self.writer) 72 | self.val_metrics = MetricTracker('Loss', 'Categorical Loss', 'Continuous Loss', 'Embedding Loss', 'mAP', 'mRA', 'mR2', 'mSE', 'ERS', writer=self.writer) 73 | 74 | 75 | def _train_epoch(self, epoch, phase="train"): 76 | """ 77 | Training logic for an epoch 78 | :param epoch: Integer, current training epoch. 79 | :return: A log that contains average loss and metrics in this epoch. 80 | """ 81 | 82 | if phase == "train": 83 | self.logger.info("Starting training phase for epoch: {}".format(epoch)) 84 | self.logger.info("Printing learning rates...") 85 | for param_group in self.optimizer.param_groups: 86 | self.logger.info(param_group['lr']) 87 | self.model.train() 88 | self.train_metrics.reset() 89 | torch.set_grad_enabled(True) 90 | metrics = self.train_metrics 91 | 92 | elif phase == "val": 93 | self.logger.info("Starting validation phase for epoch: {}".format(epoch)) 94 | self.model.eval() 95 | self.val_metrics.reset() 96 | torch.set_grad_enabled(False) 97 | metrics = self.val_metrics 98 | 99 | _outputs_categorical = [] 100 | _outputs_continuous = [] 101 | _targets_categorical = [] 102 | _targets_continuous = [] 103 | 104 | running_loss = 0 105 | running_cat_loss = 0 106 | running_cont_loss = 0 107 | running_embed_loss = 0 108 | 109 | total_loss = 0 110 | total_cat_loss = 0 111 | total_cont_loss = 0 112 | total_embed_loss = 0 113 | 114 | dataloader = self.train_dataloader if phase == "train" else self.val_dataloader 115 | 116 | for batch_idx, batch_data in enumerate(dataloader): 117 | 118 | inputs = {} 119 | if self.mod == 'RGB': 120 | if self.rgb_body: 121 | inputs['body'] = batch_data[0].to(self.device) 122 | if self.rgb_face: 123 | inputs['face'] = batch_data[1].to(self.device) 124 | if self.rgb_context: 125 | inputs['context'] = batch_data[6].to(self.device) 126 | elif self.mod == 'Flow': 127 | if self.flow_body: 128 | inputs['body'] = batch_data[0].to(self.device) 129 | if self.flow_face: 130 | inputs['face'] = batch_data[1].to(self.device) 131 | if self.flow_context: 132 | inputs['context'] = batch_data[6].to(self.device) 133 | elif self.mod == 'RGBDiff': 134 | if self.rgbdiff_body: 135 | inputs['body'] = batch_data[0].to(self.device) 136 | if self.rgbdiff_face: 137 | inputs['face'] = batch_data[1].to(self.device) 138 | if self.rgbdiff_context: 139 | inputs['context'] = batch_data[6].to(self.device) 140 | elif self.mod == 'Depth': 141 | raise NotImplementedError() 142 | elif self.mod == 'Skeleton': 143 | inputs['skeleton'] = batch_data[0].to(self.device) 144 | 145 | if self.mod != 'Skeleton': 146 | embeddings = batch_data[2].to(self.device) 147 | target_categorical = batch_data[3].to(self.device) 148 | target_continuous= batch_data[4].to(self.device) 149 | else: 150 | target_categorical = batch_data[1].to(self.device) 151 | target_continuous= batch_data[2].to(self.device) 152 | 153 | if phase == "train": 154 | self.optimizer.zero_grad() 155 | 156 | if self.mod != 'Skeleton': 157 | out = self.model(inputs, dataloader.dataset.num_segments) 158 | else: 159 | out = self.model(inputs) 160 | 161 | loss = 0 162 | 163 | loss_categorical = self.criterion_categorical(out['categorical'], target_categorical) 164 | loss += loss_categorical 165 | running_cat_loss += loss_categorical.item() 166 | 167 | loss_continuous = self.criterion_continuous(torch.sigmoid(out['continuous']), target_continuous) 168 | loss += loss_continuous 169 | running_cont_loss += loss_continuous.item() 170 | 171 | if self.embed: 172 | loss_embed = model.loss.mse_center_loss(out['embeddings'], embeddings, target_categorical) 173 | loss += loss_embed 174 | running_embed_loss += loss_embed.item() 175 | total_embed_loss += loss_embed.item() 176 | 177 | if phase == "train": 178 | loss.backward() 179 | self.optimizer.step() 180 | 181 | running_loss += loss.item() 182 | total_loss += loss.item() 183 | total_cat_loss += loss_categorical.item() 184 | total_cont_loss += loss_continuous.item() 185 | 186 | output_categorical = out['categorical'].cpu().detach().numpy() 187 | targ_categorical = target_categorical.cpu().detach().numpy() 188 | _outputs_categorical.append(output_categorical) 189 | _targets_categorical.append(targ_categorical) 190 | 191 | output_continuous = torch.sigmoid(out['continuous']).cpu().detach().numpy() 192 | targ_continuous = target_continuous.cpu().detach().numpy() 193 | _outputs_continuous.append(output_continuous) 194 | _targets_continuous.append(targ_continuous) 195 | 196 | if (batch_idx % self.log_step == self.log_step - 1) and phase == 'train': 197 | self.logger.info('[Epoch: {}] {} [Total Loss: {:.4f}] [Categorical Loss: {:.4f}] [Continuous Loss: {:.4f}] [Embedding Loss: {:.4f}]'.format(epoch, 198 | self._progress(batch_idx), 199 | running_loss / self.log_step, running_cat_loss / self.log_step, running_cont_loss / self.log_step, running_embed_loss / self.log_step)) 200 | 201 | running_loss = 0 202 | running_cat_loss = 0 203 | running_cont_loss = 0 204 | running_embed_loss = 0 205 | 206 | if batch_idx == self.len_epoch and phase == 'train': 207 | break 208 | 209 | self.writer.set_step(epoch, phase) 210 | 211 | if phase == 'val': 212 | metrics.update('Loss', total_loss / len(dataloader)) 213 | metrics.update('Categorical Loss', total_cat_loss / len(dataloader)) 214 | metrics.update('Continuous Loss', total_cont_loss / len(dataloader)) 215 | if self.embed: 216 | metrics.update('Embedding Loss', total_embed_loss / len(dataloader)) 217 | else: 218 | metrics.update('Loss', total_loss / self.len_epoch) 219 | metrics.update('Categorical Loss', total_cat_loss / self.len_epoch) 220 | metrics.update('Continuous Loss', total_cont_loss / self.len_epoch) 221 | if self.embed: 222 | metrics.update('Embedding Loss', total_embed_loss / self.len_epoch) 223 | 224 | out_cat = np.vstack(_outputs_categorical) 225 | target_cat = np.vstack(_targets_categorical) 226 | 227 | target_cat[target_cat >= 0.5] = 1 228 | target_cat[target_cat < 0.5] = 0 229 | 230 | _ap = model.metric.average_precision(out_cat, target_cat) 231 | _ra = model.metric.roc_auc(out_cat, target_cat) 232 | metrics.update("mAP", np.mean(_ap)) 233 | metrics.update("mRA", np.mean(_ra)) 234 | 235 | out_cont = np.vstack(_outputs_continuous) 236 | target_cont = np.vstack(_targets_continuous) 237 | 238 | mse = model.metric.mean_squared_error(out_cont, target_cont) 239 | _r2 = model.metric.r2(out_cont, target_cont) 240 | metrics.update("mR2", np.mean(_r2)) 241 | metrics.update("mSE", np.mean(mse)) 242 | metrics.update("ERS", model.metric.ERS(np.mean(_r2), np.mean(_ap), np.mean(_ra))) 243 | 244 | log = metrics.result() 245 | 246 | self.writer.add_figure('%s AP per class' % phase, make_barplot(_ap, self.val_dataloader.dataset.categorical_emotions, 'average precision')) 247 | self.writer.add_figure('%s ROC AUC per class' % phase, make_barplot(_ra, self.val_dataloader.dataset.categorical_emotions, 'roc auc')) 248 | self.writer.add_figure('%s R2 per dimension' % phase, make_barplot(_r2, self.val_dataloader.dataset.continuous_emotions, 'r2')) 249 | 250 | if phase == "train": 251 | 252 | if self.lr_scheduler is not None: 253 | self.lr_scheduler.step() 254 | 255 | if self.do_validation: 256 | val_log = self._train_epoch(epoch, phase="val") 257 | log.update(**{'Validation ' + k: v for k, v in val_log.items()}) 258 | 259 | return log 260 | 261 | elif phase == "val": 262 | self.writer.save_results(out_cat, "out_cat") 263 | self.writer.save_results(out_cont, "out_cont") 264 | return metrics.result() 265 | 266 | 267 | def _progress(self, batch_idx): 268 | base = '[{}/{} ({:.0f}%)]' 269 | if hasattr(self.train_dataloader, 'n_samples'): 270 | current = batch_idx * self.train_dataloader.batch_size 271 | total = self.train_dataloader.n_samples 272 | else: 273 | current = batch_idx 274 | total = self.len_epoch 275 | return base.format(current, total, 100.0 * current / total) -------------------------------------------------------------------------------- /train_tsn.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import argparse 3 | import collections 4 | import torch 5 | import numpy as np 6 | import model.loss as module_loss 7 | import model.metric as module_metric 8 | from parse_config import ConfigParser 9 | from transforms import * 10 | from logger import setup_logging 11 | from model import loss 12 | from trainer.trainer import Trainer 13 | from dataset import TSNDataset 14 | from model.models import TSN 15 | 16 | # fix random seeds for reproducibility 17 | SEED = 123 18 | torch.manual_seed(SEED) 19 | torch.backends.cudnn.deterministic = True 20 | torch.backends.cudnn.benchmark = False 21 | np.random.seed(SEED) 22 | 23 | def main(args, config): 24 | 25 | logger = config.get_logger('train') 26 | 27 | model = TSN(logger=logger, num_classes=args.num_classes, num_dimensions=args.num_dimensions, 28 | rgb_body=args.rgb_body, rgb_context=args.rgb_context, rgb_face=args.rgb_face, 29 | flow_body=args.flow_body, flow_context=args.flow_context, flow_face=args.flow_face, 30 | scenes=args.scenes, attributes=args.attributes, depth=(args.modality=='Depth'), 31 | rgbdiff_body=args.rgbdiff_body, rgbdiff_context=args.rgbdiff_context, rgbdiff_face=args.rgbdiff_face, 32 | arch=args.arch, consensus_type=args.consensus_type, partial_bn=args.partial_bn, embed=args.embed, 33 | pretrained_affectnet=args.pretrained_affectnet, pretrained_places=args.pretrained_places, 34 | pretrained_imagenet=args.pretrained_imagenet) 35 | 36 | logger.info("\nTotal number of network trainable parameters: {}".format(sum(p.numel() for p in model.parameters() if p.requires_grad))) 37 | logger.info(model) 38 | 39 | rgb_mean = model.rgb_mean 40 | rgb_std = model.rgb_std 41 | flow_mean = model.flow_mean 42 | flow_std = model.flow_std 43 | depth_mean = model.depth_mean 44 | depth_std = model.depth_std 45 | diff_mean = model.diff_mean 46 | diff_std = model.diff_std 47 | 48 | policies = model.get_optim_policies() 49 | 50 | rgb_normalize = GroupNormalize(rgb_mean, rgb_std) 51 | flow_normalize = GroupNormalize(flow_mean, flow_std) 52 | depth_normalize = GroupNormalize(depth_mean, depth_std) 53 | diff_normalize = GroupNormalize(diff_mean, diff_std) 54 | 55 | train_dataset = TSNDataset(mode="train", num_segments=args.train_segments, 56 | inp_type=args.modality, 57 | rgb_transform=torchvision.transforms.Compose([ 58 | GroupScale((224,224)), 59 | Stack(roll=False), 60 | ToTorchFormatTensor(div=True), 61 | rgb_normalize 62 | ]), 63 | flow_transform=torchvision.transforms.Compose([ 64 | GroupScale((224,224)), 65 | Stack(roll=False), 66 | ToTorchFormatTensor(div=True), 67 | flow_normalize 68 | ]), 69 | depth_transform=torchvision.transforms.Compose([ 70 | GroupScale((224,224)), 71 | Stack(roll=False), 72 | ToTorchFormatTensor(div=True), 73 | depth_normalize 74 | ]), 75 | diff_transform=torchvision.transforms.Compose([ 76 | GroupScale((224,224)), 77 | Stack(roll=False), 78 | ToTorchFormatTensor(div=True), 79 | diff_normalize 80 | ]), 81 | random_shift=True, 82 | context=args.context) 83 | 84 | train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.n_workers, pin_memory=True) 85 | 86 | val_dataset = TSNDataset(mode="val", num_segments=args.val_segments, 87 | inp_type=args.modality, 88 | rgb_transform=torchvision.transforms.Compose([ 89 | GroupScale((224,224)), 90 | Stack(roll=False), 91 | ToTorchFormatTensor(div=True), 92 | rgb_normalize 93 | ]), 94 | flow_transform=torchvision.transforms.Compose([ 95 | GroupScale((224,224)), 96 | Stack(roll=False), 97 | ToTorchFormatTensor(div=True), 98 | flow_normalize 99 | ]), 100 | depth_transform=torchvision.transforms.Compose([ 101 | GroupScale((224,224)), 102 | Stack(roll=False), 103 | ToTorchFormatTensor(div=True), 104 | depth_normalize 105 | ]), 106 | diff_transform=torchvision.transforms.Compose([ 107 | GroupScale((224,224)), 108 | Stack(roll=False), 109 | ToTorchFormatTensor(div=True), 110 | diff_normalize 111 | ]), 112 | random_shift=False, 113 | context=args.context) 114 | 115 | val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.n_workers, pin_memory=True) 116 | 117 | optimizer = torch.optim.SGD(policies, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) 118 | """ 119 | Starting epoch is set to 1 120 | Consider the fact that the learning rate is reduced one epoch after each milestone 121 | """ 122 | lr_scheduler = config.init_obj('lr_scheduler', torch.optim.lr_scheduler, optimizer) 123 | 124 | # get function handles of loss and metrics 125 | criterion_categorical = getattr(module_loss, config['loss_categorical']) 126 | criterion_continuous = getattr(module_loss, config['loss_continuous']) 127 | 128 | metrics_categorical = [getattr(module_metric, met) for met in config['metrics_categorical']] 129 | metrics_continuous = [getattr(module_metric, met) for met in config['metrics_continuous']] 130 | 131 | trainer = Trainer(model, criterion_categorical, criterion_continuous, metrics_categorical, metrics_continuous, optimizer, config=config, train_dataloader=train_loader, val_dataloader=val_loader, lr_scheduler=lr_scheduler, embed=args.embed) 132 | 133 | trainer.train() 134 | logger.info('Best result: {}'.format(trainer.mnt_best)) 135 | 136 | 137 | if __name__ == '__main__': 138 | 139 | parser = argparse.ArgumentParser(description='Multi-modal, multi-stream TSN training on the Body Language Dataset (BoLD)') 140 | 141 | # ========================= Runtime Configs ========================== 142 | parser.add_argument('--n_workers', default=4, type=int, help='number of data loading workers (default: %(default)s)') 143 | parser.add_argument('--config', default=None, type=str, help='config file path (default: %(default)s)') 144 | parser.add_argument('--resume', default=None, type=str, help='path to latest checkpoint (default: %(default)s)') 145 | parser.add_argument('--device', required=True, type=str, help='indices of GPUs to enable separated by commas') 146 | 147 | # ========================= Model Configs ========================== 148 | parser.add_argument('--arch', type=str, default="resnet18", choices=["resnet18", "resnet50"], help="CNN backbone architecture (default: %(default)s)") 149 | parser.add_argument('--train_segments', type=int, default=3, help='number of segments used during training (default: %(default)s)') 150 | parser.add_argument('--val_segments', type=int, default=25, help='number of segments used during validation (default: %(default)s)') 151 | parser.add_argument('--consensus_type', type=str, default='avg', choices=['avg', 'linear_weighting', 'attention_weighting'], help='segmental consensus function (default: %(default)s)') 152 | 153 | # ========================= Learning Configs ========================== 154 | parser.add_argument('--batch_size', default=16, type=int, help='mini-batch size (default: %(default)s)') 155 | parser.add_argument('--lr', '--learning_rate', default=0.001, type=float, help='initial learning rate (default: %(default)s)') 156 | parser.add_argument('--momentum', default=0.9, type=float, help='momentum (default: %(default)s)') 157 | parser.add_argument('--weight_decay', default=1e-5, type=float, help='weight decay (default: %(default)s)') 158 | parser.add_argument('--partial_bn', default=False, action="store_true", help='partial batch normalization (default: %(default)s)') 159 | parser.add_argument('--context', default=False, action="store_true", help='load context data (default: %(default)s)') 160 | parser.add_argument('--embed', default=False, action="store_true", help='use embedding loss (default: %(default)s)') 161 | parser.add_argument('--num_classes', type=int, default=26, help='number of emotional classes (default: %(default)s)') 162 | parser.add_argument('--num_dimensions', type=int, default=3, help='number of emotional dimensions (default: %(default)s)') 163 | 164 | # ========================= Modality Config ========================== 165 | parser.add_argument('--modality', type=str, choices=['RGB', 'Flow', 'RGBDiff', 'Depth'], required=True, help='input data modality') 166 | 167 | # ========================= TSN Model Stream Configs ========================== 168 | parser.add_argument('--rgb_body', default=False, action="store_true", help='use RGB body stream (default: %(default)s)') 169 | parser.add_argument('--rgb_context', default=False, action="store_true", help='use RGB context stream (default: %(default)s)') 170 | parser.add_argument('--rgb_face', default=False, action="store_true", help='use RGB face stream (default: %(default)s)') 171 | parser.add_argument('--scenes', default=False, action="store_true", help='use RGB scenes stream (default: %(default)s)') 172 | parser.add_argument('--attributes', default=False, action="store_true", help='use RGB attributes stream (default: %(default)s)') 173 | 174 | parser.add_argument('--flow_body', default=False, action="store_true", help='use Flow body stream (default: %(default)s)') 175 | parser.add_argument('--flow_context', default=False, action="store_true", help='use Flow context stream (default: %(default)s)') 176 | parser.add_argument('--flow_face', default=False, action="store_true", help='use Flow face stream (default: %(default)s)') 177 | 178 | parser.add_argument('--rgbdiff_body', default=False, action="store_true", help='use RGBDiff body stream (default: %(default)s)') 179 | parser.add_argument('--rgbdiff_context', default=False, action="store_true", help='use RGBDiff context stream (default: %(default)s)') 180 | parser.add_argument('--rgbdiff_face', default=False, action="store_true", help='use RGBDiff face stream (default: %(default)s)') 181 | 182 | # ========================= TSN Stream Pretraining Configs ========================== 183 | parser.add_argument('--pretrained_affectnet', default=False, action="store_true", help='load AffectNet pretrained weights, for RGB face stream (default: %(default)s)') 184 | parser.add_argument('--pretrained_places', default=False, action="store_true", help='load Places365 pretrained weights, for RGB context stream (default: %(default)s)') 185 | parser.add_argument('--pretrained_imagenet', default=False, action="store_true", help='load ImageNet pretrained weights, for RGB body stream and all Flow/RGBDiff streams (default: %(default)s)') 186 | 187 | # custom cli options to modify configuration from default values given in json file. 188 | custom_name = collections.namedtuple('custom_name', 'flags type target help') 189 | custom_epochs = collections.namedtuple('custom_epochs', 'flags type target help') 190 | custom_milestones = collections.namedtuple('custom_milestones', 'flags type nargs target help') 191 | 192 | options = [custom_name(['--exp_name'], type=str, target='name', help="custom experiment name (overwrites 'name' value from the configuration file"), 193 | custom_epochs(['--epochs'], type=int, target='trainer;epochs', help="custom number of epochs (overwrites 'trainer->epochs' value from the configuration file"), 194 | custom_milestones(['--milestones'], type=int, nargs='+', target='lr_scheduler;args;milestones', help="custom milestones for scheduler (overwrites 'lr_scheduler->args->milestones' value from the configuration file")] 195 | 196 | config = ConfigParser.from_args(parser, options) 197 | 198 | try: 199 | args = parser.parse_args() 200 | except: 201 | parser.print_help() 202 | sys.exit(0) 203 | 204 | if args.modality == 'RGB': 205 | if not args.rgb_body and not args.rgb_context and not args.rgb_face: 206 | raise ValueError("At least one RGB stream needs to be specified when using the RGB input modality") 207 | if (args.scenes or args.attributes) and not args.rgb_context: 208 | raise ValueError("The scenes and attributes streams require the RGB context stream") 209 | if args.context != args.rgb_context: 210 | raise ValueError("The RGB context stream requires context data to be loaded from the dataset") 211 | elif args.modality == 'Flow': 212 | if not args.flow_body and not args.flow_context and not args.flow_face: 213 | raise ValueError("At least one Optical Flow stream needs to be specified when using the Optical Flow input modality") 214 | if args.context != args.flow_context: 215 | raise ValueError("The Optical Flow context stream requires context data to be loaded from the dataset") 216 | elif args.modality == 'RGBDiff': 217 | if not args.rgbdiff_body and not args.rgbdiff_context and not args.rgbdiff_face: 218 | raise ValueError("At least one RGB Difference stream needs to be specified when using the RGB Difference input modality") 219 | if args.context != args.rgbdiff_context: 220 | raise ValueError("The RGB Difference context stream requires context data to be loaded from the dataset") 221 | main(args, config) -------------------------------------------------------------------------------- /model/stgcn.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from torch.autograd import Variable 6 | 7 | 8 | class Graph(): 9 | """ The Graph to model the skeletons extracted by the openpose 10 | Args: 11 | strategy (string): must be one of the follow candidates 12 | - uniform: Uniform Labeling 13 | - distance: Distance Partitioning 14 | - spatial: Spatial Configuration 15 | For more information, please refer to the section 'Partition Strategies' 16 | in our paper (https://arxiv.org/abs/1801.07455). 17 | layout (string): must be one of the follow candidates 18 | - openpose: Is consists of 18 joints. For more information, please 19 | refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose#output 20 | - ntu-rgb+d: Is consists of 25 joints. For more information, please 21 | refer to https://github.com/shahroudy/NTURGB-D 22 | max_hop (int): the maximal distance between two connected nodes 23 | dilation (int): controls the spacing between the kernel points 24 | """ 25 | 26 | def __init__(self, 27 | layout='openpose', 28 | strategy='uniform', 29 | max_hop=1, 30 | dilation=1): 31 | self.max_hop = max_hop 32 | self.dilation = dilation 33 | self.get_edge(layout) 34 | self.hop_dis = get_hop_distance(self.num_node, self.edge, max_hop=max_hop) 35 | self.get_adjacency(strategy) 36 | 37 | 38 | def __str__(self): 39 | return self.A 40 | 41 | 42 | def get_edge(self, layout): 43 | if layout == 'openpose': 44 | self.num_node = 18 45 | self_link = [(i, i) for i in range(self.num_node)] 46 | neighbor_link = [(4, 3), (3, 2), (7, 6), (6, 5), (13, 12), (12, 47 | 11), 48 | (10, 9), (9, 8), (11, 5), (8, 2), (5, 1), (2, 1), 49 | (0, 1), (15, 0), (14, 0), (17, 15), (16, 14)] 50 | self.edge = self_link + neighbor_link 51 | self.center = 1 52 | elif layout == 'ntu-rgb+d': 53 | self.num_node = 25 54 | self_link = [(i, i) for i in range(self.num_node)] 55 | neighbor_1base = [(1, 2), (2, 21), (3, 21), (4, 3), (5, 21), 56 | (6, 5), (7, 6), (8, 7), (9, 21), (10, 9), 57 | (11, 10), (12, 11), (13, 1), (14, 13), (15, 14), 58 | (16, 15), (17, 1), (18, 17), (19, 18), (20, 19), 59 | (22, 23), (23, 8), (24, 25), (25, 12)] 60 | neighbor_link = [(i - 1, j - 1) for (i, j) in neighbor_1base] 61 | self.edge = self_link + neighbor_link 62 | self.center = 21 - 1 63 | elif layout == 'ntu_edge': 64 | self.num_node = 24 65 | self_link = [(i, i) for i in range(self.num_node)] 66 | neighbor_1base = [(1, 2), (3, 2), (4, 3), (5, 2), (6, 5), (7, 6), 67 | (8, 7), (9, 2), (10, 9), (11, 10), (12, 11), 68 | (13, 1), (14, 13), (15, 14), (16, 15), (17, 1), 69 | (18, 17), (19, 18), (20, 19), (21, 22), (22, 8), 70 | (23, 24), (24, 12)] 71 | neighbor_link = [(i - 1, j - 1) for (i, j) in neighbor_1base] 72 | self.edge = self_link + neighbor_link 73 | self.center = 2 74 | elif layout=='customer settings': 75 | pass 76 | else: 77 | raise ValueError("The given layout does not exist") 78 | 79 | 80 | def get_adjacency(self, strategy): 81 | valid_hop = range(0, self.max_hop + 1, self.dilation) 82 | adjacency = np.zeros((self.num_node, self.num_node)) 83 | for hop in valid_hop: 84 | adjacency[self.hop_dis == hop] = 1 85 | normalize_adjacency = normalize_undigraph(adjacency) 86 | 87 | if strategy == 'uniform': 88 | A = np.zeros((1, self.num_node, self.num_node)) 89 | A[0] = normalize_adjacency 90 | self.A = A 91 | elif strategy == 'distance': 92 | A = np.zeros((len(valid_hop), self.num_node, self.num_node)) 93 | for i, hop in enumerate(valid_hop): 94 | A[i][self.hop_dis == hop] = normalize_adjacency[self.hop_dis == hop] 95 | self.A = A 96 | elif strategy == 'spatial': 97 | A = [] 98 | for hop in valid_hop: 99 | a_root = np.zeros((self.num_node, self.num_node)) 100 | a_close = np.zeros((self.num_node, self.num_node)) 101 | a_further = np.zeros((self.num_node, self.num_node)) 102 | for i in range(self.num_node): 103 | for j in range(self.num_node): 104 | if self.hop_dis[j, i] == hop: 105 | if self.hop_dis[j, self.center] == self.hop_dis[i, self.center]: 106 | a_root[j, i] = normalize_adjacency[j, i] 107 | elif self.hop_dis[j, self.center] > self.hop_dis[i, self.center]: 108 | a_close[j, i] = normalize_adjacency[j, i] 109 | else: 110 | a_further[j, i] = normalize_adjacency[j, i] 111 | if hop == 0: 112 | A.append(a_root) 113 | else: 114 | A.append(a_root + a_close) 115 | A.append(a_further) 116 | A = np.stack(A) 117 | self.A = A 118 | else: 119 | raise ValueError("This strategy does not exist!") 120 | 121 | 122 | def get_hop_distance(num_node, edge, max_hop=1): 123 | A = np.zeros((num_node, num_node)) 124 | for i, j in edge: 125 | A[j, i] = 1 126 | A[i, j] = 1 127 | # compute hop steps 128 | hop_dis = np.zeros((num_node, num_node)) + np.inf 129 | transfer_mat = [np.linalg.matrix_power(A, d) for d in range(max_hop + 1)] 130 | arrive_mat = (np.stack(transfer_mat) > 0) 131 | for d in range(max_hop, -1, -1): 132 | hop_dis[arrive_mat[d]] = d 133 | return hop_dis 134 | 135 | 136 | def normalize_digraph(A): 137 | Dl = np.sum(A, 0) 138 | num_node = A.shape[0] 139 | Dn = np.zeros((num_node, num_node)) 140 | for i in range(num_node): 141 | if Dl[i] > 0: 142 | Dn[i, i] = Dl[i]**(-1) 143 | AD = np.dot(A, Dn) 144 | return AD 145 | 146 | 147 | def normalize_undigraph(A): 148 | Dl = np.sum(A, 0) 149 | num_node = A.shape[0] 150 | Dn = np.zeros((num_node, num_node)) 151 | for i in range(num_node): 152 | if Dl[i] > 0: 153 | Dn[i, i] = Dl[i]**(-0.5) 154 | DAD = np.dot(np.dot(Dn, A), Dn) 155 | return DAD 156 | 157 | 158 | class ConvTemporalGraphical(nn.Module): 159 | 160 | """The basic module for applying a graph convolution. 161 | Args: 162 | in_channels (int): Number of channels in the input sequence data 163 | out_channels (int): Number of channels produced by the convolution 164 | kernel_size (int): Size of the graph convolving kernel 165 | t_kernel_size (int): Size of the temporal convolving kernel 166 | t_stride (int, optional): Stride of the temporal convolution. Default: 1 167 | t_padding (int, optional): Temporal zero-padding added to both sides of 168 | the input. Default: 0 169 | t_dilation (int, optional): Spacing between temporal kernel elements. 170 | Default: 1 171 | bias (bool, optional): If ``True``, adds a learnable bias to the output. 172 | Default: ``True`` 173 | Shape: 174 | - Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format 175 | - Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format 176 | - Output[0]: Outpu graph sequence in :math:`(N, out_channels, T_{out}, V)` format 177 | - Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format 178 | where 179 | :math:`N` is a batch size, 180 | :math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`, 181 | :math:`T_{in}/T_{out}` is a length of input/output sequence, 182 | :math:`V` is the number of graph nodes. 183 | """ 184 | 185 | def __init__(self, 186 | in_channels, 187 | out_channels, 188 | kernel_size, 189 | t_kernel_size=1, 190 | t_stride=1, 191 | t_padding=0, 192 | t_dilation=1, 193 | bias=True): 194 | super().__init__() 195 | 196 | self.kernel_size = kernel_size 197 | self.conv = nn.Conv2d( 198 | in_channels, 199 | out_channels * kernel_size, 200 | kernel_size=(t_kernel_size, 1), 201 | padding=(t_padding, 0), 202 | stride=(t_stride, 1), 203 | dilation=(t_dilation, 1), 204 | bias=bias) 205 | 206 | 207 | def forward(self, x, A): 208 | assert A.size(0) == self.kernel_size 209 | x = self.conv(x) 210 | n, kc, t, v = x.size() 211 | x = x.view(n, self.kernel_size, kc//self.kernel_size, t, v) 212 | x = torch.einsum('nkctv,kvw->nctw', (x, A)) 213 | return x.contiguous(), A 214 | 215 | 216 | class Model(nn.Module): 217 | """Spatial temporal graph convolutional networks. 218 | Args: 219 | in_channels (int): Number of channels in the input data 220 | num_class (int): Number of classes for the classification task 221 | graph_args (dict): The arguments for building the graph 222 | edge_importance_weighting (bool): If ``True``, adds a learnable 223 | importance weighting to the edges of the graph 224 | **kwargs (optional): Other parameters for graph convolution units 225 | Shape: 226 | - Input: :math:`(N, in_channels, T_{in}, V_{in}, M_{in})` 227 | - Output: :math:`(N, num_class)` where 228 | :math:`N` is a batch size, 229 | :math:`T_{in}` is a length of input sequence, 230 | :math:`V_{in}` is the number of graph nodes, 231 | :math:`M_{in}` is the number of instance in a frame. 232 | """ 233 | 234 | def __init__(self, in_channels, num_class, num_dim, 235 | layout, strategy, max_hop, dilation, 236 | edge_importance_weighting, **kwargs): 237 | super().__init__() 238 | 239 | self.num_rgb_mods = 0 240 | self.num_flow_mods = 0 241 | self.num_depth_mods = 0 242 | self.num_diff_mods = 0 243 | 244 | # load graph 245 | self.graph = Graph(layout, strategy, max_hop, dilation) 246 | A = torch.tensor(self.graph.A, dtype=torch.float32, requires_grad=False) 247 | self.register_buffer('A', A) 248 | # build networks 249 | spatial_kernel_size = A.size(0) 250 | temporal_kernel_size = 9 251 | kernel_size = (temporal_kernel_size, spatial_kernel_size) 252 | self.data_bn = nn.BatchNorm1d(in_channels * A.size(1)) 253 | kwargs0 = {k: v for k, v in kwargs.items() if k != 'dropout'} 254 | self.st_gcn_networks = nn.ModuleList(( 255 | st_gcn(in_channels, 64, kernel_size, 1, residual=False, **kwargs0), 256 | st_gcn(64, 64, kernel_size, 1, **kwargs), 257 | st_gcn(64, 64, kernel_size, 1, **kwargs), 258 | st_gcn(64, 64, kernel_size, 1, **kwargs), 259 | st_gcn(64, 128, kernel_size, 2, **kwargs), 260 | st_gcn(128, 128, kernel_size, 1, **kwargs), 261 | st_gcn(128, 128, kernel_size, 1, **kwargs), 262 | st_gcn(128, 256, kernel_size, 2, **kwargs), 263 | st_gcn(256, 256, kernel_size, 1, **kwargs), 264 | st_gcn(256, 256, kernel_size, 1, **kwargs), 265 | )) 266 | 267 | # initialize parameters for edge importance weighting 268 | if edge_importance_weighting: 269 | self.edge_importance = nn.ParameterList([ 270 | nn.Parameter(torch.ones(self.A.size())) 271 | for i in self.st_gcn_networks 272 | ]) 273 | else: 274 | self.edge_importance = [1] * len(self.st_gcn_networks) 275 | 276 | # fcn for prediction/regression 277 | self.fcn_cat = nn.Conv2d(256, num_class, kernel_size=1) 278 | self.fcn_cont = nn.Conv2d(256, num_dim, kernel_size=1) 279 | 280 | 281 | def forward(self, inputs): 282 | 283 | x = inputs['skeleton'] 284 | 285 | # data normalization 286 | N, C, T, V, M = x.size() 287 | x = x.permute(0, 4, 3, 1, 2).contiguous() 288 | x = x.view(N * M, V * C, T) 289 | x = self.data_bn(x) 290 | x = x.view(N, M, V, C, T) 291 | x = x.permute(0, 1, 3, 4, 2).contiguous() 292 | x = x.view(N * M, C, T, V) 293 | 294 | # forward 295 | for gcn, importance in zip(self.st_gcn_networks, self.edge_importance): 296 | x, _ = gcn(x, self.A * importance) 297 | 298 | # global pooling 299 | x = F.avg_pool2d(x, x.size()[2:]) 300 | x = x.view(N, M, -1, 1, 1).mean(dim=1) 301 | 302 | outputs = {} 303 | 304 | #prediction/regresssion 305 | y_cat = self.fcn_cat(x) 306 | y_cat = y_cat.view(y_cat.size(0), -1) 307 | outputs['categorical'] = y_cat 308 | 309 | y_cont = self.fcn_cont(x) 310 | y_cont = y_cont.view(y_cont.size(0), -1) 311 | outputs['continuous'] = y_cont 312 | 313 | return outputs 314 | 315 | 316 | def get_optim_policies(self): 317 | params = [{'params': self.parameters()}] 318 | return params 319 | 320 | 321 | class st_gcn(nn.Module): 322 | """Applies a spatial temporal graph convolution over an input graph sequence. 323 | Args: 324 | in_channels (int): Number of channels in the input sequence data 325 | out_channels (int): Number of channels produced by the convolution 326 | kernel_size (tuple): Size of the temporal convolving kernel and graph convolving kernel 327 | stride (int, optional): Stride of the temporal convolution. Default: 1 328 | dropout (int, optional): Dropout rate of the final output. Default: 0 329 | residual (bool, optional): If ``True``, applies a residual mechanism. Default: ``True`` 330 | Shape: 331 | - Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format 332 | - Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format 333 | - Output[0]: Outpu graph sequence in :math:`(N, out_channels, T_{out}, V)` format 334 | - Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format 335 | where 336 | :math:`N` is a batch size, 337 | :math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`, 338 | :math:`T_{in}/T_{out}` is a length of input/output sequence, 339 | :math:`V` is the number of graph nodes. 340 | """ 341 | 342 | def __init__(self, 343 | in_channels, 344 | out_channels, 345 | kernel_size, 346 | stride=1, 347 | dropout=0, 348 | residual=True): 349 | super().__init__() 350 | 351 | assert len(kernel_size) == 2 352 | assert kernel_size[0] % 2 == 1 353 | padding = ((kernel_size[0] - 1) // 2, 0) 354 | 355 | self.gcn = ConvTemporalGraphical(in_channels, out_channels, 356 | kernel_size[1]) 357 | 358 | self.tcn = nn.Sequential( 359 | nn.BatchNorm2d(out_channels), 360 | nn.ReLU(inplace=True), 361 | nn.Conv2d( 362 | out_channels, 363 | out_channels, 364 | (kernel_size[0], 1), 365 | (stride, 1), 366 | padding, 367 | ), 368 | nn.BatchNorm2d(out_channels), 369 | nn.Dropout(dropout, inplace=True), 370 | ) 371 | 372 | if not residual: 373 | self.residual = lambda x: 0 374 | 375 | elif (in_channels == out_channels) and (stride == 1): 376 | self.residual = lambda x: x 377 | 378 | else: 379 | self.residual = nn.Sequential( 380 | nn.Conv2d( 381 | in_channels, 382 | out_channels, 383 | kernel_size=1, 384 | stride=(stride, 1)), 385 | nn.BatchNorm2d(out_channels), 386 | ) 387 | 388 | self.relu = nn.ReLU(inplace=True) 389 | 390 | 391 | def forward(self, x, A): 392 | 393 | res = self.residual(x) 394 | x, A = self.gcn(x, A) 395 | x = self.tcn(x) + res 396 | 397 | return self.relu(x), A -------------------------------------------------------------------------------- /infer_tsn.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import time 3 | import os 4 | import sys 5 | import numpy as np 6 | import torchvision 7 | from transforms import * 8 | import model.metric as module_metric 9 | from dataset import TSNDataset 10 | from model.models import TSN 11 | from utils import MetricTracker 12 | from collections import OrderedDict 13 | 14 | SEED = 123 15 | torch.manual_seed(SEED) 16 | torch.backends.cudnn.deterministic = True 17 | torch.backends.cudnn.benchmark = False 18 | np.random.seed(SEED) 19 | 20 | 21 | def _prepare_device(n_gpu_use): 22 | """ 23 | setup GPU device if available, move model into configured device 24 | """ 25 | n_gpu = torch.cuda.device_count() 26 | if n_gpu_use > 0 and n_gpu == 0: 27 | print("Warning: There\'s no GPU available on this machine," 28 | "training will be performed on CPU.") 29 | n_gpu_use = 0 30 | if n_gpu_use > n_gpu: 31 | print("Warning: The number of GPU\'s configured to use is {}, but only {} are available " 32 | "on this machine.".format(n_gpu_use, n_gpu)) 33 | n_gpu_use = n_gpu 34 | device = torch.device('cuda:0' if n_gpu_use > 0 else 'cpu') 35 | list_ids = list(range(n_gpu_use)) 36 | return device, list_ids 37 | 38 | if __name__ == '__main__': 39 | # options 40 | parser = argparse.ArgumentParser(description="Run inference on BoLD with TSN") 41 | 42 | parser.add_argument('--modality', type=str, choices=['RGB', 'Flow', 'RGBDiff', 'Depth'], required=True, help='input data modality') 43 | parser.add_argument('--num_classes', type=int, default=26, help='number of emotional classes (default: %(default)s)') 44 | parser.add_argument('--num_dimensions', type=int, default=3, help='number of emotional dimensions (default: %(default)s)') 45 | parser.add_argument('--num_segments', type=int, default=25, help='number of segments to use during inference (default: %(default)s)') 46 | parser.add_argument('--arch', type=str, default="resnet18", choices=["resnet18", "resnet50"], help="CNN backbone architecture (default: %(default)s)") 47 | parser.add_argument('--consensus_type', type=str, default='avg', choices=['avg', 'linear_weighting', 'attention_weighting'], help='segmental consensus function (default: %(default)s)') 48 | parser.add_argument('--batch_size', default=16, type=int, help='mini-batch size (default: %(default)s)') 49 | 50 | parser.add_argument('--rgb_body', default=False, action="store_true", help='use RGB body stream (default: %(default)s)') 51 | parser.add_argument('--rgb_context', default=False, action="store_true", help='use RGB context stream (default: %(default)s)') 52 | parser.add_argument('--rgb_face', default=False, action="store_true", help='use RGB face stream (default: %(default)s)') 53 | parser.add_argument('--scenes', default=False, action="store_true", help='use RGB scenes stream (default: %(default)s)') 54 | parser.add_argument('--attributes', default=False, action="store_true", help='use RGB attributes stream (default: %(default)s)') 55 | 56 | parser.add_argument('--flow_body', default=False, action="store_true", help='use Flow body stream (default: %(default)s)') 57 | parser.add_argument('--flow_context', default=False, action="store_true", help='use Flow context stream (default: %(default)s)') 58 | parser.add_argument('--flow_face', default=False, action="store_true", help='use Flow face stream (default: %(default)s)') 59 | 60 | parser.add_argument('--rgbdiff_body', default=False, action="store_true", help='use RGBDiff body stream (default: %(default)s)') 61 | parser.add_argument('--rgbdiff_context', default=False, action="store_true", help='use RGBDiff context stream (default: %(default)s)') 62 | parser.add_argument('--rgbdiff_face', default=False, action="store_true", help='use RGBDiff face stream (default: %(default)s)') 63 | 64 | parser.add_argument('--partial_bn', default=False, action="store_true", help='partial batch normalization (default: %(default)s)') 65 | parser.add_argument('--context', default=False, action="store_true", help='load context data (default: %(default)s)') 66 | parser.add_argument('--embed', default=False, action="store_true", help='use embedding loss (default: %(default)s)') 67 | 68 | parser.add_argument('--checkpoint', required=True, type=str, help='pretrained model checkpoint') 69 | parser.add_argument('--output_dir', required=True, type=str, help='directory where to store outputs') 70 | parser.add_argument('--exp_name', type=str, required=True, help='custom experiment name') 71 | 72 | parser.add_argument('--n_workers', default=4, type=int, help='number of data loading workers (default: %(default)s)') 73 | parser.add_argument('--device', default=None, type=str, help='indices of GPUs to enable separated by commas (default: all)') 74 | parser.add_argument('--n_gpu', default=1, type=int, help='number of GPUs to use (default: %(default)s)') 75 | parser.add_argument('--mode', required=True, type=str, choices=['val', 'test'], help='type of inference to run (default: %(default)s)') 76 | parser.add_argument('--save_outputs', default=False, action="store_true", help='whether to save outputs produced during inference (default: %(default)s)') 77 | 78 | try: 79 | args = parser.parse_args() 80 | except: 81 | parser.print_help() 82 | sys.exit(0) 83 | 84 | os.environ["CUDA_VISIBLE_DEVICES"] = args.device 85 | 86 | if args.modality == 'RGB': 87 | if not args.rgb_body and not args.rgb_context and not args.rgb_face: 88 | raise ValueError("At least one RGB stream needs to be specified when using the RGB input modality") 89 | if (args.scenes or args.attributes) and not args.rgb_context: 90 | raise ValueError("The 'scenes' and 'attributes' streams require the RGB context stream") 91 | if args.context != args.rgb_context: 92 | raise ValueError("The RGB 'context' stream requires 'context' data to be loaded from the dataset") 93 | elif args.modality == 'Flow': 94 | if not args.flow_body and not args.flow_context and not args.flow_face: 95 | raise ValueError("At least one Optical Flow stream needs to be specified when using the Optical Flow input modality") 96 | if args.context != args.flow_context: 97 | raise ValueError("The Optical Flow 'context' stream requires 'context' data to be loaded from the dataset") 98 | elif args.modality == 'RGBDiff': 99 | if not args.rgbdiff_body and not args.rgbdiff_context and not args.rgbdiff_face: 100 | raise ValueError("At least one RGB Difference stream needs to be specified when using the RGB Difference input modality") 101 | if args.context != args.rgbdiff_context: 102 | raise ValueError("The RGB Difference 'context' stream requires 'context' data to be loaded from the dataset") 103 | 104 | model = TSN(logger=None, num_classes=args.num_classes, num_dimensions=args.num_dimensions, 105 | rgb_body=args.rgb_body, rgb_context=args.rgb_context, rgb_face=args.rgb_face, 106 | flow_body=args.flow_body, flow_context=args.flow_context, flow_face=args.flow_face, 107 | scenes=args.scenes, attributes=args.attributes, depth=(args.modality=='Depth'), 108 | rgbdiff_body=args.rgbdiff_body, rgbdiff_context=args.rgbdiff_context, rgbdiff_face=args.rgbdiff_face, 109 | arch=args.arch, consensus_type=args.consensus_type, partial_bn=args.partial_bn, embed=args.embed, 110 | pretrained_affectnet=False, pretrained_places=False, pretrained_imagenet=False) 111 | 112 | _outputs_categorical = [] 113 | _outputs_continuous = [] 114 | _targets_categorical = [] 115 | _targets_continuous = [] 116 | 117 | rgb_mean = model.rgb_mean 118 | rgb_std = model.rgb_std 119 | flow_mean = model.flow_mean 120 | flow_std = model.flow_std 121 | depth_mean = model.depth_mean 122 | depth_std = model.depth_std 123 | diff_mean = model.diff_mean 124 | diff_std = model.diff_std 125 | 126 | rgb_normalize = GroupNormalize(rgb_mean, rgb_std) 127 | flow_normalize = GroupNormalize(flow_mean, flow_std) 128 | depth_normalize = GroupNormalize(depth_mean, depth_std) 129 | diff_normalize = GroupNormalize(diff_mean, diff_std) 130 | 131 | dataset = TSNDataset(mode=args.mode, num_segments=args.num_segments, 132 | inp_type=args.modality, 133 | rgb_transform=torchvision.transforms.Compose([ 134 | GroupScale((224,224)), 135 | Stack(roll=False), 136 | ToTorchFormatTensor(div=True), 137 | rgb_normalize 138 | ]), 139 | flow_transform=torchvision.transforms.Compose([ 140 | GroupScale((224,224)), 141 | Stack(roll=False), 142 | ToTorchFormatTensor(div=True), 143 | flow_normalize 144 | ]), 145 | depth_transform=torchvision.transforms.Compose([ 146 | GroupScale((224,224)), 147 | Stack(roll=False), 148 | ToTorchFormatTensor(div=True), 149 | depth_normalize 150 | ]), 151 | diff_transform=torchvision.transforms.Compose([ 152 | GroupScale((224,224)), 153 | Stack(roll=False), 154 | ToTorchFormatTensor(div=True), 155 | diff_normalize 156 | ]), 157 | random_shift=False, 158 | context=args.context) 159 | 160 | print('\nSet: {}'.format(args.mode)) 161 | 162 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.n_workers, pin_memory=True) 163 | 164 | metrics = MetricTracker('ERS', 'mAP', 'mRA', 'mR2', 'mSE', writer=None) 165 | 166 | # Create directory to save predictions 167 | if not os.path.exists(os.path.join(args.output_dir, args.exp_name, args.mode)): 168 | os.makedirs(os.path.join(args.output_dir, args.exp_name, args.mode)) 169 | 170 | # Load checkpoint 171 | print('Checkpoint path: {}'.format(args.checkpoint)) 172 | checkpoint = torch.load(args.checkpoint) 173 | 174 | new_state_dict = OrderedDict() 175 | 176 | for k, v in checkpoint['state_dict'].items(): 177 | if k[:7] == 'module.': 178 | name = k[7:] # remove `module.` 179 | else: 180 | name = k 181 | new_state_dict[name] = v 182 | 183 | model.load_state_dict(new_state_dict) 184 | 185 | # setup GPU device if available, move model into configured device 186 | device, device_ids = _prepare_device(n_gpu_use=args.n_gpu) 187 | model = model.to(device) 188 | if len(device_ids) > 1: 189 | model = torch.nn.DataParallel(model, device_ids=device_ids) 190 | 191 | print("Total number of network trainable parameters: {}".format(sum(p.numel() for p in model.parameters() if p.requires_grad))) 192 | 193 | model.eval() 194 | 195 | with torch.set_grad_enabled(False): 196 | 197 | for batch_idx, batch_data in enumerate(dataloader): 198 | 199 | inputs = {} 200 | if args.mode != 'test': 201 | if args.modality == 'RGB': 202 | if model.rgb_body: 203 | inputs['body'] = batch_data[0].to(device) 204 | if model.rgb_face: 205 | inputs['face'] = batch_data[1].to(device) 206 | if model.rgb_context: 207 | inputs['context'] = batch_data[6].to(device) 208 | elif args.modality == 'Flow': 209 | if model.flow_body: 210 | inputs['body'] = batch_data[0].to(device) 211 | if model.flow_face: 212 | inputs['face'] = batch_data[1].to(device) 213 | if model.flow_context: 214 | inputs['context'] = batch_data[6].to(device) 215 | elif args.modality == 'RGBDiff': 216 | if args.model.rgbdiff_body: 217 | inputs['body'] = batch_data[0].to(device) 218 | if args.model.rgbdiff_face: 219 | inputs['face'] = batch_data[1].to(device) 220 | if args.model.rgbdiff_context: 221 | inputs['context'] = batch_data[6].to(device) 222 | else: 223 | raise NotImplementedError() 224 | 225 | embeddings = batch_data[2].to(device) 226 | target_categorical = batch_data[3].to(device) 227 | target_continuous= batch_data[4].to(device) 228 | 229 | else: 230 | if args.modality == 'RGB': 231 | if model.rgb_body: 232 | inputs['body'] = batch_data[0].to(device) 233 | if model.rgb_face: 234 | inputs['face'] = batch_data[1].to(device) 235 | if model.rgb_context: 236 | inputs['context'] = batch_data[4].to(device) 237 | elif args.modality == 'Flow': 238 | if model.flow_body: 239 | inputs['body'] = batch_data[0].to(device) 240 | if model.flow_face: 241 | inputs['face'] = batch_data[1].to(device) 242 | if model.flow_context: 243 | inputs['context'] = batch_data[4].to(device) 244 | elif args.modality == 'RGBDiff': 245 | if args.model.rgbdiff_body: 246 | inputs['body'] = batch_data[0].to(device) 247 | if args.model.rgbdiff_face: 248 | inputs['face'] = batch_data[1].to(device) 249 | if args.model.rgbdiff_context: 250 | inputs['context'] = batch_data[4].to(device) 251 | else: 252 | raise NotImplementedError() 253 | 254 | embeddings = batch_data[2].to(device) 255 | 256 | out = model(inputs, args.num_segments) 257 | 258 | output_categorical = out['categorical'].cpu().detach().numpy() 259 | _outputs_categorical.append(output_categorical) 260 | if args.mode != 'test': 261 | targ_categorical = target_categorical.cpu().detach().numpy() 262 | _targets_categorical.append(targ_categorical) 263 | 264 | output_continuous = torch.sigmoid(out['continuous']).cpu().detach().numpy() 265 | _outputs_continuous.append(output_continuous) 266 | if args.mode != 'test': 267 | targ_continuous = target_continuous.cpu().detach().numpy() 268 | _targets_continuous.append(targ_continuous) 269 | 270 | out_cat = np.vstack(_outputs_categorical) 271 | if args.mode != 'test': 272 | target_cat = np.vstack(_targets_categorical) 273 | 274 | if args.mode != 'test': 275 | target_cat[target_cat >= 0.5] = 1 276 | target_cat[target_cat < 0.5] = 0 277 | _ap = module_metric.average_precision(out_cat, target_cat) 278 | _ra = module_metric.roc_auc(out_cat, target_cat) 279 | metrics.update("mAP", np.mean(_ap)) 280 | metrics.update("mRA", np.mean(_ra)) 281 | 282 | out_cont = np.vstack(_outputs_continuous) 283 | if args.mode != 'test': 284 | target_cont = np.vstack(_targets_continuous) 285 | 286 | if args.mode != 'test': 287 | mse = module_metric.mean_squared_error(out_cont, target_cont) 288 | _r2 = module_metric.r2(out_cont, target_cont) 289 | metrics.update("mR2", np.mean(_r2)) 290 | metrics.update("mSE", np.mean(mse)) 291 | metrics.update("ERS", module_metric.ERS(np.mean(_r2), np.mean(_ap), np.mean(_ra))) 292 | 293 | if args.mode != 'test': 294 | log = metrics.result() 295 | print('Printing {} performance metrics...'.format(args.mode)) 296 | print(log) 297 | 298 | if args.mode != 'test': 299 | if args.save_outputs: 300 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cat.npy'), out_cat) 301 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cont.npy'), out_cont) 302 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'target_cat.npy'), target_cat) 303 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'target_cont.npy'), target_cont) 304 | print('Done saving {} outputs and targets!'.format(args.mode)) 305 | else: 306 | combined = np.hstack((out_cont, out_cat)) 307 | if args.save_outputs: 308 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cat.npy'), out_cat) 309 | np.save(os.path.join(args.output_dir, args.exp_name, args.mode, 'output_cont.npy'), out_cont) 310 | np.savetxt(os.path.join(args.output_dir, args.exp_name, args.mode, 'output.csv'), combined, delimiter=",", fmt='%1.6f') 311 | print('Done saving {} outputs!'.format(args.mode)) -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data as data 2 | import cv2 3 | from PIL import Image 4 | import os 5 | import os.path 6 | import numpy as np 7 | from numpy.random import randint 8 | import pandas as pd 9 | import torch 10 | import torchvision.transforms.functional as tF 11 | 12 | 13 | def rreplace(s, old, new, occurrence): 14 | li = s.rsplit(old, occurrence) 15 | return new.join(li) 16 | 17 | 18 | class VideoRecord(object): 19 | 20 | def __init__(self, row): 21 | self._data = row 22 | 23 | @property 24 | def path(self): 25 | return self._data[0] 26 | 27 | @property 28 | def num_frames(self): 29 | return int(self._data[1]) 30 | 31 | @property 32 | def min_frame(self): 33 | return int(self._data[2]) 34 | 35 | @property 36 | def max_frame(self): 37 | return int(self._data[3]) 38 | 39 | 40 | class TSNDataset(data.Dataset): 41 | 42 | def __init__(self, mode, 43 | num_segments=3, 44 | inp_type='RGB', 45 | rgb_transform=None, 46 | flow_transform=None, 47 | depth_transform=None, 48 | diff_transform=None, 49 | random_shift=True, 50 | context=True): 51 | 52 | # Change the template accordingly 53 | self.rgb_tmpl = "img_{:05d}.jpg" 54 | self.flow_tmpl = "{}_{:05d}.jpg" 55 | 56 | self.num_segments = num_segments 57 | self.rgb_transform = rgb_transform 58 | self.flow_transform = flow_transform 59 | self.depth_transform = depth_transform 60 | self.diff_transform = diff_transform 61 | self.random_shift = random_shift 62 | self.test_mode = (mode=='test') 63 | self.inp_type = inp_type 64 | 65 | # Change the path accordingly 66 | self.bold_path = "/gpu-data2/jpik/BoLD/BOLD_public" 67 | 68 | self.context = context 69 | self.mode = mode 70 | 71 | self.categorical_emotions = ["Peace", "Affection", "Esteem", "Anticipation", "Engagement", "Confidence", "Happiness", 72 | "Pleasure", "Excitement", "Surprise", "Sympathy", "Doubt/Confusion", "Disconnect", 73 | "Fatigue", "Embarrassment", "Yearning", "Disapproval", "Aversion", "Annoyance", "Anger", 74 | "Sensitivity", "Sadness", "Disquietment", "Fear", "Pain", "Suffering"] 75 | 76 | self.continuous_emotions = ["Valence", "Arousal", "Dominance"] 77 | 78 | self.attributes = ["Gender", "Age", "Ethnicity"] 79 | 80 | header = ["video", "person_id", "min_frame", "max_frame"] + self.categorical_emotions + self.continuous_emotions + self.attributes + ["annotation_confidence"] 81 | 82 | if not self.test_mode: 83 | self.df = pd.read_csv(os.path.join(self.bold_path, "annotations/{}.csv".format(mode)), names=header) 84 | else: 85 | self.df = pd.read_csv(os.path.join(self.bold_path, "annotations/test_meta.csv"), names=header) 86 | 87 | self.df["joints_path"] = self.df["video"].apply(rreplace,args=[".mp4",".npy",1]) 88 | 89 | self.video_list = self.df["video"] 90 | 91 | # Change the path accordingly 92 | self.embeddings = np.load("glove_840B_embeddings.npy") 93 | 94 | if inp_type=='RGB': 95 | self.data_length = 5 96 | elif inp_type=='Flow': 97 | self.data_length = 5 98 | elif inp_type=='RGBDiff': 99 | self.data_length = 6 100 | elif inp_type=='Depth': 101 | raise NotImplementedError 102 | 103 | 104 | def get_context(self, image, joints, format="cv2"): 105 | 106 | joints = joints.reshape((18,3)) 107 | joints[joints[:,2]<0.1] = np.nan 108 | joints[np.isnan(joints[:,2])] = np.nan 109 | 110 | joint_min_x = int(round(np.nanmin(joints[:,0]))) 111 | joint_min_y = int(round(np.nanmin(joints[:,1]))) 112 | 113 | joint_max_x = int(round(np.nanmax(joints[:,0]))) 114 | joint_max_y = int(round(np.nanmax(joints[:,1]))) 115 | 116 | expand_x = int(round(10/100 * (joint_max_x-joint_min_x))) 117 | expand_y = int(round(10/100 * (joint_max_y-joint_min_y))) 118 | 119 | if format == "cv2": 120 | 121 | image[max(0, joint_min_x - expand_x):min(joint_max_x + expand_x, image.shape[1])] = [0,0,0] 122 | 123 | elif format == "PIL": 124 | 125 | bottom = min(joint_max_y+expand_y, image.height) 126 | right = min(joint_max_x+expand_x,image.width) 127 | top = max(0,joint_min_y-expand_y) 128 | left = max(0,joint_min_x-expand_x) 129 | image = np.array(image) 130 | 131 | if len(image.shape) == 3: 132 | image[top:bottom,left:right] = [0,0,0] 133 | else: 134 | image[top:bottom,left:right] = np.min(image) 135 | return Image.fromarray(image) 136 | 137 | 138 | def get_bounding_box(self, image, joints, format="cv2"): 139 | 140 | joints = joints.reshape((18,3)) 141 | joints[joints[:,2]<0.1] = np.nan 142 | joints[np.isnan(joints[:,2])] = np.nan 143 | 144 | joint_min_x = int(round(np.nanmin(joints[:,0]))) 145 | joint_min_y = int(round(np.nanmin(joints[:,1]))) 146 | 147 | joint_max_x = int(round(np.nanmax(joints[:,0]))) 148 | joint_max_y = int(round(np.nanmax(joints[:,1]))) 149 | 150 | expand_x = int(round(100/100 * (joint_max_x-joint_min_x))) 151 | expand_y = int(round(100/100 * (joint_max_y-joint_min_y))) 152 | 153 | if format == "cv2": 154 | return image[max(0,joint_min_y-expand_y):min(joint_max_y+expand_y, image.shape[0]), max(0,joint_min_x-expand_x):min(joint_max_x+expand_x,image.shape[1])] 155 | elif format == "PIL": 156 | bottom = min(joint_max_y+expand_y, image.height) 157 | right = min(joint_max_x+expand_x,image.width) 158 | top = max(0,joint_min_y-expand_y) 159 | left = max(0,joint_min_x-expand_x) 160 | return tF.crop(image, top, left, bottom-top ,right-left) 161 | 162 | 163 | def get_face(self, image, joints, _modality, format="cv2"): 164 | 165 | joints = joints.reshape((18,3)) 166 | #joints[joints[:,2]<0.1] = np.nan 167 | #joints[np.isnan(joints[:,2])] = np.nan 168 | 169 | head_indices = [0,1,14,15,16,17] 170 | 171 | joints = joints[head_indices] 172 | 173 | if not np.isnan(joints).all(): 174 | 175 | joint_min_x = int(round(np.nanmin(joints[:,0]))) 176 | joint_min_y = int(round(np.nanmin(joints[:,1]))) 177 | 178 | joint_max_x = int(round(np.nanmax(joints[:,0]))) 179 | joint_max_y = int(round(np.nanmax(joints[:,1]))) 180 | 181 | expand_x = int(round(30/100 * (joint_max_x-joint_min_x))) 182 | expand_y = int(round(30/100 * (joint_max_y-joint_min_y))) 183 | 184 | if format == "cv2": 185 | return image[max(0,joint_min_y-expand_y):min(joint_max_y+expand_y, image.shape[0]), max(0,joint_min_x-expand_x):min(joint_max_x+expand_x,image.shape[1])] 186 | elif format == "PIL": 187 | bottom = min(joint_max_y+expand_y, image.height) 188 | right = min(joint_max_x+expand_x,image.width) 189 | top = max(0,joint_min_y-expand_y) 190 | left = max(0,joint_min_x-expand_x) 191 | return tF.crop(image, top, left, bottom-top ,right-left) 192 | else: 193 | if _modality == 'RGB': 194 | return Image.new('RGB', (300, 300)) 195 | else: 196 | return Image.new('L', (300, 300)) 197 | 198 | 199 | def joints(self, index): 200 | 201 | sample = self.df.iloc[index] 202 | joints_path = os.path.join(self.bold_path, "joints", sample["joints_path"]) 203 | joints18 = np.load(joints_path) 204 | joints18[:,0] -= joints18[0,0] 205 | return joints18 206 | 207 | 208 | def _load_image(self, directory, idx, index, modality, mode): 209 | 210 | joints = self.joints(index) 211 | poi_joints = joints[joints[:, 0] + 1 == idx] 212 | sample = self.df.iloc[index] 213 | poi_joints = poi_joints[(poi_joints[:, 1] == sample["person_id"]), 2:] 214 | 215 | if modality == 'RGB': 216 | 217 | frame = Image.open(os.path.join(directory, self.rgb_tmpl.format(idx))).convert("RGB") 218 | 219 | if mode == "context": 220 | if poi_joints.size == 0: 221 | return [frame] 222 | context = self.get_context(frame, poi_joints, format="PIL") 223 | return [context] 224 | 225 | if poi_joints.size == 0: 226 | body = frame 227 | face = Image.new('RGB', (300, 300)) 228 | pass #do whole frame, black face image 229 | else: 230 | body = self.get_bounding_box(frame, poi_joints, format="PIL") 231 | face = self.get_face(frame, poi_joints, _modality='RGB', format="PIL") 232 | if body.size == 0: 233 | print(poi_joints) 234 | body = frame 235 | face = Image.new('RGB', (300, 300)) 236 | return [body], [face] 237 | 238 | elif modality == 'Flow': 239 | 240 | frame_x = Image.open(os.path.join(directory, self.flow_tmpl.format('flow_x', idx))).convert('L') 241 | frame_y = Image.open(os.path.join(directory, self.flow_tmpl.format('flow_y', idx))).convert('L') 242 | 243 | if mode == "context": 244 | if poi_joints.size == 0: 245 | return [frame_x, frame_y] 246 | context_x = self.get_context(frame_x, poi_joints, format="PIL") 247 | context_y = self.get_context(frame_y, poi_joints, format="PIL") 248 | return [context_x, context_y] 249 | 250 | if poi_joints.size == 0: 251 | body_x = frame_x 252 | body_y = frame_y 253 | face_x = Image.new('L', (300, 300)) 254 | face_y = Image.new('L', (300, 300)) 255 | pass # do whole frame 256 | else: 257 | body_x = self.get_bounding_box(frame_x, poi_joints, format="PIL") 258 | body_y = self.get_bounding_box(frame_y, poi_joints, format="PIL") 259 | face_x = self.get_face(frame_x, poi_joints, _modality="Flow", format="PIL") 260 | face_y = self.get_face(frame_y, poi_joints, _modality="Flow", format="PIL") 261 | if body_x.size == 0: 262 | body_x = frame_x 263 | body_y = frame_y 264 | face_x = Image.new('L', (300, 300)) 265 | face_y = Image.new('L', (300, 300)) 266 | return [body_x, body_y], [face_x, face_y] 267 | 268 | elif modality == 'Depth': 269 | 270 | # Change it accordingly 271 | directory_depth = directory.replace('test_raw','depth') 272 | 273 | frame = Image.open(os.path.join(directory, self.rgb_tmpl.format(idx))).convert("RGB") 274 | 275 | depth_map = Image.open(os.path.join(directory_depth, self.rgb_tmpl.format(idx))).convert("L") 276 | 277 | return [frame], [depth_map] 278 | 279 | elif modality == 'RGBDiff': 280 | 281 | frame = Image.open(os.path.join(directory, self.rgb_tmpl.format(idx))).convert("RGB") 282 | 283 | return [frame] 284 | 285 | 286 | def _load_diffimage(self, frame, idx, index, mode): 287 | 288 | joints = self.joints(index) 289 | poi_joints = joints[joints[:, 0] + 1 == idx] 290 | sample = self.df.iloc[index] 291 | poi_joints = poi_joints[(poi_joints[:, 1] == sample["person_id"]), 2:] 292 | 293 | if mode == "context": 294 | if poi_joints.size == 0: 295 | return [frame] 296 | context = self.get_context(frame, poi_joints, format="PIL") 297 | return [context] 298 | 299 | if poi_joints.size == 0: 300 | body = frame 301 | face = Image.new('RGB', (300, 300)) 302 | pass # do whole frame, black face image 303 | else: 304 | body = self.get_bounding_box(frame, poi_joints, format="PIL") 305 | face = self.get_face(frame, poi_joints, _modality='RGB', format="PIL") 306 | if body.size == 0: 307 | print(poi_joints) 308 | body = frame 309 | face = Image.new('RGB', (300, 300)) 310 | return [body], [face] 311 | 312 | 313 | def _sample_indices(self, record): 314 | 315 | """ 316 | :param record: VideoRecord 317 | :return: list 318 | """ 319 | 320 | average_duration = (record.num_frames - self.data_length + 1) // self.num_segments 321 | if average_duration > 0: 322 | offsets = np.multiply(list(range(self.num_segments)), average_duration) + randint(average_duration-1, size=self.num_segments) 323 | elif record.num_frames > self.num_segments: 324 | offsets = np.sort(randint(record.num_frames - self.data_length + 1, size=self.num_segments)) 325 | else: 326 | offsets = np.zeros((self.num_segments,)) 327 | return offsets + 3 328 | 329 | 330 | def _get_val_indices(self, record): 331 | 332 | if record.num_frames > self.num_segments + self.data_length - 1: 333 | tick = (record.num_frames - self.data_length + 1) / float(self.num_segments) 334 | offsets = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segments)]) 335 | else: 336 | offsets = np.zeros((self.num_segments,)) 337 | return offsets + 3 338 | 339 | 340 | def _get_test_indices(self, record): 341 | 342 | tick = (record.num_frames - self.data_length + 1) / float(self.num_segments) 343 | offsets = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segments)]) 344 | return offsets + 3 345 | 346 | 347 | def __getitem__(self, index): 348 | 349 | sample = self.df.iloc[index] 350 | 351 | fname = os.path.join(self.bold_path,"videos",self.df.iloc[index]["video"]) 352 | 353 | capture = cv2.VideoCapture(fname) 354 | 355 | frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))-1 356 | 357 | capture.release() 358 | 359 | record_path = os.path.join(self.bold_path,"test_raw",sample["video"][4:-4]) 360 | 361 | record = VideoRecord([record_path, frame_count, sample["min_frame"], sample["max_frame"]]) 362 | 363 | if not self.test_mode: 364 | segment_indices = self._sample_indices(record) if self.random_shift else self._get_val_indices(record) 365 | else: 366 | segment_indices = self._get_test_indices(record) 367 | 368 | return self.get(record, segment_indices, index) 369 | 370 | 371 | def get(self, record, indices, index): 372 | 373 | rgb_body = list() 374 | rgb_context = list() 375 | rgb_face = list() 376 | 377 | flow_body = list() 378 | flow_context = list() 379 | flow_face = list() 380 | 381 | frame = list() 382 | #depth = list() 383 | 384 | rgbdiff = list() 385 | rgbdiff_body = list() 386 | rgbdiff_context = list() 387 | rgbdiff_face = list() 388 | 389 | #print(indices) 390 | 391 | """ Get RGB """ 392 | if self.inp_type=="RGB": 393 | for seg_ind in indices: 394 | p = int(seg_ind) 395 | for i in range(1): 396 | seg_body, seg_face = self._load_image(record.path, p, index, modality = "RGB", mode = "body") 397 | rgb_body.extend(seg_body) 398 | rgb_face.extend(seg_face) 399 | if self.context: 400 | seg_context = self._load_image(record.path, p, index, modality = "RGB", mode = "context") 401 | rgb_context.extend(seg_context) 402 | if p < record.num_frames: 403 | p += 1 404 | 405 | """ Get Optical Flow """ 406 | if self.inp_type=="Flow": 407 | for seg_ind in indices: 408 | p = int(seg_ind)-2 409 | for i in range(5): 410 | seg_body, seg_face = self._load_image(record.path, p, index, modality = "Flow", mode = "body") 411 | flow_body.extend(seg_body) 412 | flow_face.extend(seg_face) 413 | if self.context: 414 | seg_context = self._load_image(record.path, p, index, modality = "Flow", mode = "context") 415 | flow_context.extend(seg_context) 416 | if p < record.num_frames: 417 | p += 1 418 | 419 | #""" Get Depth """ 420 | #if self.inp_type=="Depth": 421 | # for seg_ind in indices: 422 | # p = int(seg_ind)-2 423 | # for i in range(self.data_length): 424 | # seg_frame, seg_depth = self._load_image(record.path, p, index, modality = "Depth", mode = None) 425 | # frame.extend(seg_frame) 426 | # depth.extend(seg_depth) 427 | # if p < record.num_frames: 428 | # p += 1 429 | 430 | """ Get RGBDiff""" 431 | if self.inp_type=="RGBDiff": 432 | for seg_ind in indices: 433 | p = int(seg_ind)-2 434 | for i in range(6): 435 | seg_frame = self._load_image(record.path, p, index, modality = "RGBDiff", mode = None) 436 | frame.extend(seg_frame) 437 | if p < record.num_frames: 438 | p += 1 439 | 440 | for j in range(1,self.data_length): 441 | diff = (np.array(frame[j])-np.array(frame[j-1])) 442 | diff = (diff.astype('float64')-np.min(diff))/(np.max(diff)-np.min(diff)) 443 | diff = 255*diff 444 | diff = diff.astype('uint8') 445 | rgbdiff.append(diff) 446 | 447 | for seg_ind in indices: 448 | p = int(seg_ind)-2 449 | for i in range(5): 450 | diff_body, diff_face = self._load_diffimage(Image.fromarray(rgbdiff[i]), p, index, mode = 'body') 451 | rgbdiff_body.extend(diff_body) 452 | rgbdiff_face.extend(diff_face) 453 | if self.context: 454 | diff_context = self._load_diffimage(Image.fromarray(rgbdiff[i]), p, index, mode = 'context') 455 | rgbdiff_context.extend(diff_context) 456 | if p < record.num_frames: 457 | p += 1 458 | 459 | if not self.test_mode: 460 | categorical = self.df.iloc[index][self.categorical_emotions] 461 | continuous = self.df.iloc[index][self.continuous_emotions] 462 | continuous = continuous/10.0 # normalize to 0 - 1 463 | 464 | if self.inp_type=="RGB": 465 | if self.rgb_transform is None: 466 | process_rgb_body = rgb_body 467 | if self.context: 468 | process_rgb_context = rgb_context 469 | process_rgb_face = rgb_face 470 | else: 471 | process_rgb_body = self.rgb_transform(rgb_body) 472 | if self.context: 473 | process_rgb_context = self.rgb_transform(rgb_context) 474 | process_rgb_face = self.rgb_transform(rgb_face) 475 | if self.inp_type=="Flow": 476 | if self.flow_transform is None: 477 | process_flow_body = flow_body 478 | if self.context: 479 | process_flow_context = flow_context 480 | process_flow_face = flow_face 481 | else: 482 | process_flow_body = self.flow_transform(flow_body) 483 | if self.context: 484 | process_flow_context = self.flow_transform(flow_context) 485 | process_flow_face = self.flow_transform(flow_face) 486 | if self.inp_type=="RGBDiff": 487 | if self.diff_transform is None: 488 | process_rgbdiff_body = rgbdiff_body 489 | if self.context: 490 | process_rgbdiff_context = rgbdiff_context 491 | process_rgbdiff_face = rgbdiff_face 492 | else: 493 | process_rgbdiff_body = self.diff_transform(rgbdiff_body) 494 | if self.context: 495 | process_rgbdiff_context = self.diff_transform(rgbdiff_context) 496 | process_rgbdiff_face = self.diff_transform(rgbdiff_face) 497 | 498 | if self.inp_type=="Flow": 499 | if self.context: 500 | return process_flow_body, process_flow_face, torch.tensor(self.embeddings).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float(), self.df.iloc[index]["video"], process_flow_context 501 | else: 502 | return process_flow_body, process_flow_face, torch.tensor(self.embeddings).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float(), self.df.iloc[index]["video"] 503 | if self.inp_type=="RGB": 504 | if self.context: 505 | return process_rgb_body, process_rgb_face, torch.tensor(self.embeddings).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float(), self.df.iloc[index]["video"], process_rgb_context 506 | else: 507 | return process_rgb_body, process_rgb_face, torch.tensor(self.embeddings).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float(), self.df.iloc[index]["video"] 508 | if self.inp_type=="RGBDiff": 509 | if self.context: 510 | return process_rgbdiff_body, process_rgbdiff_face, torch.tensor(self.embeddings).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float(), self.df.iloc[index]["video"], process_rgbdiff_context 511 | else: 512 | return process_rgbdiff_body, process_rgbdiff_face, torch.tensor(self.embeddings).float(), torch.tensor(categorical).float(), torch.tensor(continuous).float(), self.df.iloc[index]["video"] 513 | 514 | # --> Testing (TODO) 515 | else: 516 | if self.inp_type=="RGB": 517 | if self.rgb_transform is None: 518 | process_rgb_body = rgb_body 519 | if self.context: 520 | process_rgb_context = rgb_context 521 | process_rgb_face = rgb_face 522 | else: 523 | process_rgb_body = self.rgb_transform(rgb_body) 524 | if self.context: 525 | process_rgb_context = self.rgb_transform(rgb_context) 526 | process_rgb_face = self.rgb_transform(rgb_face) 527 | if self.inp_type=="Flow": 528 | if self.flow_transform is None: 529 | process_flow_body = flow_body 530 | if self.context: 531 | process_flow_context = flow_context 532 | process_flow_face = flow_face 533 | else: 534 | process_flow_body = self.flow_transform(flow_body) 535 | if self.context: 536 | process_flow_context = self.flow_transform(flow_context) 537 | process_flow_face = self.flow_transform(flow_face) 538 | if self.inp_type=="RGBDiff": 539 | if self.diff_transform is None: 540 | process_rgbdiff_body = rgbdiff_body 541 | if self.context: 542 | process_rgbdiff_context = rgbdiff_context 543 | process_rgbdiff_face = rgbdiff_face 544 | else: 545 | process_rgbdiff_body = self.diff_transform(rgbdiff_body) 546 | if self.context: 547 | process_rgbdiff_context = self.diff_transform(rgbdiff_context) 548 | process_rgbdiff_face = self.diff_transform(rgbdiff_face) 549 | 550 | if self.inp_type=="Flow": 551 | if self.context: 552 | return process_flow_body, process_flow_face, torch.tensor(self.embeddings).float(), self.df.iloc[index]["video"], process_flow_context 553 | else: 554 | return process_flow_body, process_flow_face, torch.tensor(self.embeddings).float(), self.df.iloc[index]["video"] 555 | if self.inp_type=="RGB": 556 | if self.context: 557 | return process_rgb_body, process_rgb_face, torch.tensor(self.embeddings).float(), self.df.iloc[index]["video"], process_rgb_context 558 | else: 559 | return process_rgb_body, process_rgb_face, torch.tensor(self.embeddings).float(), self.df.iloc[index]["video"] 560 | if self.inp_type=="RGBDiff": 561 | if self.context: 562 | return process_rgbdiff_body, process_rgbdiff_face, torch.tensor(self.embeddings).float(), self.df.iloc[index]["video"], process_rgbdiff_context 563 | else: 564 | return process_rgbdiff_body, process_rgbdiff_face, torch.tensor(self.embeddings).float(), self.df.iloc[index]["video"] 565 | 566 | 567 | def __len__(self): 568 | return len(self.df) 569 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------