Opencv+Kinect2.0获取BodyIndex图像

直接上代码吧。

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>
#include <Kinect.h> 
#include<Kinect.Face.h>
#include <Kinect.VisualGestureBuilder.h>
#pragma comment ( lib, "kinect20.lib" ) 
#pragma comment ( lib, "Kinect20.face.lib" ) 
#pragma comment ( lib, "Kinect20.VisualGestureBuilder.lib" ) 

using namespace cv;
using namespace std;

template<class Interface>
inline void SafeRelease(Interface *& pInterfaceToRelease)
{
    if (pInterfaceToRelease != NULL)
    {
        pInterfaceToRelease->Release();
        pInterfaceToRelease = NULL;
    }
}

int main()
{
    HRESULT hResult;
    setUseOptimized(true);

    IKinectSensor *kinect;
    GetDefaultKinectSensor(&kinect);
    kinect->Open();

    IBodyIndexFrameSource *bodyindexframesource;
    kinect->get_BodyIndexFrameSource(&bodyindexframesource);
    IBodyIndexFrameReader *bodyindexframereader;
    bodyindexframesource->OpenReader(&bodyindexframereader);

    IFrameDescription *fd;
    bodyindexframesource->get_FrameDescription(&fd);
    int width = 0;
    int height = 0;
    fd->get_Width(&width); 
    fd->get_Height(&height); 

    Mat img(height, width, CV_8UC3);

    while(1)
    {
        IBodyIndexFrame*bodyindexframe = nullptr;
        hResult = bodyindexframereader->AcquireLatestFrame(&bodyindexframe);
        if (SUCCEEDED(hResult))
        {
            unsigned int buffersize = 0;
            unsigned char* buffer = nullptr;
            hResult = bodyindexframe->AccessUnderlyingBuffer(&buffersize, &buffer);
            if (SUCCEEDED(hResult))
            {
                for (int x = 0; x < height; x++)
                {
                    for (int y = 0; y < width; y++)

                    {
                        unsigned int index = x * width + y;
                        if (buffer[index] != 255)
                        {
                            img.at<Vec3b>(x, y) = Vec3b(0,0,255);
                        }
                        else 
                        {
                            img.at<Vec3b>(x, y) = Vec3b(0, 0, 0);
                        }
                    }
                }
            }
        }
        SafeRelease(bodyindexframe);

        imshow("BodyIndex", img);

        if (waitKey(34) == VK_ESCAPE) 
            break;
    }
    SafeRelease(bodyindexframesource);
    SafeRelease(bodyindexframereader);
    SafeRelease(fd);
    if (kinect) 
    {
        kinect->Close();
    }
    SafeRelease(kinect);
    destroyAllWindows();

    return 0;
}

运行图:
Opencv+Kinect2.0获取BodyIndex图像_第1张图片

你可能感兴趣的:(opencv,kinect)