3d姿态 mhformer 预测代码

目录

预测并可视化代码

调整部分代码:

可视化推理:


mhformer 也是先进行人体检测,输出2d关键点,再估计3d关键点,

预测并可视化代码

需要注释掉plt.switch_backend('agg')

调整部分代码:

        output_dir_3D = output_dir +'pose3D/'os.makedirs(output_dir_3D, exist_ok=True)plt.show()# plt.savefig(output_dir_3D + str(('%04d'% i)) + '_3D.png', dpi=200, format='png', bbox_inches = 'tight')

可视化推理:

import sys
import argparse
import cv2
from demo.lib.preprocess import h36m_coco_format, revise_kpts
from demo.lib.hrnet.gen_kpts import gen_video_kpts as hrnet_pose
import os 
import numpy as np
import torch
import glob
from tqdm import tqdm
import copysys.path.append(os.getcwd())
from model.mhformer import Model
from common.camera import *import matplotlib
import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec# plt.switch_backend('agg')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42def show2Dpose(kps, img):connections = [[0, 1], [1, 2], [2, 3], [0, 4], [4, 5],[5, 6], [0, 7], [7, 8], [8, 9], [9, 10],[8, 11], [11, 12], [12, 13], [8, 14], [14, 15], [15, 16]]LR = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], dtype=bool)lcolor = (255, 0, 0)rcolor = (0, 0, 255)thickness = 3for j,c in enumerate(connections):start = map(int, kps[c[0]])end = map(int, kps[c[1]])start = list(start)end = list(end)cv2.line(img, (start[0], start[1]), (end[0], end[1]), lcolor if LR[j] else rcolor, thickness)cv2.circle(img, (start[0], start[1]), thickness=-1, color=(0, 255, 0), radius=3)cv2.circle(img, (end[0], end[1]), thickness=-1, color=(0, 255, 0), radius=3)return imgdef show3Dpose(vals, ax):ax.view_init(elev=15., azim=70)lcolor=(0,0,1)rcolor=(1,0,0)I = np.array( [0, 0, 1, 4, 2, 5, 0, 7,  8,  8, 14, 15, 11, 12, 8,  9])J = np.array( [1, 4, 2, 5, 3, 6, 7, 8, 14, 11, 15, 16, 12, 13, 9, 10])LR = np.array([0, 1, 0, 1, 0, 1, 0, 0, 0,   1,  0,  0,  1,  1, 0, 0], dtype=bool)for i in np.arange( len(I) ):x, y, z = [np.array( [vals[I[i], j], vals[J[i], j]] ) for j in range(3)]ax.plot(x, y, z, lw=2, color = lcolor if LR[i] else rcolor)RADIUS = 0.72RADIUS_Z = 0.7xroot, yroot, zroot = vals[0,0], vals[0,1], vals[0,2]ax.set_xlim3d([-RADIUS+xroot, RADIUS+xroot])ax.set_ylim3d([-RADIUS+yroot, RADIUS+yroot])ax.set_zlim3d([-RADIUS_Z+zroot, RADIUS_Z+zroot])ax.set_aspect('equal') # works fine in matplotlib==2.2.2 or 3.7.1white = (1.0, 1.0, 1.0, 0.0)ax.xaxis.set_pane_color(white) ax.yaxis.set_pane_color(white)ax.zaxis.set_pane_color(white)ax.tick_params('x', labelbottom = False)ax.tick_params('y', labelleft = False)ax.tick_params('z', labelleft = False)def get_pose2D(video_path, output_dir):cap = cv2.VideoCapture(video_path)width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)print('\nGenerating 2D pose...')with torch.no_grad():# the first frame of the video should be detected a personkeypoints, scores = hrnet_pose(video_path, det_dim=416, num_peroson=1, gen_output=True)keypoints, scores, valid_frames = h36m_coco_format(keypoints, scores)re_kpts = revise_kpts(keypoints, scores, valid_frames)print('Generating 2D pose successfully!')output_dir += 'input_2D/'os.makedirs(output_dir, exist_ok=True)output_npz = output_dir + 'keypoints.npz'np.savez_compressed(output_npz, reconstruction=keypoints)def img2video(video_path, output_dir):cap = cv2.VideoCapture(video_path)fps = int(cap.get(cv2.CAP_PROP_FPS)) + 5fourcc = cv2.VideoWriter_fourcc(*"mp4v")names = sorted(glob.glob(os.path.join(output_dir + 'pose/', '*.png')))img = cv2.imread(names[0])size = (img.shape[1], img.shape[0])videoWrite = cv2.VideoWriter(output_dir + video_name + '.mp4', fourcc, fps, size) for name in names:img = cv2.imread(name)videoWrite.write(img)videoWrite.release()def showimage(ax, img):ax.set_xticks([])ax.set_yticks([]) plt.axis('off')ax.imshow(img)def get_pose3D(video_path, output_dir):args, _ = argparse.ArgumentParser().parse_known_args()args.layers, args.channel, args.d_hid, args.frames = 3, 512, 1024, 351args.pad = (args.frames - 1) // 2args.previous_dir = 'checkpoint/pretrained/351'args.n_joints, args.out_joints = 17, 17## Reload model = Model(args).cuda()model_dict = model.state_dict()# Put the pretrained model of MHFormer in 'checkpoint/pretrained/351'model_path = sorted(glob.glob(os.path.join(args.previous_dir, '*.pth')))[0]pre_dict = torch.load(model_path)for name, key in model_dict.items():model_dict[name] = pre_dict[name]model.load_state_dict(model_dict)model.eval()## inputkeypoints = np.load(output_dir + 'input_2D/keypoints.npz', allow_pickle=True)['reconstruction']cap = cv2.VideoCapture(video_path)video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))## 3Dprint('\nGenerating 3D pose...')output_3d_all = []for i in tqdm(range(video_length)):ret, img = cap.read()img_size = img.shape## input framesstart = max(0, i - args.pad)end =  min(i + args.pad, len(keypoints[0])-1)input_2D_no = keypoints[0][start:end+1]left_pad, right_pad = 0, 0if input_2D_no.shape[0] != args.frames:if i < args.pad:left_pad = args.pad - iif i > len(keypoints[0]) - args.pad - 1:right_pad = i + args.pad - (len(keypoints[0]) - 1)input_2D_no = np.pad(input_2D_no, ((left_pad, right_pad), (0, 0), (0, 0)), 'edge')joints_left =  [4, 5, 6, 11, 12, 13]joints_right = [1, 2, 3, 14, 15, 16]input_2D = normalize_screen_coordinates(input_2D_no, w=img_size[1], h=img_size[0])  input_2D_aug = copy.deepcopy(input_2D)input_2D_aug[ :, :, 0] *= -1input_2D_aug[ :, joints_left + joints_right] = input_2D_aug[ :, joints_right + joints_left]input_2D = np.concatenate((np.expand_dims(input_2D, axis=0), np.expand_dims(input_2D_aug, axis=0)), 0)input_2D = input_2D[np.newaxis, :, :, :, :]input_2D = torch.from_numpy(input_2D.astype('float32')).cuda()N = input_2D.size(0)## estimationoutput_3D_non_flip = model(input_2D[:, 0])output_3D_flip     = model(input_2D[:, 1])output_3D_flip[:, :, :, 0] *= -1output_3D_flip[:, :, joints_left + joints_right, :] = output_3D_flip[:, :, joints_right + joints_left, :] output_3D = (output_3D_non_flip + output_3D_flip) / 2output_3D = output_3D[0:, args.pad].unsqueeze(1) output_3D[:, :, 0, :] = 0post_out = output_3D[0, 0].cpu().detach().numpy()output_3d_all.append(post_out)rot =  [0.1407056450843811, -0.1500701755285263, -0.755240797996521, 0.6223280429840088]rot = np.array(rot, dtype='float32')post_out = camera_to_world(post_out, R=rot, t=0)post_out[:, 2] -= np.min(post_out[:, 2])input_2D_no = input_2D_no[args.pad]## 2Dimage = show2Dpose(input_2D_no, copy.deepcopy(img))output_dir_2D = output_dir +'pose2D/'os.makedirs(output_dir_2D, exist_ok=True)cv2.imwrite(output_dir_2D + str(('%04d'% i)) + '_2D.png', image)## 3Dfig = plt.figure( figsize=(9.6, 5.4))gs = gridspec.GridSpec(1, 1)gs.update(wspace=-0.00, hspace=0.05) ax = plt.subplot(gs[0], projection='3d')show3Dpose( post_out, ax)output_dir_3D = output_dir +'pose3D/'os.makedirs(output_dir_3D, exist_ok=True)plt.show()# plt.savefig(output_dir_3D + str(('%04d'% i)) + '_3D.png', dpi=200, format='png', bbox_inches = 'tight')## save 3D keypointsoutput_3d_all = np.stack(output_3d_all, axis = 0)os.makedirs(output_dir + 'output_3D/', exist_ok=True)output_npz = output_dir + 'output_3D/' + 'output_keypoints_3d.npz'np.savez_compressed(output_npz, reconstruction=output_3d_all)print('Generating 3D pose successfully!')## allimage_dir = 'results/' image_2d_dir = sorted(glob.glob(os.path.join(output_dir_2D, '*.png')))image_3d_dir = sorted(glob.glob(os.path.join(output_dir_3D, '*.png')))print('\nGenerating demo...')for i in tqdm(range(len(image_2d_dir))):image_2d = plt.imread(image_2d_dir[i])image_3d = plt.imread(image_3d_dir[i])## cropedge = (image_2d.shape[1] - image_2d.shape[0]) // 2image_2d = image_2d[:, edge:image_2d.shape[1] - edge]edge = 102image_3d = image_3d[edge:image_3d.shape[0] - edge, edge:image_3d.shape[1] - edge]## showfont_size = 12fig = plt.figure(figsize=(9.6, 5.4))ax = plt.subplot(121)showimage(ax, image_2d)ax.set_title("Input", fontsize = font_size)ax = plt.subplot(122)showimage(ax, image_3d)ax.set_title("Reconstruction", fontsize = font_size)## saveoutput_dir_pose = output_dir +'pose/'os.makedirs(output_dir_pose, exist_ok=True)plt.show()# plt.savefig(output_dir_pose + str(('%04d'% i)) + '_pose.png', dpi=200, bbox_inches = 'tight')if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument('--video', type=str, default='CUSTOM_390-1.mp4', help='input video')# parser.add_argument('--video', type=str, default='sample_video.mp4', help='input video')parser.add_argument('--gpu', type=str, default='0', help='input video')args = parser.parse_args()os.environ["CUDA_VISIBLE_DEVICES"] = args.gpuvideo_path = './demo/video/' + args.videovideo_name = video_path.split('/')[-1].split('.')[0]output_dir = './demo/output/' + video_name + '/'get_pose2D(video_path, output_dir)get_pose3D(video_path, output_dir)img2video(video_path, output_dir)print('Generating demo successful!')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/627963.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

发现了一个比GPT-4还厉害的写论文解读的agent !

已经2024年了&#xff0c;该出现一个写论文解读AI Agent了。 大家肯定也在经常刷论文吧。 但真正尝试过用GPT去刷论文、写论文解读的小伙伴&#xff0c;一定深有体验——费劲。其他agents也没有能搞定的&#xff0c;今天我发现了一个超级厉害的写论文解读的agent &#xff0c…

进程上下文的概念和切换简单通俗的解释

进程上下文是进程执行活动全过程的静态描述。我们把已执行过的进程指令和数据在相关寄存器与堆栈中的内容称为进程上文&#xff0c;把正在执行的指令和数据在寄存器与堆栈中的内容称为进程正文&#xff0c;把待执行的指令和数据在寄存器与堆栈中的内容称为进程下文。 实际上li…

JavaScrip-运算符-知识点

运算符 运算符运算符分类算术运算符递增和递减运算符比较运算符逻辑运算符赋值运算符三元运算符逗号运算符运算符优先级 运算符 运算符分类 算术运算符递增和递减运算符比较运算符逻辑运算符赋值运算符三元运算符逗号运算符 算术运算符 概念&#xff1a;算术运算使用的符号…

运维体系中的那些Ops们

目录 前言 DevOps DevSecOps GitOps 1、缺少一致性 2、使用成本高 3、鉴权分散 4、审核审计困难 5、不可变基础设施扩展难 DataOps AIOps 总结 前言 提到运维&#xff0c;自然而然会联想到DevOps&#xff0c;大家应该还听说过DataOps、GitOps、DevSecOps、AIOps等…

K8s面试题——基础篇2

文章目录 一、简述 Kubernetes 如何保证集群的安全性二、简述 Kubernetes 准入机制三、简述 Kubernetes RBAC 及其特点&#xff08;优势&#xff09;四、简述 Kubernetes Secret 作用五、简述 Kubernetes Secret 有哪些使用方式六、简述 Kubernetes PodSecurityPolicy 机制七、…

rsync

rsync 文章目录 rsync1. rsync简介2. rsync特性3. rsync的ssh认证协议4. rsync命令5. rsyncinotify 1. rsync简介 rsync是linux系统下的数据镜像备份工具。使用快速增量备份工具Remote Sync可以远程同步&#xff0c;支持本地复制&#xff0c;或者与其他SSH、rsync主机同步。 …

Kafka 集群部署

目录 1、环境准备 2、搭建ZooKeeper集群 配置文件 节点标记 环境变量 启动集群 数据同步测试 故障测试 3、搭建 Kafka 集群 配置文件 环境变量 配置其他机器 启动服务 4、集群测试 创建 Topic 显示 Topic 配置 创建 Producer 创建consumer 删除Topic 查看Z…

代码随想录算法训练营第21天 | 530.二叉搜索树的最小绝对差 + 501.二叉搜索树中的众数 + 236.二叉树的最近公共祖先

今日任务 530.二叉搜索树的最小绝对差 - Easy 501.二叉搜索树中的众数 - Easy 236.二叉树的最近公共祖先 - Medium 530.二叉搜索树的最小绝对差 - Easy 题目链接&#xff1a;力扣-530. 二叉搜索树的最小绝对差 给你一个二叉搜索树的根节点 root &#xff0c;返回 树中任意两…

Postgres操作jsonb数据

Postgres操作jsonb数据 PostgreSQL 对 jsonb 类型的筛选查询可以使用 -> 或者 ->> 操作符。 -> 操作符用于通过 JSON 对象中的键来获取对应的值。 ->> 操作符可以将获取到的值转化为字符串类型。 1 查询 -- 数据准备 CREATE TABLE test (id SERIAL PRIMARY …

windows下的私钥权限管理

被问到Windows的私钥是否可以共享给多个用户&#xff0c;我们知道CNG创建的私钥&#xff0c;压根就没有提供跨用户和组的机制&#xff0c;因此无论对称还是非对称&#xff0c;CNG中的私钥没办法在用户间共享。 Windows支持的SACL中的访问客体&#xff0c;也不包括密钥。 但是…

Vulnhub靶机:driftingblues 6

一、介绍 运行环境&#xff1a;Virtualbox 攻击机&#xff1a;kali&#xff08;10.0.2.15&#xff09; 靶机&#xff1a;driftingblues6&#xff08;10.0.2.22&#xff09; 目标&#xff1a;获取靶机root权限和flag 靶机下载地址&#xff1a;https://www.vulnhub.com/entr…

服务拆分及远程调用

分布式架构都离不开服务的拆分&#xff0c;微服务也是一样。 1.微服务拆分 不同微服务&#xff0c;不要重复开发相同业务 微服务数据独立&#xff0c;不要访问其它微服务的数据库 微服务可以将自己的业务暴露为接口&#xff0c;供其它微服务调用 2.远程调用 以前时&#xf…

如何在Linux中使用~/.bashrc配置Java环境变量

为什么使用 ~/.bashrc 而不是 ~/.profile 原因 ~/.bashrc和~/.profile&#xff08;或在某些系统中是~/.bash_profile或~/.bash_login&#xff09;是用来配置用户的shell环境的两个不同的文件。它们的主要区别在于它们被加载的时机和适用的场合&#xff1a; ~/.bashrc主要用于…

1 python计算机基础

计算机基础和环境搭建 1 计算机基础和环境搭建1.计算机基础1.1 基本概念1.2 编程语言1.3 编译器/解释器 2.学习编程的本质3.Python的介绍3.1 语言的分类3.2 Python3.3 Python的解释器种类&#xff08;了解&#xff09;3.4 CPython解释器的版本 4.环境搭建4.1 安装Python解释器4…

关于C#中Monitor的wait/pulse的理解

wait&#xff1a;表示释放对象上的锁并阻止当前线程&#xff0c;直到它重新获取该锁。 pulse&#xff1a;表示通知等待队列中的线程锁定对象状态的更改。 当线程调用 Wait 时&#xff0c;它会释放对象上的锁并进入对象的等待队列。 对象的就绪队列中的下一个线程 (如果有一个…

Matlab交互式的局部放大图

在数据可视化中&#xff0c;很多时候需要对某一区间的数据进行局部放大&#xff0c;以获得对比度更高的可视化效果。下面利用 MATLAB 语言实现一个交互式的局部放大图绘制。 源码自行下载&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1yItVSinh6vU4ImlbZW6Deg?pwd9d…

《2023年度程序员收入报告》 :旧金山位居第一,北京程序员中位数超60万元

2024年刚刚拉开序幕&#xff0c;备受瞩目的程序员薪资调研报告再度登场。由知名数据采集平台levels.fyi 搜集并整理了《2023年全球程序员收入报告》&#xff0c;为我们揭示了程序员最新的收入情况&#xff0c;其中有哪些值得关注的亮点呢&#xff1f; 行情向好&#xff0c;大多…

burp靶场——XXE注入

XML 外部实体 (XXE) 注入 1. 什么是xxe漏洞&#xff1a; https://portswigger.net/web-security/xxe#what-is-xml-external-entity-injection XML 外部实体注入&#xff08;也称为 XXE&#xff09;是一种 Web 安全漏洞&#xff0c;允许攻击者干扰应用程序对 XML 数据的处理。…

GEE:机器学习分类中每个类别的概率图像可视化

作者:CSDN @ _养乐多_ 在 Google Earth Engine(GEE) 中应用机器学习分类器进行多分类时,有一个需求是想知道每个像素对于每个类别的分类概率。 比如在进行随机森林分类时,每个决策树会生成一个类别,通过投票选择票数最多的类别作为最终分类。除了最终分类结果,其他类别…