def main(args): print('==> Using settings {}'.format(args)) # print('==> Loading dataset...') # dataset_path = path.join('data', 'data_3d_' + args.dataset + '.npz') # if args.dataset == 'h36m': # from common.h36m_dataset import Human36mDataset, TRAIN_SUBJECTS, TEST_SUBJECTS # dataset = Human36mDataset(dataset_path) # subjects_train = TRAIN_SUBJECTS # subjects_test = TEST_SUBJECTS # else: # raise KeyError('Invalid dataset') # print('==> Preparing data...') # dataset = read_3d_data(dataset) # # print('==> Loading 2D detections...') # keypoints = create_2d_data(path.join('data', 'data_2d_' + args.dataset + '_' + args.keypoints + '.npz'), dataset) # # action_filter = None if args.actions == '*' else args.actions.split(',') # if action_filter is not None: # action_filter = map(lambda x: dataset.define_actions(x)[0], action_filter) # print('==> Selected actions: {}'.format(action_filter)) # stride = args.downsample cudnn.benchmark = True device = torch.device("cuda") # Create model print("==> Creating model...") p_dropout = (None if args.dropout == 0.0 else args.dropout) # adj = adj_mx_from_skeleton(dataset.skeleton()) adj = adj_mx_from_skeleton() print(adj) # model_pos = SemGCN(adj, args.hid_dim, num_layers=args.num_layers, p_dropout=p_dropout, # nodes_group=dataset.skeleton().joints_group() if args.non_local else None).to(device) model_pos = SemGCN(adj, args.hid_dim, num_layers=args.num_layers, p_dropout=p_dropout, nodes_group=None).to(device) print("==> Total parameters: {:.2f}M".format( sum(p.numel() for p in model_pos.parameters()) / 1000000.0)) criterion = nn.MSELoss(reduction='mean').to(device) optimizer = torch.optim.Adam(model_pos.parameters(), lr=args.lr) # Optionally resume from a checkpoint if args.resume or args.evaluate: ckpt_path = (args.resume if args.resume else args.evaluate) if path.isfile(ckpt_path): print("==> Loading checkpoint '{}'".format(ckpt_path)) ckpt = torch.load(ckpt_path) start_epoch = ckpt['epoch'] error_best = ckpt['error'] glob_step = ckpt['step'] lr_now = ckpt['lr'] model_pos.load_state_dict(ckpt['state_dict']) optimizer.load_state_dict(ckpt['optimizer']) print("==> Loaded checkpoint (Epoch: {} | Error: {})".format( start_epoch, error_best)) if args.resume: ckpt_dir_path = path.dirname(ckpt_path) logger = Logger(path.join(ckpt_dir_path, 'log.txt'), resume=True) else: raise RuntimeError( "==> No checkpoint found at '{}'".format(ckpt_path)) else: start_epoch = 0 error_best = None glob_step = 0 lr_now = args.lr ckpt_dir_path = args.checkpoint + '/' + 'test1' if not path.exists(ckpt_dir_path): os.makedirs(ckpt_dir_path) print('==> Making checkpoint dir: {}'.format(ckpt_dir_path)) logger = Logger(os.path.join(ckpt_dir_path, 'log.txt')) logger.set_names( ['epoch', 'lr', 'loss_train', 'error_eval_p1', 'error_eval_p2']) if args.evaluate: print('==> Evaluating...') # if action_filter is None: # action_filter = dataset.define_actions() # # errors_p1 = np.zeros(len(action_filter)) # errors_p2 = np.zeros(len(action_filter)) # for i, action in enumerate(action_filter): # poses_valid, poses_valid_2d, actions_valid = fetch(subjects_test, dataset, keypoints, [action], stride) # valid_loader = DataLoader(PoseGenerator(poses_valid, poses_valid_2d, actions_valid), # batch_size=args.batch_size, shuffle=False, # num_workers=args.num_workers, pin_memory=True) # poses_valid, poses_valid_2d, actions_valid = fetch(subjects_test, dataset, keypoints, [action], stride) valid_loader = DataLoader(PoseGenerator(opt='val'), batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) errors_p1, errors_p2 = evaluate(valid_loader, model_pos, device) print('Protocol #1 (MPJPE) action-wise average: {:.2f} (mm)'.format( np.mean(errors_p1))) print('Protocol #2 (P-MPJPE) action-wise average: {:.2f} (mm)'.format( np.mean(errors_p2))) # print('Protocol #1 (MPJPE) action-wise average: {:.2f} (mm)'.format(np.mean(errors_p1).item())) # print('Protocol #2 (P-MPJPE) action-wise average: {:.2f} (mm)'.format(np.mean(errors_p2).item())) exit(0) # poses_train, poses_train_2d, actions_train = fetch(subjects_train, dataset, keypoints, action_filter, stride) # print('2d data shape: ', len(poses_train_2d)) # print('3d data shape: ', len(poses_train)) # print('action data shape: ', len(actions_train)) # train_loader = DataLoader(PoseGenerator(poses_train, poses_train_2d, actions_train), batch_size=args.batch_size, # shuffle=True, num_workers=args.num_workers, pin_memory=True) train_loader = DataLoader(PoseGenerator(opt='train'), batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=True) # poses_valid, poses_valid_2d, actions_valid = fetch(subjects_test, dataset, keypoints, action_filter, stride) # valid_loader = DataLoader(PoseGenerator(poses_valid, poses_valid_2d, actions_valid), batch_size=args.batch_size, # shuffle=False, num_workers=args.num_workers, pin_memory=True) valid_loader = DataLoader(PoseGenerator(opt='val'), batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) for epoch in range(start_epoch, args.epochs): print('\nEpoch: %d | LR: %.8f' % (epoch + 1, lr_now)) # Train for one epoch epoch_loss, lr_now, glob_step = train(train_loader, model_pos, criterion, optimizer, device, args.lr, lr_now, glob_step, args.lr_decay, args.lr_gamma, max_norm=args.max_norm) # Evaluate error_eval_p1, error_eval_p2 = evaluate(valid_loader, model_pos, device) # Update log file logger.append( [epoch + 1, lr_now, epoch_loss, error_eval_p1, error_eval_p2]) # Save checkpoint if error_best is None or error_best > error_eval_p1: error_best = error_eval_p1 save_ckpt( { 'epoch': epoch + 1, 'lr': lr_now, 'step': glob_step, 'state_dict': model_pos.state_dict(), 'optimizer': optimizer.state_dict(), 'error': error_eval_p1 }, ckpt_dir_path, suffix='best') if (epoch + 1) % args.snapshot == 0: save_ckpt( { 'epoch': epoch + 1, 'lr': lr_now, 'step': glob_step, 'state_dict': model_pos.state_dict(), 'optimizer': optimizer.state_dict(), 'error': error_eval_p1 }, ckpt_dir_path) logger.close() logger.plot(['loss_train', 'error_eval_p1']) savefig(path.join(ckpt_dir_path, 'log.eps')) return
def main(args): print('==> Using settings {}'.format(args)) convm = torch.zeros(3, 17, 17, dtype=torch.float) print('==> Loading dataset...') dataset_path = path.join('data', 'data_3d_' + args.dataset + '.npz') if args.dataset == 'h36m': from common.h36m_dataset import Human36mDataset dataset = Human36mDataset(dataset_path) else: raise KeyError('Invalid dataset') print('==> Preparing data...') dataset = read_3d_data(dataset) print('==> Loading 2D detections...') keypoints = create_2d_data( path.join('data', 'data_2d_' + args.dataset + '_' + args.keypoints + '.npz'), dataset) cudnn.benchmark = True device = torch.device("cuda") # Create model print("==> Creating model...") if args.architecture == 'linear': from models.linear_model import LinearModel, init_weights num_joints = dataset.skeleton().num_joints() model_pos = LinearModel(num_joints * 2, (num_joints - 1) * 3).to(device) model_pos.apply(init_weights) elif args.architecture == 'gcn': from models.sem_gcn import SemGCN from common.graph_utils import adj_mx_from_skeleton p_dropout = (None if args.dropout == 0.0 else args.dropout) adj = adj_mx_from_skeleton(dataset.skeleton()) model_pos = SemGCN(convm, adj, args.hid_dim, num_layers=args.num_layers, p_dropout=p_dropout, nodes_group=dataset.skeleton().joints_group() if args.non_local else None).to(device) else: raise KeyError('Invalid model architecture') print("==> Total parameters: {:.2f}M".format( sum(p.numel() for p in model_pos.parameters()) / 1000000.0)) # Resume from a checkpoint ckpt_path = args.evaluate if path.isfile(ckpt_path): print("==> Loading checkpoint '{}'".format(ckpt_path)) ckpt = torch.load(ckpt_path) start_epoch = ckpt['epoch'] error_best = ckpt['error'] model_pos.load_state_dict(ckpt['state_dict']) print("==> Loaded checkpoint (Epoch: {} | Error: {})".format( start_epoch, error_best)) else: raise RuntimeError("==> No checkpoint found at '{}'".format(ckpt_path)) print('==> Rendering...') poses_2d = keypoints[args.viz_subject][args.viz_action] out_poses_2d = poses_2d[args.viz_camera] out_actions = [args.viz_camera] * out_poses_2d.shape[0] poses_3d = dataset[args.viz_subject][args.viz_action]['positions_3d'] assert len(poses_3d) == len(poses_2d), 'Camera count mismatch' out_poses_3d = poses_3d[args.viz_camera] ground_truth = dataset[args.viz_subject][args.viz_action]['positions_3d'][ args.viz_camera].copy() input_keypoints = out_poses_2d.copy() render_loader = DataLoader(PoseGenerator([out_poses_3d], [out_poses_2d], [out_actions]), batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) prediction = evaluate(render_loader, model_pos, device, args.architecture)[0] # Invert camera transformation cam = dataset.cameras()[args.viz_subject][args.viz_camera] prediction = camera_to_world(prediction, R=cam['orientation'], t=0) prediction[:, :, 2] -= np.min(prediction[:, :, 2]) ground_truth = camera_to_world(ground_truth, R=cam['orientation'], t=0) ground_truth[:, :, 2] -= np.min(ground_truth[:, :, 2]) anim_output = {'Regression': prediction, 'Ground truth': ground_truth} input_keypoints = image_coordinates(input_keypoints[..., :2], w=cam['res_w'], h=cam['res_h']) render_animation(input_keypoints, anim_output, dataset.skeleton(), dataset.fps(), args.viz_bitrate, cam['azimuth'], args.viz_output, limit=args.viz_limit, downsample=args.viz_downsample, size=args.viz_size, input_video_path=args.viz_video, viewport=(cam['res_w'], cam['res_h']), input_video_skip=args.viz_skip)
def __init__(self, args, device, skeleton): print("Initialize SemGCMDriver - begin.") from models.sem_gcn import SemGCN from common.graph_utils import adj_mx_from_skeleton self.hid_dim = args.sem_hid_dim self.num_layers = args.sem_num_layers self.p_dropout = (None if args.sem_dropout == 0.0 else args.sem_dropout) self.render_score_threshold = args.render_score_threshold self.skeleton = skeleton adj = adj_mx_from_skeleton(self.skeleton) self.device = device self.model_pos = SemGCN(adj, self.hid_dim, num_layers=self.num_layers, p_dropout=self.p_dropout, nodes_group=self.skeleton.joints_group()).to( self.device.device) self.last_2d_positions = None self.last_3d_positions = None self.last_scores = None self.render_3d = args.sem_show_3d self._plot = args.sem_plot self._plot_initalized = False self._plot_skeleton = None self.last_3d_skeletons = None # Resume from a checkpoint ckpt_path = args.sem_evaluate if path.isfile(ckpt_path): print("==> Loading checkpoint '{}'".format(ckpt_path)) self.ckpt = torch.load(ckpt_path) self.rename_nonlocal_node(self.ckpt) start_epoch = self.ckpt['epoch'] error_best = self.ckpt['error'] self.model_pos.load_state_dict(self.ckpt['state_dict']) print("==> Loaded checkpoint (Epoch: {} | Error: {})".format( start_epoch, error_best)) else: raise RuntimeError( "==> No checkpoint found at '{}'".format(ckpt_path)) if self._plot: size = 5 radius = 1 azim = 45 title = "test" plt.ion() fig = plt.figure(figsize=(size, size)) self._plot_ax = fig.add_subplot(1, 1, 1, projection='3d') self._plot_ax.view_init(elev=15., azim=azim) self._plot_ax.set_xlim3d([-radius / 2, radius / 2]) self._plot_ax.set_zlim3d([0, radius]) self._plot_ax.set_ylim3d([-radius / 2, radius / 2]) self._plot_ax.set_aspect('auto') self._plot_ax.set_xticklabels([]) self._plot_ax.set_yticklabels([]) self._plot_ax.set_zticklabels([]) self._plot_ax.dist = 7.5 self._plot_ax.set_title(title) # , pad=35 print("Initialize SemGCMDriver - end.")
def main(): dataset_path = "./data/data_3d_h36m.npz" # 加载数据 from common.h36m_dataset import Human36mDataset dataset = Human36mDataset(dataset_path) dataset = read_3d_data(dataset) cudnn.benchmark = True device = torch.device("cpu") from models.sem_gcn import SemGCN from common.graph_utils import adj_mx_from_skeleton p_dropout = None adj = adj_mx_from_skeleton(dataset.skeleton()) model_pos = SemGCN(adj, 128, num_layers=4, p_dropout=p_dropout, nodes_group=dataset.skeleton().joints_group()).to(device) ckpt_path = "./checkpoint/pretrained/ckpt_semgcn_nonlocal_sh.pth.tar" ckpt = torch.load(ckpt_path, map_location='cpu') model_pos.load_state_dict(ckpt['state_dict'], False) model_pos.eval() # ============ 新增代码 ============== # 从项目处理2d数据的代码中输出的一个人体数据 inputs_2d = [[483.0, 450], [503, 450], [503, 539], [496, 622], [469, 450], [462, 546], [469, 622], [483, 347], [483, 326], [489, 264], [448, 347], [448, 408], [441, 463], [517, 347], [524, 408], [538, 463]] # # openpose的测试样例识别结果 # inputs_2d = [[86.0, 137], [99, 128], [94, 127], [97, 110], [89, 105], [102, 129], [116, 116], [99, 110], # [105, 93], [117, 69], [147, 63], [104, 93], [89, 69], [82, 38], [89, 139], [94, 140]] inputs_2d = np.array(inputs_2d) # inputs_2d[:, 1] = np.max(inputs_2d[:, 1]) - inputs_2d[:, 1] # 变成正的人体姿态,原始数据为倒立的 cam = dataset.cameras()['S1'][0] # 获取相机参数 inputs_2d[..., :2] = normalize_screen_coordinates(inputs_2d[..., :2], w=cam['res_w'], h=cam['res_h']) # 2d坐标处理 # 画出归一化屏幕坐标并且标记序号的二维关键点图像 print(inputs_2d) # 打印归一化后2d关键点坐标 d_x = inputs_2d[:, 0] d_y = inputs_2d[:, 1] plt.figure() plt.scatter(d_x, d_y) for i, txt in enumerate(np.arange(inputs_2d.shape[0])): plt.annotate(txt, (d_x[i], d_y[i])) # 标号 # plt.show() # 显示2d关键点归一化后的图像 # 获取3d结果 inputs_2d = torch.tensor(inputs_2d, dtype=torch.float32) # 转换为张量 outputs_3d = model_pos(inputs_2d).cpu() # 加载模型 outputs_3d[:, :, :] -= outputs_3d[:, :1, :] # Remove global offset / 移除全球偏移 predictions = [outputs_3d.detach().numpy()] # 预测结果 prediction = np.concatenate(predictions)[0] # 累加取第一个 # Invert camera transformation / 反相机的转换 prediction = camera_to_world(prediction, R=cam['orientation'], t=0) # R和t的参数设置影响不大,有多种写法和选取的相机参数有关,有些S没有t等等问题 prediction[:, 2] -= np.min(prediction[:, 2]) # 向上偏移min(prediction[:, 2]),作用是把坐标变为正数 print('prediction') print(prediction) # 打印画图的3d坐标 plt.figure() ax = plt.subplot(111, projection='3d') # 创建一个三维的绘图工程 o_x = prediction[:, 0] o_y = prediction[:, 1] o_z = prediction[:, 2] print(o_x) print(o_y) print(o_z) ax.scatter(o_x, o_y, o_z) temp = o_x x = [temp[9], temp[8], temp[7], temp[10], temp[11], temp[12]] temp = o_y y = [temp[9], temp[8], temp[7], temp[10], temp[11], temp[12]] temp = o_z z = [temp[9], temp[8], temp[7], temp[10], temp[11], temp[12]] ax.plot(x, y, z) temp = o_x x = [temp[7], temp[0], temp[4], temp[5], temp[6]] temp = o_y y = [temp[7], temp[0], temp[4], temp[5], temp[6]] temp = o_z z = [temp[7], temp[0], temp[4], temp[5], temp[6]] ax.plot(x, y, z) temp = o_x x = [temp[0], temp[1], temp[2], temp[3]] temp = o_y y = [temp[0], temp[1], temp[2], temp[3]] temp = o_z z = [temp[0], temp[1], temp[2], temp[3]] ax.plot(x, y, z) temp = o_x x = [temp[7], temp[13], temp[14], temp[15]] temp = o_y y = [temp[7], temp[13], temp[14], temp[15]] temp = o_z z = [temp[7], temp[13], temp[14], temp[15]] ax.plot(x, y, z) # temp = o_x # x = [temp[0], temp[14]] # temp = o_y # y = [temp[0], temp[14]] # temp = o_z # z = [temp[0], temp[14]] # ax.plot(y, x, z) # # temp = o_x # x = [temp[0], temp[15]] # temp = o_y # y = [temp[0], temp[15]] # temp = o_z # z = [temp[0], temp[15]] # ax.plot(y, x, z) # 改变坐标比例的代码,该代码的效果是z坐标轴是其他坐标的两倍 from matplotlib.pyplot import MultipleLocatort major_locator = MultipleLocator(0.5) ax.xaxis.set_major_locator(major_locator) ax.yaxis.set_major_locator(major_locator) ax.zaxis.set_major_locator(major_locator) ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([0.5, 0.5, 1, 1])) plt.show()
class SemGCMDriver: def __init__(self, args, device, skeleton): print("Initialize SemGCMDriver - begin.") from models.sem_gcn import SemGCN from common.graph_utils import adj_mx_from_skeleton self.hid_dim = args.sem_hid_dim self.num_layers = args.sem_num_layers self.p_dropout = (None if args.sem_dropout == 0.0 else args.sem_dropout) self.render_score_threshold = args.render_score_threshold self.skeleton = skeleton adj = adj_mx_from_skeleton(self.skeleton) self.device = device self.model_pos = SemGCN(adj, self.hid_dim, num_layers=self.num_layers, p_dropout=self.p_dropout, nodes_group=self.skeleton.joints_group()).to( self.device.device) self.last_2d_positions = None self.last_3d_positions = None self.last_scores = None self.render_3d = args.sem_show_3d self._plot = args.sem_plot self._plot_initalized = False self._plot_skeleton = None self.last_3d_skeletons = None # Resume from a checkpoint ckpt_path = args.sem_evaluate if path.isfile(ckpt_path): print("==> Loading checkpoint '{}'".format(ckpt_path)) self.ckpt = torch.load(ckpt_path) self.rename_nonlocal_node(self.ckpt) start_epoch = self.ckpt['epoch'] error_best = self.ckpt['error'] self.model_pos.load_state_dict(self.ckpt['state_dict']) print("==> Loaded checkpoint (Epoch: {} | Error: {})".format( start_epoch, error_best)) else: raise RuntimeError( "==> No checkpoint found at '{}'".format(ckpt_path)) if self._plot: size = 5 radius = 1 azim = 45 title = "test" plt.ion() fig = plt.figure(figsize=(size, size)) self._plot_ax = fig.add_subplot(1, 1, 1, projection='3d') self._plot_ax.view_init(elev=15., azim=azim) self._plot_ax.set_xlim3d([-radius / 2, radius / 2]) self._plot_ax.set_zlim3d([0, radius]) self._plot_ax.set_ylim3d([-radius / 2, radius / 2]) self._plot_ax.set_aspect('auto') self._plot_ax.set_xticklabels([]) self._plot_ax.set_yticklabels([]) self._plot_ax.set_zticklabels([]) self._plot_ax.dist = 7.5 self._plot_ax.set_title(title) # , pad=35 print("Initialize SemGCMDriver - end.") def update(self, mmpose): self.last_2d_positions, self.last_scores = mmpose.getLastPoseResult() self.last_3d_positions = None if self.last_2d_positions is None: return self.last_3d_positions = [] for input2d in self.last_2d_positions: result = self.model_pos(input2d).cpu() self.last_3d_positions.append(result) self.last_3d_skeletons = [] for index, position in enumerate(self.last_3d_positions): skeleton = [] for node, parent in enumerate(self.skeleton._parents): if parent < 0: continue n = [ position[0][node][0], position[0][node][1], position[0][node][2] ] p = [ position[0][parent][0], position[0][parent][1], position[0][parent][2] ] line = [ n, p, [ self.last_scores[index][node], self.last_scores[index][parent] ] ] skeleton.append(line) self.last_3d_skeletons.append(skeleton) def render(self, img): img = self.__render_3d(img) return img def plotting(self): if not self._plot: return if not self.last_3d_skeletons: return if not self._plot_skeleton: for skeleton in self.last_3d_skeletons: self._plot_skeleton = [] for line in skeleton: clr = '#a0a0a0' if line[2][0] > self.render_score_threshold and line[2][ 1] > self.render_score_threshold: clr = 'black' self._plot_skeleton.append( self._plot_ax.plot([line[0][0], line[1][0]], [line[0][1], line[1][1]], [line[0][2], line[1][2]], zdir='z', color=clr)) break else: for si, skeleton in enumerate(self.last_3d_skeletons): for li, line in enumerate(skeleton): clr = '#a0a0a0' if line[2][0] > self.render_score_threshold and line[2][ 1] > self.render_score_threshold: clr = 'black' self._plot_skeleton[li][0].set_xdata( np.array([line[0][0], line[1][0]])) self._plot_skeleton[li][0].set_ydata( np.array([line[0][2], line[1][2]])) self._plot_skeleton[li][0].set_3d_properties( [line[0][1], line[1][1]], zdir='z') self._plot_skeleton[li][0].set_color(clr) break plt.draw() plt.pause(0.01) def __render_3d(self, img): if self.render_3d and self.last_3d_skeletons: for skeleton in self.last_3d_skeletons: for line in skeleton: color = (255, 0, 0) if line[2][0] > self.render_score_threshold and line[2][ 1] > self.render_score_threshold: color = (255, 255, 0) nx = line[0][0] * 100 + 100 ny = line[0][1] * 100 + 100 px = line[1][0] * 100 + 100 py = line[1][1] * 100 + 100 cv2.line(img, (nx, ny), (px, py), color, 1) break return img def rename_nonlocal_node(self, dic): if 'items' not in dir(dic): return targets = [] for key, value in dic.items(): if type(key) == str: if '.nonlocal.' in key: targets.append(key) self.rename_nonlocal_node(value) for key in targets: value = dic.pop(key) key = key.replace('.nonlocal.', '._nonlocal.') dic[key] = value def term(self): if self._plot: plt.ioff()