任务流程:RGB摄像头 --> AlphaPose(2D) --> HybrIK(3D) --> 数据预处理 --> .npz动作包 --> 训练
1.RGB摄像头
摄像头型号:D435i
下载realsense iewer 图形界面工具

可能遇到的问题:无法识别摄像头

摄像头驱动问题 重新插摄像头
验证摄像头:

2.使用alphapose获取摄像头输入的2d关键点坐标
AlphaPose 项目网址 https://github.com/MVIG-SJTU/AlphaPose
权重文件: fast_res50_256x192_2.pth
跟踪权重文件:1myNKfr2cXqiHZVXaaG8ZAq_U2UpeOLfG
https://drive.google.com/file/d/1myNKfr2cXqiHZVXaaG8ZAq_U2UpeOLfG/view?usp=share_link

每次pip install -e. 以开发者模式安装都会卡住
解决办法:设置临时环境变量


问题: 没有安装 Intel RealSense SDK
# 添加官方 apt-key
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-key F6E5AC44F831C80BA66380CB3A563A5F3EFCDE
# 添加 RealSense 官方 APT 仓库
sudo add-apt-repository "deb https://librealsense.intel.com/Debian/apt-repo $(lsb_release -cs) main" -u
# 更新软件包列表
sudo apt-get update
# 安装 RealSense 驱动与开发库
sudo apt-get install librealsense2-dkms
sudo apt-get install librealsense2-dev
sudo apt-get install librealsense2-utils

问题:OpenCV 尝试用 index=0 打开摄像头失败,因为 RealSense 不是标准 UVC 摄像头,不能被 cv2.VideoCapture(0) 识别。
cv2.VideoCapture 是为标准 UVC 摄像头设计的, 而RealSense 摄像头是专用协议和复杂的多数据流结构。要使用 pyrealsense2 这样的专用 SDK 来首先获取原始图像数据,然后再将其交给 OpenCV 或 AlphaPose 进行后续处理
解决:更改alphapose/utils/webcam_detector.py
from itertools import count
from threading import Thread
from queue import Queue
import cv2
import numpy as np
import pyrealsense2 as rs # Import RealSense
import torch
import torch.multiprocessing as mp
from alphapose.utils.presets import SimpleTransform, SimpleTransform3DSMPL
class WebCamDetectionLoader():
def __init__(self, input_source, detector, cfg, opt, queueSize=1):
self.cfg = cfg
self.opt = opt
self.input_source = input_source # Store the input source identifier
# Check if input_source indicates RealSense (e.g., "realsense")
if input_source.lower() == "realsense":
self.use_realsense = True
# Initialize RealSense pipeline here or just store config
# We'll initialize the pipeline inside frame_preprocess to avoid conflicts
self.frameSize = (640, 480) # Default resolution, can be changed
self.fps = 30 # Default FPS, can be changed
self.videoinfo = {'fourcc': None, 'fps': self.fps, 'frameSize': self.frameSize}
else:
self.use_realsense = False
# Original logic for standard webcam
stream = cv2.VideoCapture(int(input_source))
assert stream.isOpened(), 'Cannot capture source'
self.path = input_source
self.fourcc = int(stream.get(cv2.CAP_PROP_FOURCC))
self.fps = stream.get(cv2.CAP_PROP_FPS)
self.frameSize = (int(stream.get(cv2.CAP_PROP_FRAME_WIDTH)), int(stream.get(cv2.CAP_PROP_FRAME_HEIGHT)))
self.videoinfo = {'fourcc': self.fourcc, 'fps': self.fps, 'frameSize': self.frameSize}
stream.release()
self.detector = detector
self._input_size = cfg.DATA_PRESET.IMAGE_SIZE
self._output_size = cfg.DATA_PRESET.HEATMAP_SIZE
self._sigma = cfg.DATA_PRESET.SIGMA
if cfg.DATA_PRESET.TYPE == 'simple':
self.transformation = SimpleTransform(
self, scale_factor=0,
input_size=self._input_size,
output_size=self._output_size,
rot=0, sigma=self._sigma,
train=False, add_dpg=False)
elif cfg.DATA_PRESET.TYPE == 'simple_smpl':
# TODO: new features
from easydict import EasyDict as edict
dummpy_set = edict({
'joint_pairs_17': None,
'joint_pairs_24': None,
'joint_pairs_29': None,
'bbox_3d_shape': (2.2, 2.2, 2.2)
})
self.transformation = SimpleTransform3DSMPL(
dummpy_set, scale_factor=cfg.DATASET.SCALE_FACTOR,
color_factor=cfg.DATASET.COLOR_FACTOR,
occlusion=cfg.DATASET.OCCLUSION,
input_size=cfg.MODEL.IMAGE_SIZE,
output_size=cfg.MODEL.HEATMAP_SIZE,
depth_dim=cfg.MODEL.EXTRA.DEPTH_DIM,
bbox_3d_shape=(2.2, 2.2, 2.2),
rot=cfg.DATASET.ROT_FACTOR, sigma=cfg.MODEL.EXTRA.SIGMA,
train=False, add_dpg=False, gpu_device=self.device,
loss_type=cfg.LOSS['TYPE'])
# initialize the queue used to store data
"""
pose_queue: the buffer storing post-processed cropped human image for pose estimation
"""
if opt.sp:
self._stopped = False
self.pose_queue = Queue(maxsize=queueSize)
else:
self._stopped = mp.Value('b', False)
self.pose_queue = mp.Queue(maxsize=queueSize)
def start_worker(self, target):
if self.opt.sp:
p = Thread(target=target, args=())
else:
p = mp.Process(target=target, args=())
# p.daemon = True
p.start()
return p
def start(self):
# start a thread to pre process images for object detection
image_preprocess_worker = self.start_worker(self.frame_preprocess)
return [image_preprocess_worker]
def stop(self):
# clear queues
self.clear_queues()
def terminate(self):
if self.opt.sp:
self._stopped = True
else:
self._stopped.value = True
self.stop()
def clear_queues(self):
self.clear(self.pose_queue)
def clear(self, queue):
while not queue.empty():
queue.get()
def wait_and_put(self, queue, item):
if not self.stopped:
queue.put(item)
def wait_and_get(self, queue):
if not self.stopped:
return queue.get()
def frame_preprocess(self):
if self.use_realsense:
# --- RealSense Specific Logic ---
print("WebCamDetectionLoader: Initializing RealSense pipeline...")
pipeline = rs.pipeline()
config = rs.config()
# Configure the pipeline to stream color frames as BGR (OpenCV compatible)
config.enable_stream(rs.stream.color, self.frameSize[0], self.frameSize[1], rs.format.bgr8, int(self.fps))
profile = pipeline.start(config)
print("WebCamDetectionLoader: RealSense pipeline started.")
else:
# --- Original Standard Webcam Logic ---
stream = cv2.VideoCapture(self.path)
assert stream.isOpened(), 'Cannot capture source'
# keep looping infinitely
for i in count():
if self.stopped:
if self.use_realsense:
print("WebCamDetectionLoader: Stopping RealSense pipeline...")
pipeline.stop()
print("WebCamDetectionLoader: RealSense pipeline stopped.")
else:
stream.release()
return
if not self.pose_queue.full():
# otherwise, ensure the queue has room in it
if self.use_realsense:
# Get frames from RealSense
frames = pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
if not color_frame:
continue # Skip if no frame received
# ✅ CRITICAL FIX: Keep as BGR — NO conversion!
frame = np.asanyarray(color_frame.get_data()) # BGR format
grabbed = True
else:
(grabbed, frame) = stream.read()
# if the `grabbed` boolean is `False`, then we have
# reached the end of the video file
if not grabbed:
self.wait_and_put(self.pose_queue, (None, None, None, None, None, None, None))
if self.use_realsense:
pipeline.stop()
else:
stream.release()
return
# expected frame shape like (1,3,h,w) or (3,h,w)
img_k = self.detector.image_preprocess(frame)
if isinstance(img_k, np.ndarray):
img_k = torch.from_numpy(img_k)
# add one dimension at the front for batch if image shape (3,h,w)
if img_k.dim() == 3:
img_k = img_k.unsqueeze(0)
im_dim_list_k = frame.shape[1], frame.shape[0]
# ✅ orig_img must be BGR for vis_frame (which uses cv2 drawing)
orig_img = frame # ← KEEP AS BGR! Do NOT convert with ::-1
im_name = str(i) + '.jpg'
with torch.no_grad():
# Record original image resolution
im_dim_list_k = torch.FloatTensor(im_dim_list_k).repeat(1, 2)
img_det = self.image_detection((img_k, orig_img, im_name, im_dim_list_k))
self.image_postprocess(img_det)
def image_detection(self, inputs):
img, orig_img, im_name, im_dim_list = inputs
if img is None or self.stopped:
return (None, None, None, None, None, None, None)
with torch.no_grad():
dets = self.detector.images_detection(img, im_dim_list)
if isinstance(dets, int) or dets.shape[0] == 0:
return (orig_img, im_name, None, None, None, None, None)
if isinstance(dets, np.ndarray):
dets = torch.from_numpy(dets)
dets = dets.cpu()
boxes = dets[:, 1:5]
scores = dets[:, 5:6]
if self.opt.tracking:
ids = dets[:, 6:7]
else:
ids = torch.zeros(scores.shape)
boxes_k = boxes[dets[:, 0] == 0]
if isinstance(boxes_k, int) or boxes_k.shape[0] == 0:
return (orig_img, im_name, None, None, None, None, None)
inps = torch.zeros(boxes_k.size(0), 3, *self._input_size)
cropped_boxes = torch.zeros(boxes_k.size(0), 4)
return (orig_img, im_name, boxes_k, scores[dets[:, 0] == 0], ids[dets[:, 0] == 0], inps, cropped_boxes)
def image_postprocess(self, inputs):
with torch.no_grad():
(orig_img, im_name, boxes, scores, ids, inps, cropped_boxes) = inputs
if orig_img is None or self.stopped:
self.wait_and_put(self.pose_queue, (None, None, None, None, None, None, None))
return
if boxes is None or boxes.nelement() == 0:
self.wait_and_put(self.pose_queue, (None, orig_img, im_name, boxes, scores, ids, None))
return
# imght = orig_img.shape[0]
# imgwidth = orig_img.shape[1]
for i, box in enumerate(boxes):
inps[i], cropped_box = self.transformation.test_transform(orig_img, box)
cropped_boxes[i] = torch.FloatTensor(cropped_box)
# inps, cropped_boxes = self.transformation.align_transform(orig_img, boxes)
self.wait_and_put(self.pose_queue, (inps, orig_img, im_name, boxes, scores, ids, cropped_boxes))
def read(self):
return self.wait_and_get(self.pose_queue)
@property
def stopped(self):
if self.opt.sp:
return self._stopped
else:
return self._stopped.value
@property
def joint_pairs(self):
"""Joint pairs which defines the pairs of joint to be swapped
when the image is flipped horizontally."""
return [[1, 2], [3, 4], [5, 6], [7, 8],
[9, 10], [11, 12], [13, 14], [15, 16]]
检查 demo_inference.py 的参数定义。--webcam 参数被定义为 type=int,所以它期望一个数字(通常是摄像头索引,如 0, 1)。我们不能直接传入字符串 "realsense"。
我们需要稍微修改 scripts/demo_inference.py 文件,让它能够接受 "realsense" 作为 --webcam 的有效值。
labuser@labuser-ThinkCentre-M950t:~/unitree_ws/src/AlphaPose-master$ cat scripts/demo_inference.py
"""Script for single-gpu/multi-gpu demo."""
import argparse
import os
import platform
import sys
import time
import numpy as np
import torch
from tqdm import tqdm
import natsort
from detector.apis import get_detector
from trackers.tracker_api import Tracker
from trackers.tracker_cfg import cfg as tcfg
from trackers import track
from alphapose.models import builder
from alphapose.utils.config import update_config
from alphapose.utils.detector import DetectionLoader
from alphapose.utils.file_detector import FileDetectionLoader
from alphapose.utils.transforms import flip, flip_heatmap
from alphapose.utils.vis import getTime
from alphapose.utils.webcam_detector import WebCamDetectionLoader
from alphapose.utils.writer import DataWriter
"""----------------------------- Demo options -----------------------------"""
parser = argparse.ArgumentParser(description='AlphaPose Demo')
parser.add_argument('--cfg', type=str, required=True,
help='experiment configure file name')
parser.add_argument('--checkpoint', type=str, required=True,
help='checkpoint file name')
parser.add_argument('--sp', default=False, action='store_true',
help='Use single process for pytorch')
parser.add_argument('--detector', dest='detector',
help='detector name', default="yolo")
parser.add_argument('--detfile', dest='detfile',
help='detection result file', default="")
parser.add_argument('--indir', dest='inputpath',
help='image-directory', default="")
parser.add_argument('--list', dest='inputlist',
help='image-list', default="")
parser.add_argument('--image', dest='inputimg',
help='image-name', default="")
parser.add_argument('--outdir', dest='outputpath',
help='output-directory', default="examples/res/")
parser.add_argument('--save_img', default=False, action='store_true',
help='save result as image')
parser.add_argument('--vis', default=False, action='store_true',
help='visualize image')
parser.add_argument('--showbox', default=False, action='store_true',
help='visualize human bbox')
parser.add_argument('--profile', default=False, action='store_true',
help='add speed profiling at screen output')
parser.add_argument('--format', type=str,
help='save in the format of cmu or coco or openpose, option: coco/cmu/open')
parser.add_argument('--min_box_area', type=int, default=0,
help='min box area to filter out')
parser.add_argument('--detbatch', type=int, default=5,
help='detection batch size PER GPU')
parser.add_argument('--posebatch', type=int, default=64,
help='pose estimation maximum batch size PER GPU')
parser.add_argument('--eval', dest='eval', default=False, action='store_true',
help='save the result json as coco format, using image index(int) instead of image name(str)')
parser.add_argument('--gpus', type=str, dest='gpus', default="0",
help='choose which cuda device to use by index and input comma to use multi gpus, e.g. 0,1,2,3. (input -1 for cpu only)')
parser.add_argument('--qsize', type=int, dest='qsize', default=1024,
help='the length of result buffer, where reducing it will lower requirement of cpu memory')
parser.add_argument('--flip', default=False, action='store_true',
help='enable flip testing')
parser.add_argument('--debug', default=False, action='store_true',
help='print detail information')
"""----------------------------- Video options -----------------------------"""
parser.add_argument('--video', dest='video',
help='video-name', default="")
parser.add_argument('--webcam', dest='webcam', type=str,
help='webcam number (e.g., 0, 1) or "realsense"', default=None)
parser.add_argument('--save_video', dest='save_video',
help='whether to save rendered video', default=False, action='store_true')
parser.add_argument('--vis_fast', dest='vis_fast',
help='use fast rendering', action='store_true', default=False)
"""----------------------------- Tracking options -----------------------------"""
parser.add_argument('--pose_flow', dest='pose_flow',
help='track humans in video with PoseFlow', action='store_true', default=False)
parser.add_argument('--pose_track', dest='pose_track',
help='track humans in video with reid', action='store_true', default=False)
args = parser.parse_args()
cfg = update_config(args.cfg)
if platform.system() == 'Windows':
args.sp = True
args.gpus = [int(i) for i in args.gpus.split(',')] if torch.cuda.device_count() >= 1 else [-1]
args.device = torch.device("cuda:" + str(args.gpus[0]) if args.gpus[0] >= 0 else "cpu")
args.detbatch = args.detbatch * len(args.gpus)
args.posebatch = args.posebatch * len(args.gpus)
args.tracking = args.pose_track or args.pose_flow or args.detector=='tracker'
if not args.sp:
torch.multiprocessing.set_start_method('forkserver', force=True)
torch.multiprocessing.set_sharing_strategy('file_system')
def check_input():
# for webcam
if args.webcam is not None:
args.detbatch = 1
# Check if it's a standard webcam index or realsense
if args.webcam.lower() == 'realsense':
return 'webcam', 'realsense'
else:
return 'webcam', int(args.webcam)
# for video
if len(args.video):
if os.path.isfile(args.video):
videofile = args.video
return 'video', videofile
else:
raise IOError('Error: --video must refer to a video file, not directory.')
# for detection results
if len(args.detfile):
if os.path.isfile(args.detfile):
detfile = args.detfile
return 'detfile', detfile
else:
raise IOError('Error: --detfile must refer to a detection json file, not directory.')
# for images
if len(args.inputpath) or len(args.inputlist) or len(args.inputimg):
inputpath = args.inputpath
inputlist = args.inputlist
inputimg = args.inputimg
if len(inputlist):
im_names = open(inputlist, 'r').readlines()
elif len(inputpath) and inputpath != '/':
for root, dirs, files in os.walk(inputpath):
im_names = files
im_names = natsort.natsorted(im_names)
elif len(inputimg):
args.inputpath = os.path.split(inputimg)[0]
im_names = [os.path.split(inputimg)[1]]
return 'image', im_names
else:
raise NotImplementedError
def print_finish_info():
print('===========================> Finish Model Running.')
if (args.save_img or args.save_video) and not args.vis_fast:
print('===========================> Rendering remaining images in the queue...')
print('===========================> If this step takes too long, you can enable the --vis_fast flag to use fast rendering (real-time).')
def loop():
n = 0
while True:
yield n
n += 1
if __name__ == "__main__":
mode, input_source = check_input()
if not os.path.exists(args.outputpath):
os.makedirs(args.outputpath)
# Load detection loader
if mode == 'webcam':
det_loader = WebCamDetectionLoader(input_source, get_detector(args), cfg, args)
det_worker = det_loader.start()
elif mode == 'detfile':
det_loader = FileDetectionLoader(input_source, cfg, args)
det_worker = det_loader.start()
else:
det_loader = DetectionLoader(input_source, get_detector(args), cfg, args, batchSize=args.detbatch, mode=mode, queueSize=args.qsize)
det_worker = det_loader.start()
# Load pose model
pose_model = builder.build_sppe(cfg.MODEL, preset_cfg=cfg.DATA_PRESET)
print('Loading pose model from %s...' % (args.checkpoint,))
pose_model.load_state_dict(torch.load(args.checkpoint, map_location=args.device))
pose_dataset = builder.retrieve_dataset(cfg.DATASET.TRAIN)
if args.pose_track:
tracker = Tracker(tcfg, args)
if len(args.gpus) > 1:
pose_model = torch.nn.DataParallel(pose_model, device_ids=args.gpus).to(args.device)
else:
pose_model.to(args.device)
pose_model.eval()
runtime_profile = {
'dt': [],
'pt': [],
'pn': []
}
# Init data writer
queueSize = 2 if mode == 'webcam' else args.qsize
if args.save_video and mode != 'image':
from alphapose.utils.writer import DEFAULT_VIDEO_SAVE_OPT as video_save_opt
if mode == 'video':
video_save_opt['savepath'] = os.path.join(args.outputpath, 'AlphaPose_' + os.path.basename(input_source))
else:
video_save_opt['savepath'] = os.path.join(args.outputpath, 'AlphaPose_webcam' + str(input_source) + '.mp4')
video_save_opt.update(det_loader.videoinfo)
writer = DataWriter(cfg, args, save_video=True, video_save_opt=video_save_opt, queueSize=queueSize).start()
else:
writer = DataWriter(cfg, args, save_video=False, queueSize=queueSize).start()
if mode == 'webcam':
print('Starting webcam demo, press Ctrl + C to terminate...')
sys.stdout.flush()
im_names_desc = tqdm(loop())
else:
data_len = det_loader.length
im_names_desc = tqdm(range(data_len), dynamic_ncols=True)
batchSize = args.posebatch
if args.flip:
batchSize = int(batchSize / 2)
try:
for i in im_names_desc:
start_time = getTime()
with torch.no_grad():
(inps, orig_img, im_name, boxes, scores, ids, cropped_boxes) = det_loader.read()
if orig_img is None:
break
if boxes is None or boxes.nelement() == 0:
writer.save(None, None, None, None, None, orig_img, im_name)
continue
if args.profile:
ckpt_time, det_time = getTime(start_time)
runtime_profile['dt'].append(det_time)
# Pose Estimation
inps = inps.to(args.device)
datalen = inps.size(0)
leftover = 0
if (datalen) % batchSize:
leftover = 1
num_batches = datalen // batchSize + leftover
hm = []
for j in range(num_batches):
inps_j = inps[j * batchSize:min((j + 1) * batchSize, datalen)]
if args.flip:
inps_j = torch.cat((inps_j, flip(inps_j)))
hm_j = pose_model(inps_j)
if args.flip:
hm_j_flip = flip_heatmap(hm_j[int(len(hm_j) / 2):], pose_dataset.joint_pairs, shift=True)
hm_j = (hm_j[0:int(len(hm_j) / 2)] + hm_j_flip) / 2
hm.append(hm_j)
hm = torch.cat(hm)
if args.profile:
ckpt_time, pose_time = getTime(ckpt_time)
runtime_profile['pt'].append(pose_time)
if args.pose_track:
boxes,scores,ids,hm,cropped_boxes = track(tracker,args,orig_img,inps,boxes,hm,cropped_boxes,im_name,scores)
hm = hm.cpu()
writer.save(boxes, scores, ids, hm, cropped_boxes, orig_img, im_name)
if args.profile:
ckpt_time, post_time = getTime(ckpt_time)
runtime_profile['pn'].append(post_time)
if args.profile:
# TQDM
im_names_desc.set_description(
'det time: {dt:.4f} | pose time: {pt:.4f} | post processing: {pn:.4f}'.format(
dt=np.mean(runtime_profile['dt']), pt=np.mean(runtime_profile['pt']), pn=np.mean(runtime_profile['pn']))
)
print_finish_info()
while(writer.running()):
time.sleep(1)
print('===========================> Rendering remaining ' + str(writer.count()) + ' images in the queue...', end='\r')
writer.stop()
det_loader.stop()
except Exception as e:
print(repr(e))
print('An error as above occurs when processing the images, please check it')
pass
except KeyboardInterrupt:
print_finish_info()
# Thread won't be killed when press Ctrl+C
if args.sp:
det_loader.terminate()
while(writer.running()):
time.sleep(1)
print('===========================> Rendering remaining ' + str(writer.count()) + ' images in the queue...', end='\r')
writer.stop()
else:
# subprocesses are killed, manually clear queues
det_loader.terminate()
writer.terminate()
writer.clear_queues()
det_loader.clear_queues()
python scripts/demo_inference.py --cfg configs/coco/resnet/256x192_res50_lr1e-3_1x.yaml --checkpoint pretrained_models/fast_res50_256x192.pth --outdir examples/res --vis --webcam realsense
指定摄像头输入 可视化结果(骨架) gpu加速
补充跟踪模型权重文件之后可以加上 --pose_track参数 以及--gpus 0 使用gpu加速

骨架线(黄色、蓝色、绿色等)是 AlphaPose 的标准可视化输出:AlphaPose 在检测到人体后,会根据其姿态估计模型(如 ResNet50)预测出 17 个关键点(Keypoints),然后用线条将这些关键点连接起来,形成我们看到的骨架图。这些颜色和连线方式是由 AlphaPose 的 vis.py 模块定义的,是其标准功能。
颜色失真问题:
RealSense 输出的是 BGR 格式(与 OpenCV 一致);
但 AlphaPose 的模型推理和可视化模块内部期望输入是 RGB(因为 PyTorch 图像预处理通常基于 PIL/RGB);
解决:在 writer.py 文件的write_image 函数中添加了从 RGB 到 BGR 的颜色空间转换
更改 alphapose/utils/writer.py
import os
import time
from threading import Thread
from queue import Queue
import cv2
import numpy as np
import torch
import torch.multiprocessing as mp
from alphapose.utils.transforms import get_func_heatmap_to_coord
from alphapose.utils.pPose_nms import pose_nms, write_json
DEFAULT_VIDEO_SAVE_OPT = {
'savepath': 'examples/res/1.mp4',
'fourcc': cv2.VideoWriter_fourcc(*'mp4v'),
'fps': 25,
'frameSize': (640, 480)
}
EVAL_JOINTS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
class DataWriter():
def __init__(self, cfg, opt, save_video=False,
video_save_opt=DEFAULT_VIDEO_SAVE_OPT,
queueSize=1024):
self.cfg = cfg
self.opt = opt
self.video_save_opt = video_save_opt
self.eval_joints = EVAL_JOINTS
self.save_video = save_video
self.heatmap_to_coord = get_func_heatmap_to_coord(cfg)
# initialize the queue used to store frames read from
# the video file
if opt.sp:
self.result_queue = Queue(maxsize=queueSize)
else:
self.result_queue = mp.Queue(maxsize=queueSize)
if opt.save_img:
if not os.path.exists(opt.outputpath + '/vis'):
os.mkdir(opt.outputpath + '/vis')
if opt.pose_flow:
from trackers.PoseFlow.poseflow_infer import PoseFlowWrapper
self.pose_flow_wrapper = PoseFlowWrapper(save_path=os.path.join(opt.outputpath, 'poseflow'))
if self.opt.save_img or self.save_video or self.opt.vis:
loss_type = self.cfg.DATA_PRESET.get('LOSS_TYPE', 'MSELoss')
num_joints = self.cfg.DATA_PRESET.NUM_JOINTS
if loss_type == 'MSELoss':
self.vis_thres = [0.4] * num_joints
elif 'JointRegression' in loss_type:
self.vis_thres = [0.05] * num_joints
elif loss_type == 'Combined':
if num_joints == 68:
hand_face_num = 42
else:
hand_face_num = 110
self.vis_thres = [0.4] * (num_joints - hand_face_num) + [0.05] * hand_face_num
self.use_heatmap_loss = (self.cfg.DATA_PRESET.get('LOSS_TYPE', 'MSELoss') == 'MSELoss')
def start_worker(self, target):
if self.opt.sp:
p = Thread(target=target, args=())
else:
p = mp.Process(target=target, args=())
# p.daemon = True
p.start()
return p
def start(self):
# start a thread to read pose estimation results per frame
self.result_worker = self.start_worker(self.update)
return self
def update(self):
final_result = []
norm_type = self.cfg.LOSS.get('NORM_TYPE', None)
hm_size = self.cfg.DATA_PRESET.HEATMAP_SIZE
if self.save_video:
# initialize the file video stream, adapt ouput video resolution to original video
stream = cv2.VideoWriter(*[self.video_save_opt[k] for k in ['savepath', 'fourcc', 'fps', 'frameSize']])
if not stream.isOpened():
print("Try to use other video encoders...")
ext = self.video_save_opt['savepath'].split('.')[-1]
fourcc, _ext = self.recognize_video_ext(ext)
self.video_save_opt['fourcc'] = fourcc
self.video_save_opt['savepath'] = self.video_save_opt['savepath'][:-4] + _ext
stream = cv2.VideoWriter(*[self.video_save_opt[k] for k in ['savepath', 'fourcc', 'fps', 'frameSize']])
assert stream.isOpened(), 'Cannot open video for writing'
# keep looping infinitelyd
while True:
# ensure the queue is not empty and get item
(boxes, scores, ids, hm_data, cropped_boxes, orig_img, im_name) = self.wait_and_get(self.result_queue)
if orig_img is None:
# if the thread indicator variable is set (img is None), stop the thread
if self.save_video:
stream.release()
write_json(final_result, self.opt.outputpath, form=self.opt.format, for_eval=self.opt.eval)
print("Results have been written to json.")
return
# image channel RGB->BGR
orig_img = np.array(orig_img, dtype=np.uint8)[:, :, ::-1]
if boxes is None or len(boxes) == 0:
if self.opt.save_img or self.save_video or self.opt.vis:
self.write_image(orig_img, im_name, stream=stream if self.save_video else None)
else:
# location prediction (n, kp, 2) | score prediction (n, kp, 1)
assert hm_data.dim() == 4
face_hand_num = 110
if hm_data.size()[1] == 136:
self.eval_joints = [*range(0,136)]
elif hm_data.size()[1] == 26:
self.eval_joints = [*range(0,26)]
elif hm_data.size()[1] == 133:
self.eval_joints = [*range(0,133)]
elif hm_data.size()[1] == 68:
face_hand_num = 42
self.eval_joints = [*range(0,68)]
elif hm_data.size()[1] == 21:
self.eval_joints = [*range(0,21)]
pose_coords = []
pose_scores = []
for i in range(hm_data.shape[0]):
bbox = cropped_boxes[i].tolist()
if isinstance(self.heatmap_to_coord, list):
pose_coords_body_foot, pose_scores_body_foot = self.heatmap_to_coord[0](
hm_data[i][self.eval_joints[:-face_hand_num]], bbox, hm_shape=hm_size, norm_type=norm_type)
pose_coords_face_hand, pose_scores_face_hand = self.heatmap_to_coord[1](
hm_data[i][self.eval_joints[-face_hand_num:]], bbox, hm_shape=hm_size, norm_type=norm_type)
pose_coord = np.concatenate((pose_coords_body_foot, pose_coords_face_hand), axis=0)
pose_score = np.concatenate((pose_scores_body_foot, pose_scores_face_hand), axis=0)
else:
pose_coord, pose_score = self.heatmap_to_coord(hm_data[i][self.eval_joints], bbox, hm_shape=hm_size, norm_type=norm_type)
pose_coords.append(torch.from_numpy(pose_coord).unsqueeze(0))
pose_scores.append(torch.from_numpy(pose_score).unsqueeze(0))
preds_img = torch.cat(pose_coords)
preds_scores = torch.cat(pose_scores)
if not self.opt.pose_track:
boxes, scores, ids, preds_img, preds_scores, pick_ids = \
pose_nms(boxes, scores, ids, preds_img, preds_scores, self.opt.min_box_area, use_heatmap_loss=self.use_heatmap_loss)
_result = []
for k in range(len(scores)):
_result.append(
{
'keypoints':preds_img[k],
'kp_score':preds_scores[k],
'proposal_score': torch.mean(preds_scores[k]) + scores[k] + 1.25 * max(preds_scores[k]),
'idx':ids[k],
'box':[boxes[k][0], boxes[k][1], boxes[k][2]-boxes[k][0],boxes[k][3]-boxes[k][1]]
}
)
result = {
'imgname': im_name,
'result': _result
}
if self.opt.pose_flow:
poseflow_result = self.pose_flow_wrapper.step(orig_img, result)
for i in range(len(poseflow_result)):
result['result'][i]['idx'] = poseflow_result[i]['idx']
final_result.append(result)
if self.opt.save_img or self.save_video or self.opt.vis:
if hm_data.size()[1] == 49:
from alphapose.utils.vis import vis_frame_dense as vis_frame
elif self.opt.vis_fast:
from alphapose.utils.vis import vis_frame_fast as vis_frame
else:
from alphapose.utils.vis import vis_frame
img = vis_frame(orig_img, result, self.opt, self.vis_thres)
self.write_image(img, im_name, stream=stream if self.save_video else None)
def write_image(self, img, im_name, stream=None):
if self.opt.vis:
# 修复:确保 cv2.imshow 接收 BGR 格式
if img is not None and len(img.shape) == 3 and img.shape[-1] == 3:
img_display = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
else:
img_display = img
cv2.imshow("AlphaPose Demo", img_display)
cv2.waitKey(30)
if self.opt.save_img:
# 修复:保存时也转换格式
if img is not None and len(img.shape) == 3 and img.shape[-1] == 3:
img_save = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
else:
img_save = img
cv2.imwrite(os.path.join(self.opt.outputpath, 'vis', im_name), img_save)
if self.save_video:
# 修复:视频写入也转换格式
if img is not None and len(img.shape) == 3 and img.shape[-1] == 3:
img_video = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
else:
img_video = img
stream.write(img_video)
def wait_and_put(self, queue, item):
queue.put(item)
def wait_and_get(self, queue):
return queue.get()
def save(self, boxes, scores, ids, hm_data, cropped_boxes, orig_img, im_name):
# save next frame in the queue
self.wait_and_put(self.result_queue, (boxes, scores, ids, hm_data, cropped_boxes, orig_img, im_name))
def running(self):
# indicate that the thread is still running
return not self.result_queue.empty()
def count(self):
# indicate the remaining images
return self.result_queue.qsize()
def stop(self):
# indicate that the thread should be stopped
self.save(None, None, None, None, None, None, None)
self.result_worker.join()
def terminate(self):
# directly terminate
self.result_worker.terminate()
def clear_queues(self):
self.clear(self.result_queue)
def clear(self, queue):
while not queue.empty():
queue.get()
def results(self):
# return final result
print(self.final_result)
return self.final_result
def recognize_video_ext(self, ext=''):
if ext == 'mp4':
return cv2.VideoWriter_fourcc(*'mp4v'), '.' + ext
elif ext == 'avi':
return cv2.VideoWriter_fourcc(*'XVID'), '.' + ext
elif ext == 'mov':
return cv2.VideoWriter_fourcc(*'XVID'), '.' + ext
else:
print("Unknow video format {}, will use .mp4 instead of it".format(ext))
return cv2.VideoWriter_fourcc(*'mp4v'), '.mp4'
更改:build/lib/alphapose/utils/writer.py
import os
import time
from threading import Thread
from queue import Queue
import cv2
import numpy as np
import torch
import torch.multiprocessing as mp
from alphapose.utils.transforms import get_func_heatmap_to_coord
from alphapose.utils.pPose_nms import pose_nms, write_json
DEFAULT_VIDEO_SAVE_OPT = {
'savepath': 'examples/res/1.mp4',
'fourcc': cv2.VideoWriter_fourcc(*'mp4v'),
'fps': 25,
'frameSize': (640, 480)
}
EVAL_JOINTS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
class DataWriter():
def __init__(self, cfg, opt, save_video=False,
video_save_opt=DEFAULT_VIDEO_SAVE_OPT,
queueSize=1024):
self.cfg = cfg
self.opt = opt
self.video_save_opt = video_save_opt
self.eval_joints = EVAL_JOINTS
self.save_video = save_video
self.heatmap_to_coord = get_func_heatmap_to_coord(cfg)
# initialize the queue used to store frames read from
# the video file
if opt.sp:
self.result_queue = Queue(maxsize=queueSize)
else:
self.result_queue = mp.Queue(maxsize=queueSize)
if opt.save_img:
if not os.path.exists(opt.outputpath + '/vis'):
os.mkdir(opt.outputpath + '/vis')
if opt.pose_flow:
from trackers.PoseFlow.poseflow_infer import PoseFlowWrapper
self.pose_flow_wrapper = PoseFlowWrapper(save_path=os.path.join(opt.outputpath, 'poseflow'))
if self.opt.save_img or self.save_video or self.opt.vis:
loss_type = self.cfg.DATA_PRESET.get('LOSS_TYPE', 'MSELoss')
num_joints = self.cfg.DATA_PRESET.NUM_JOINTS
if loss_type == 'MSELoss':
self.vis_thres = [0.4] * num_joints
elif 'JointRegression' in loss_type:
self.vis_thres = [0.05] * num_joints
elif loss_type == 'Combined':
if num_joints == 68:
hand_face_num = 42
else:
hand_face_num = 110
self.vis_thres = [0.4] * (num_joints - hand_face_num) + [0.05] * hand_face_num
self.use_heatmap_loss = (self.cfg.DATA_PRESET.get('LOSS_TYPE', 'MSELoss') == 'MSELoss')
def start_worker(self, target):
if self.opt.sp:
p = Thread(target=target, args=())
else:
p = mp.Process(target=target, args=())
# p.daemon = True
p.start()
return p
def start(self):
# start a thread to read pose estimation results per frame
self.result_worker = self.start_worker(self.update)
return self
def update(self):
final_result = []
norm_type = self.cfg.LOSS.get('NORM_TYPE', None)
hm_size = self.cfg.DATA_PRESET.HEATMAP_SIZE
if self.save_video:
# initialize the file video stream, adapt ouput video resolution to original video
stream = cv2.VideoWriter(*[self.video_save_opt[k] for k in ['savepath', 'fourcc', 'fps', 'frameSize']])
if not stream.isOpened():
print("Try to use other video encoders...")
ext = self.video_save_opt['savepath'].split('.')[-1]
fourcc, _ext = self.recognize_video_ext(ext)
self.video_save_opt['fourcc'] = fourcc
self.video_save_opt['savepath'] = self.video_save_opt['savepath'][:-4] + _ext
stream = cv2.VideoWriter(*[self.video_save_opt[k] for k in ['savepath', 'fourcc', 'fps', 'frameSize']])
assert stream.isOpened(), 'Cannot open video for writing'
# keep looping infinitelyd
while True:
# ensure the queue is not empty and get item
(boxes, scores, ids, hm_data, cropped_boxes, orig_img, im_name) = self.wait_and_get(self.result_queue)
if orig_img is None:
# if the thread indicator variable is set (img is None), stop the thread
if self.save_video:
stream.release()
write_json(final_result, self.opt.outputpath, form=self.opt.format, for_eval=self.opt.eval)
print("Results have been written to json.")
return
# image channel RGB->BGR
orig_img = np.array(orig_img, dtype=np.uint8)[:, :, ::-1]
if boxes is None or len(boxes) == 0:
if self.opt.save_img or self.save_video or self.opt.vis:
self.write_image(orig_img, im_name, stream=stream if self.save_video else None)
else:
# location prediction (n, kp, 2) | score prediction (n, kp, 1)
assert hm_data.dim() == 4
face_hand_num = 110
if hm_data.size()[1] == 136:
self.eval_joints = [*range(0,136)]
elif hm_data.size()[1] == 26:
self.eval_joints = [*range(0,26)]
elif hm_data.size()[1] == 133:
self.eval_joints = [*range(0,133)]
elif hm_data.size()[1] == 68:
face_hand_num = 42
self.eval_joints = [*range(0,68)]
elif hm_data.size()[1] == 21:
self.eval_joints = [*range(0,21)]
pose_coords = []
pose_scores = []
for i in range(hm_data.shape[0]):
bbox = cropped_boxes[i].tolist()
if isinstance(self.heatmap_to_coord, list):
pose_coords_body_foot, pose_scores_body_foot = self.heatmap_to_coord[0](
hm_data[i][self.eval_joints[:-face_hand_num]], bbox, hm_shape=hm_size, norm_type=norm_type)
pose_coords_face_hand, pose_scores_face_hand = self.heatmap_to_coord[1](
hm_data[i][self.eval_joints[-face_hand_num:]], bbox, hm_shape=hm_size, norm_type=norm_type)
pose_coord = np.concatenate((pose_coords_body_foot, pose_coords_face_hand), axis=0)
pose_score = np.concatenate((pose_scores_body_foot, pose_scores_face_hand), axis=0)
else:
pose_coord, pose_score = self.heatmap_to_coord(hm_data[i][self.eval_joints], bbox, hm_shape=hm_size, norm_type=norm_type)
pose_coords.append(torch.from_numpy(pose_coord).unsqueeze(0))
pose_scores.append(torch.from_numpy(pose_score).unsqueeze(0))
preds_img = torch.cat(pose_coords)
preds_scores = torch.cat(pose_scores)
if not self.opt.pose_track:
boxes, scores, ids, preds_img, preds_scores, pick_ids = \
pose_nms(boxes, scores, ids, preds_img, preds_scores, self.opt.min_box_area, use_heatmap_loss=self.use_heatmap_loss)
_result = []
for k in range(len(scores)):
_result.append(
{
'keypoints':preds_img[k],
'kp_score':preds_scores[k],
'proposal_score': torch.mean(preds_scores[k]) + scores[k] + 1.25 * max(preds_scores[k]),
'idx':ids[k],
'box':[boxes[k][0], boxes[k][1], boxes[k][2]-boxes[k][0],boxes[k][3]-boxes[k][1]]
}
)
result = {
'imgname': im_name,
'result': _result
}
if self.opt.pose_flow:
poseflow_result = self.pose_flow_wrapper.step(orig_img, result)
for i in range(len(poseflow_result)):
result['result'][i]['idx'] = poseflow_result[i]['idx']
final_result.append(result)
if self.opt.save_img or self.save_video or self.opt.vis:
if hm_data.size()[1] == 49:
from alphapose.utils.vis import vis_frame_dense as vis_frame
elif self.opt.vis_fast:
from alphapose.utils.vis import vis_frame_fast as vis_frame
else:
from alphapose.utils.vis import vis_frame
img = vis_frame(orig_img, result, self.opt, self.vis_thres)
self.write_image(img, im_name, stream=stream if self.save_video else None)
def write_image(self, img, im_name, stream=None):
if self.opt.vis:
# 修复:确保 cv2.imshow 接收 BGR 格式
if img is not None and len(img.shape) == 3 and img.shape[-1] == 3:
img_display = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
else:
img_display = img
cv2.imshow("AlphaPose Demo", img_display)
cv2.waitKey(30)
if self.opt.save_img:
# 修复:保存时也转换格式
if img is not None and len(img.shape) == 3 and img.shape[-1] == 3:
img_save = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
else:
img_save = img
cv2.imwrite(os.path.join(self.opt.outputpath, 'vis', im_name), img_save)
if self.save_video:
# 修复:视频写入也转换格式
if img is not None and len(img.shape) == 3 and img.shape[-1] == 3:
img_video = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
else:
img_video = img
stream.write(img_video)
def wait_and_put(self, queue, item):
queue.put(item)
def wait_and_get(self, queue):
return queue.get()
def save(self, boxes, scores, ids, hm_data, cropped_boxes, orig_img, im_name):
# save next frame in the queue
self.wait_and_put(self.result_queue, (boxes, scores, ids, hm_data, cropped_boxes, orig_img, im_name))
def running(self):
# indicate that the thread is still running
return not self.result_queue.empty()
def count(self):
# indicate the remaining images
return self.result_queue.qsize()
def stop(self):
# indicate that the thread should be stopped
self.save(None, None, None, None, None, None, None)
self.result_worker.join()
def terminate(self):
# directly terminate
self.result_worker.terminate()
def clear_queues(self):
self.clear(self.result_queue)
def clear(self, queue):
while not queue.empty():
queue.get()
def results(self):
# return final result
print(self.final_result)
return self.final_result
def recognize_video_ext(self, ext=''):
if ext == 'mp4':
return cv2.VideoWriter_fourcc(*'mp4v'), '.' + ext
elif ext == 'avi':
return cv2.VideoWriter_fourcc(*'XVID'), '.' + ext
elif ext == 'mov':
return cv2.VideoWriter_fourcc(*'XVID'), '.' + ext
else:
print("Unknow video format {}, will use .mp4 instead of it".format(ext))
return cv2.VideoWriter_fourcc(*'mp4v'), '.mp4'

可能遇到的问题:其他进程占用摄像头
ps aux | grep demo_inference 之前运行demo_inference之后crtlC,进程仍在占用摄像头,kill -9即可
查看运行结果

问题:没有输出关键点坐标的json文件 可能和每次ctrl c 中断程序有关写入进程被立即杀死 数据没有被保存到文件
解决:增加单线程参数 --sp 在收到 Ctrl+C 后等待写入完成


json文件数据格式:
{
"image_id": 图像ID,
"category_id": 类别ID (通常是1表示人),
"keypoints": [x1,y1,v1, x2,y2,v2, ..., x17,y17,v17], 17个关键点
"score": 检测置信度,
"box": [x,y,w,h], 检测框 [左上角x,左上角y,宽度,高度]
"idx": 索引
}
2617



被折叠的 条评论
为什么被折叠?



