RGB to 3D Action Tracking: AlphaPose + HybrIK(1)

Linux 下基于FFmpeg与OpenCV实现设备视频接收、解码与实时渲染全流程实战 本文基于FFmpeg+OpenCV构建低延迟、可扩展的Linux视频处理管线,涵盖从RTSP/UDP流接收、硬软解码、实时渲染到抓拍录像的全流程。通过生产者-消费者模型解耦各模块,采用有界队列控制背压,结合VAAPI硬件加速与帧队列优化,有效解决高码流下的内存暴涨、延迟累积与界面卡顿问题。关键实践包括:断流自动重连、关键帧等待、时间戳精准换算、双缓冲渲染及资源复用,最终实现4K级稳定实时视频处理,具备完全自主可控与低成本优势。 阅读详情

任务流程: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": 索引

}

【OpenCV】第二十五章: opencv实战案例:图像查找、图像拼接 opencv实战案例:图像查找、图像拼接 阅读详情

相关推荐

iTerm2+oh-my-zsh最全配置

iTerm2+oh-my-zsh最全配置安装前先看效果图一.安装[iTem2](https://iterm2.com/)二.安装[oh-my-zsh](https://ohmyz.sh/)三.安装[Powerline](https://powerline.readthedocs.io/en/latest/installation.html)四.安装 [Meslo](https://github.com/powerline/fonts) 字体库五.安装agnoster主题六.安装语法高亮七.安装代码补全插件八

xinximo的博客 2617

RGB to 3D Action Tracking: AlphaPose + HybrIK(2)

任务:将视频帧与 AlphaPose 的 2D 检测结果进行线性映射,调用 HybrIK 模型推理出每帧每个人的 24 个 SMPL 关节的 3D 坐标(单位:米),并保存为 .npz 文件供后续使用。问题:现在运行 scripts/demo_inference.py之后,输出文件只有json格式的关键点坐标,没有录制成视频(后续Hybrik要使用),也没有每一帧的照片。输出文件:examples/res_final/hybrik_3d_keypoints_linear_mapped.npz。

2302_77159195的博客 249

光电系统光轴校准与偏差控制实战指南

光轴作为光电系统的空间基准坐标系,直接影响多光谱传感器的协同工作精度。在包含可见光、红外与激光测距的复合系统中,光轴偏差会导致目标识别误差与打击精度下降。通过机械基准建立、光学通道粗调和多光谱协同校准等工厂级标定流程,结合千米靶标法、星点校准法等野战应急方案,可有效控制光轴偏差。典型应用场景中,温度补偿与振动抑制技术能维持光轴稳定性,如某舰载系统通过500Hz高频视觉伺服实现0.3mrad振动补偿。掌握这些光轴标定与保持策略,对提升光电系统在侦察、测距等场景的实战性能具有关键价值。

weixin_36149538的博客 289

RGB to 3D Action Tracking: Hyrbik+mjlab(1)

下一步工作是借助./mjlab/asset_zoo/robots/unitree_g1/xmls/g1.xml和mjlab/tasks/tracking/config/g1/env_cfgs.py 编写逆运动学转换脚本。pose_output.pred_xyz_jts_17: 17 个 COCO 关键点的 3D 坐标 (17, 3)pred_xyz_29:29个关键点的 3D 坐标。pose_output.pred_xyz_jts_29: 29 个扩展关节点的 3D 坐标 (29, 3)

2302_77159195的博客 261

从电流流向到电路设计:深入解析PMOS与NMOS的符号与导通逻辑

本文深入解析PMOS与NMOS的符号与导通逻辑,从电流流向到电路设计,详细介绍了MOS管的工作原理、符号图解与记忆技巧,以及在数字电路和模拟电路中的工程实践。通过实际案例和黄金法则,帮助读者掌握PMOS与NMOS在电路设计中的关键应用,提升设计效率和可靠性。

weixin_30800807的博客 336

<Verilog实现除法器> Verilog实现牛顿-拉夫逊(Newton-Raphson)除法器

阿斯顿阿斯顿啊啊是打发士大夫

IC跳跳鱼的博客 3593

二、opencv_ai视觉实战-几何变换

本文系统梳理图像几何变换的六大核心操作:缩放、平移、旋转、仿射、透视及图像金字塔,结合OpenCV API与数学矩阵表达,明确各变换的参数含义、插值策略与矩阵实现方式。重点解析cv.resize、cv.warpAffine、cv.getRotationMatrix2D及cv.getAffineTransform等函数的使用逻辑,辅以齐次坐标与坐标系转换原理,实现从理论到代码的一体化对齐,为视觉预处理中的形变修图提供清晰技术路径。

weixin_36323170的博客 211

STM32入门教程:WiFi通信

STM32是一款强大的嵌入式系统开发平台,可以用于开发各种应用程序,包括WiFi通信。在本教程中,我们将介绍如何使用STM32开发板和WiFi模块进行无线通信。以下是一个详细的代码案例,涵盖了WiFi通信的基本概念和实现。

qq_67153941的博客 1351

四、opencv_ai视觉实战-预处理之平滑度调整

本文系统对比了均值、高斯、中值、双边四种图像平滑滤波方法,结合噪声类型(椒盐、高斯)给出选型指南:椒盐噪声首选中值滤波,高斯噪声推荐高斯或双边滤波,快速抹平用均值,保边磨皮则用双边。通过OpenCV实现示例,强调“先分噪声、再选滤波”的预处理原则,兼顾去噪效果与边缘保留,提升后续视觉任务稳定性。

weixin_36323170的博客 236

AirSim安装和地图加载

详细教程如何安装AirSim并加载地图

fegxg的博客 3049

Xilinx FPGA平台DDR3设计保姆式教程(3)MIG IP核使用教程及DDR读写时序

干货来了,用DDR搬砖,只需要会用IP就好,Xilinx官方YYDS! ----------------------------------------------------------------------------------------------------------------- 汇总篇: Xilinx平台DDR3设计保姆式教程(汇总篇)——看这一篇就够了 ----------------------------------------------------------...

数字IC/FPGA杂货铺,找一找,或许有你想要的~ 2万+

图像处理OpenCV--黑马笔记

学习目标了解OpenCV是什么能够独立安装OpenCVOpenCV是一款由Intel公司俄罗斯团队发起并参与和维护的一个计算机视觉处理开源软件库,支持与计算机视觉和机器学习相关的众多算法,并且正在日益扩展。OpenCV的优势:编程语言OpenCV基于C++实现,同时提供python, Ruby, Matlab等语言的接口。OpenCV-Python是OpenCV的Python API,结合了OpenCV C++ API和Python语言的最佳特性。跨平台。

2401_87118211的博客 248

【RH850/U2A】:HSM与APP通信(中断方式)

HSM与APP通信(中断方式)

2004

八、opencv_ai视觉实战-特征提取之Harris & Shi-Tomasi 检测

本文详解Harris与Shi-Tomasi角点检测原理:Harris通过结构矩阵的响应值R(避开通过特征值计算)判断角点,对旋转和光照有一定鲁棒性,但需手动调参且无间距约束;Shi-Tomasi则直接以最小特征值min(λ₁, λ₂)为响应,更稳定,且支持最大角点数与最小间距限制,更适合跟踪任务。两者均需输入float32灰度图,以保证精度。

weixin_36323170的博客 365

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

OpenCV 图像处理

RGB 和 BGR 是彩色图像的两种通道排列方式。RGB:通道顺序为红、绿、蓝。BGR:通道顺序为蓝、绿、红。# RGB# BGR如果将 BGR 图像错误地当作 RGB 图像输入模型,就可能造成颜色信息错误,影响模型识别效果。HWC 和 CHW 描述的是图像数据在内存中的维度排列顺序。H:Height,高度。W:Width,宽度。C:Channels,通道数。OpenCV 读取的彩色图像通常采用 HWC 格式。表示高度为 480、宽度为 640、通道数为 3。

zengjiajun2006的博客 379

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

商品实拍图修图前先分拣:用 OpenCV 批量判断糊、暗、过曝,只看拉普拉斯方差会把噪点图判成清楚(Python 实测)

商品实拍图交给 AI 修图前,先分拣“该修”和“该重拍”。实测只看整图拉普拉斯方差会把暗光噪点图判成清楚、把过曝图判成糊;按亮度/高光→噪声→清晰度顺序判断,14 张样本全部分对,140 张约 9.6 秒。

weixin_49155889的博客 343

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

七、opencv_ai视觉实战-模版匹配与霍夫变换

模版匹配:滑窗比相似度;适合固定尺度、固定角度;灰度 +minMaxLoc;不支持缩放 / 旋转 / 视角变化霍夫线HoughLines给(ρ, θ)无限直线;给有限线段 +maxLineGap霍夫圆:霍夫梯度法两阶段(圆心 → 半径);半径范围与minDist是控假圆的关键二者都是传统算法,在光照稳定、形变可控的工业场景落地简单。

weixin_36323170的博客 294

六、opencv_ai视觉实战-边缘检测

本文系统梳理边缘检测的两大路线:一阶导数(如Sobel)与二阶导数(如Laplacian)。重点解析Sobel需用CV_64F避免负值丢失,配合convertScaleAbs可视化;Canny通过高斯滤波、梯度计算、非极大值抑制及双阈值筛选,实现强弱边缘精准提取。工业推荐首选Canny,兼顾抗噪性与边缘连续性,参数可依光照材质调优。

weixin_36323170的博客 556

移动端按键精灵自动化脚本开发里的图像识别:为什么 OpenCV 找图正在取代 FindPic

本文深入解析移动端自动化中跨设备、跨分辨率找图的最优方案——OpenCV多尺度模板匹配。对比FindPic像素级比对与OpenCV特征级匹配的本质差异,阐明其适用场景:前者快但容错低,后者抗干扰强但耗性能。详解按键精灵安卓与iOS双端实现差异,强调引擎版本与参数支持限制。指出优化关键在minScale、maxScale、stepCount三参数调优,并明确三种不适用场景:静态固定界面、高频轮询、目标不固定。最终提出选型核心逻辑:目标“变不变”决定技术路径——不变快选FindPic,可变多样选OpenCV,无

ii_best的博客 352

WorkBuddy 制作AI武侠短片实战:无 ffmpeg 的 OpenCV 拼接实战

本文复盘用600积分在WorkBuddy平台生成34.2秒竖屏武侠短片《雪夜剑归》的全流程:通过8张关键帧锚定角色视觉一致性,采用图生视频降低返工成本;在无ffmpeg环境下,仅用OpenCV与Pillow实现多段视频拼接与中文字卡绘制;强调统一输出目录、拒绝重复重试失败任务等真实决策。核心在于“先图后视、参数一致、工具链极简”,构建可复用的低成本AI短片流水线。

七夜zippoe的博客 546

一、opencv_ai视觉实战-环境搭建和图像处理基础

本文系统讲解了Python+OpenCV图像处理的入门基础,涵盖环境搭建(Python、VS Code、OpenCV及NumPy、Matplotlib安装)、图像读写与显示、BGR颜色空间认知、像素操作、颜色空间转换(BGR→GRAY/HSV/RGB)以及图形绘制(矩形、圆、线、文字等)。重点强调了OpenCV中BGR格式与坐标系(先y后x)的常见踩坑点,并通过实例实现图像算术运算与可视化闭环,助力快速掌握核心操作。

weixin_36323170的博客 525

手绘扫描稿怎么转可调线宽 SVG:OpenCV 去阴影前处理、骨架提取与在线描边实操

把手机拍摄或平板扫描的手绘草图转换为工程上可动态调线宽的中心线 SVG(Centerline Stroke SVG),主要有四条技术路径:离线零成本批处理干净勾线稿,推荐;需要严苛对齐栅格的 UI 图标或机械简图,适合垫入或用贝塞尔钢笔重构;需要保留粗笔刷封闭墨迹边界的书法或贴纸稿,可用或;如果希望跳过二值化调参与毛刺清理,直接把带轻微阴影或铅笔痕的草图转成带属性的真实描边 SVG(或供绘图仪与激光划线机单次走刀的无填充纯线条),可以使用转换并导出。

2401_86439035的博客 216

OpenCV特征匹配、相机标定与视频处理实战

真正掌握 OpenCV,需要能够解释算法原理、写出基础代码、分析处理结果,并且知道算法在什么情况下可能失效。

dongziwen1的博客 373

【Linux】RK3568-OpenCV+YOLO(十)

1

Longrun的博客 257

高精度表格识别技术通过深度学习与计算机视觉,解决纸质表格识别难题,实现从图片还原结构清晰、可查可算的真表格

本文系统解析基于深度学习的高精度表格识别技术,突破传统OCR“文字对、表格废”的瓶颈。通过图像预处理、端到端结构重建与语义校验,实现无线框、跨页、复杂表头等极端场景下的精准还原,输出可计算、可入库的结构化数据。技术具备零模板泛化、高鲁棒性与易集成优势,已在金融、医疗、政务等领域实现财务报表、化验单、业务单据的自动化处理,推动纸质表格向可流动的数据资产跃迁。

智能图像识别 389

红外海鸟目标检测数据集深度学习 目标检测 红外图像 海鸟监测 野生动物保护 YOLO格式 数据集发布9071期

红外海鸟目标检测数据集深度学习 目标检测 红外图像 海鸟监测 野生动物保护 YOLO格式 数据集发布9071期

qq_2529413168的博客 179
下一篇: RGB to 3D Action Tracking: AlphaPose + HybrIK(2)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值