先安装Kinect SDK;

如上图;需要安装2个安装文件;sdk,toolkit;然后可以获得示例代码;

运行程序需要安装Kinect传感器;

主文件代码;

//------------------------------------------------------------------------------
// <copyright file="ColorBasics.cpp" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------#include "stdafx.h"
#include <strsafe.h>
#include "ColorBasics.h"
#include "resource.h"/// <summary>
/// Entry point for the application
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="hPrevInstance">always 0</param>
/// <param name="lpCmdLine">command line arguments</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
/// <returns>status</returns>
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{CColorBasics application;application.Run(hInstance, nCmdShow);
}/// <summary>
/// Constructor
/// </summary>
CColorBasics::CColorBasics() :m_pD2DFactory(NULL),m_pDrawColor(NULL),m_hNextColorFrameEvent(INVALID_HANDLE_VALUE),m_pColorStreamHandle(INVALID_HANDLE_VALUE),m_bSaveScreenshot(false),m_pNuiSensor(NULL)
{
}/// <summary>
/// Destructor
/// </summary>
CColorBasics::~CColorBasics()
{if (m_pNuiSensor){m_pNuiSensor->NuiShutdown();}if (m_hNextColorFrameEvent != INVALID_HANDLE_VALUE){CloseHandle(m_hNextColorFrameEvent);}// clean up Direct2D rendererdelete m_pDrawColor;m_pDrawColor = NULL;// clean up Direct2DSafeRelease(m_pD2DFactory);SafeRelease(m_pNuiSensor);
}/// <summary>
/// Creates the main window and begins processing
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
int CColorBasics::Run(HINSTANCE hInstance, int nCmdShow)
{MSG       msg = {0};WNDCLASS  wc;// Dialog custom window classZeroMemory(&wc, sizeof(wc));wc.style         = CS_HREDRAW | CS_VREDRAW;wc.cbWndExtra    = DLGWINDOWEXTRA;wc.hInstance     = hInstance;wc.hCursor       = LoadCursorW(NULL, IDC_ARROW);wc.hIcon         = LoadIconW(hInstance, MAKEINTRESOURCE(IDI_APP));wc.lpfnWndProc   = DefDlgProcW;wc.lpszClassName = L"ColorBasicsAppDlgWndClass";if (!RegisterClassW(&wc)){return 0;}// Create main application windowHWND hWndApp = CreateDialogParamW(hInstance,MAKEINTRESOURCE(IDD_APP),NULL,(DLGPROC)CColorBasics::MessageRouter, reinterpret_cast<LPARAM>(this));// Show windowShowWindow(hWndApp, nCmdShow);const int eventCount = 1;HANDLE hEvents[eventCount];// Main message loopwhile (WM_QUIT != msg.message){hEvents[0] = m_hNextColorFrameEvent;// Check to see if we have either a message (by passing in QS_ALLINPUT)// Or a Kinect event (hEvents)// Update() will check for Kinect events individually, in case more than one are signalledDWORD dwEvent = MsgWaitForMultipleObjects(eventCount, hEvents, FALSE, INFINITE, QS_ALLINPUT);// Check if this is an event we're waiting on and not a timeout or messageif (WAIT_OBJECT_0 == dwEvent){Update();}if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)){// If a dialog message will be taken care of by the dialog procif ((hWndApp != NULL) && IsDialogMessageW(hWndApp, &msg)){continue;}TranslateMessage(&msg);DispatchMessageW(&msg);}}return static_cast<int>(msg.wParam);
}/// <summary>
/// Main processing function
/// </summary>
void CColorBasics::Update()
{if (NULL == m_pNuiSensor){return;}if ( WAIT_OBJECT_0 == WaitForSingleObject(m_hNextColorFrameEvent, 0) ){ProcessColor();}
}/// <summary>
/// Handles window messages, passes most to the class instance to handle
/// </summary>
/// <param name="hWnd">window message is for</param>
/// <param name="uMsg">message</param>
/// <param name="wParam">message data</param>
/// <param name="lParam">additional message data</param>
/// <returns>result of message processing</returns>
LRESULT CALLBACK CColorBasics::MessageRouter(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{CColorBasics* pThis = NULL;if (WM_INITDIALOG == uMsg){pThis = reinterpret_cast<CColorBasics*>(lParam);SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis));}else{pThis = reinterpret_cast<CColorBasics*>(::GetWindowLongPtr(hWnd, GWLP_USERDATA));}if (pThis){return pThis->DlgProc(hWnd, uMsg, wParam, lParam);}return 0;
}/// <summary>
/// Handle windows messages for the class instance
/// </summary>
/// <param name="hWnd">window message is for</param>
/// <param name="uMsg">message</param>
/// <param name="wParam">message data</param>
/// <param name="lParam">additional message data</param>
/// <returns>result of message processing</returns>
LRESULT CALLBACK CColorBasics::DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{switch (message){case WM_INITDIALOG:{// Bind application window handlem_hWnd = hWnd;// Init Direct2DD2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);// Create and initialize a new Direct2D image renderer (take a look at ImageRenderer.h)// We'll use this to draw the data we receive from the Kinect to the screenm_pDrawColor = new ImageRenderer();HRESULT hr = m_pDrawColor->Initialize(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), m_pD2DFactory, cColorWidth, cColorHeight, cColorWidth * sizeof(long));if (FAILED(hr)){SetStatusMessage(L"Failed to initialize the Direct2D draw device.");}// Look for a connected Kinect, and create it if foundCreateFirstConnected();}break;// If the titlebar X is clicked, destroy appcase WM_CLOSE:DestroyWindow(hWnd);break;case WM_DESTROY:// Quit the main message pumpPostQuitMessage(0);break;// Handle button presscase WM_COMMAND:// If it was for the screenshot control and a button clicked event, save a screenshot next frame if (IDC_BUTTON_SCREENSHOT == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam)){m_bSaveScreenshot = true;}break;}return FALSE;
}/// <summary>
/// Create the first connected Kinect found
/// </summary>
/// <returns>indicates success or failure</returns>
HRESULT CColorBasics::CreateFirstConnected()
{INuiSensor * pNuiSensor;HRESULT hr;int iSensorCount = 0;hr = NuiGetSensorCount(&iSensorCount);if (FAILED(hr)){return hr;}// Look at each Kinect sensorfor (int i = 0; i < iSensorCount; ++i){// Create the sensor so we can check status, if we can't create it, move on to the nexthr = NuiCreateSensorByIndex(i, &pNuiSensor);if (FAILED(hr)){continue;}// Get the status of the sensor, and if connected, then we can initialize ithr = pNuiSensor->NuiStatus();if (S_OK == hr){m_pNuiSensor = pNuiSensor;break;}// This sensor wasn't OK, so release it since we're not using itpNuiSensor->Release();}if (NULL != m_pNuiSensor){// Initialize the Kinect and specify that we'll be using colorhr = m_pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_COLOR); if (SUCCEEDED(hr)){// Create an event that will be signaled when color data is availablem_hNextColorFrameEvent = CreateEvent(NULL, TRUE, FALSE, NULL);// Open a color image stream to receive color frameshr = m_pNuiSensor->NuiImageStreamOpen(NUI_IMAGE_TYPE_COLOR,NUI_IMAGE_RESOLUTION_640x480,0,2,m_hNextColorFrameEvent,&m_pColorStreamHandle);}}if (NULL == m_pNuiSensor || FAILED(hr)){SetStatusMessage(L"No ready Kinect found!");return E_FAIL;}return hr;
}/// <summary>
/// Get the name of the file where screenshot will be stored.
/// </summary>
/// <param name="screenshotName">
/// [out] String buffer that will receive screenshot file name.
/// </param>
/// <param name="screenshotNameSize">
/// [in] Number of characters in screenshotName string buffer.
/// </param>
/// <returns>
/// S_OK on success, otherwise failure code.
/// </returns>
HRESULT GetScreenshotFileName(wchar_t *screenshotName, UINT screenshotNameSize)
{wchar_t *knownPath = NULL;HRESULT hr = SHGetKnownFolderPath(FOLDERID_Pictures, 0, NULL, &knownPath);if (SUCCEEDED(hr)){// Get the timewchar_t timeString[MAX_PATH];GetTimeFormatEx(NULL, 0, NULL, L"hh'-'mm'-'ss", timeString, _countof(timeString));// File name will be KinectSnapshot-HH-MM-SS.wavStringCchPrintfW(screenshotName, screenshotNameSize, L"%s\\KinectSnapshot-%s.bmp", knownPath, timeString);}CoTaskMemFree(knownPath);return hr;
}/// <summary>
/// Handle new color data
/// </summary>
/// <returns>indicates success or failure</returns>
void CColorBasics::ProcessColor()
{HRESULT hr;NUI_IMAGE_FRAME imageFrame;// Attempt to get the color framehr = m_pNuiSensor->NuiImageStreamGetNextFrame(m_pColorStreamHandle, 0, &imageFrame);if (FAILED(hr)){return;}INuiFrameTexture * pTexture = imageFrame.pFrameTexture;NUI_LOCKED_RECT LockedRect;// Lock the frame data so the Kinect knows not to modify it while we're reading itpTexture->LockRect(0, &LockedRect, NULL, 0);// Make sure we've received valid dataif (LockedRect.Pitch != 0){// Draw the data with Direct2Dm_pDrawColor->Draw(static_cast<BYTE *>(LockedRect.pBits), LockedRect.size);// If the user pressed the screenshot button, save a screenshotif (m_bSaveScreenshot){WCHAR statusMessage[cStatusMessageMaxLen];// Retrieve the path to My PhotosWCHAR screenshotPath[MAX_PATH];GetScreenshotFileName(screenshotPath, _countof(screenshotPath));// Write out the bitmap to diskhr = SaveBitmapToFile(static_cast<BYTE *>(LockedRect.pBits), cColorWidth, cColorHeight, 32, screenshotPath);if (SUCCEEDED(hr)){// Set the status bar to show where the screenshot was savedStringCchPrintf( statusMessage, cStatusMessageMaxLen, L"Screenshot saved to %s", screenshotPath);}else{StringCchPrintf( statusMessage, cStatusMessageMaxLen, L"Failed to write screenshot to %s", screenshotPath);}SetStatusMessage(statusMessage);// toggle off so we don't save a screenshot again next framem_bSaveScreenshot = false;}}// We're done with the texture so unlock itpTexture->UnlockRect(0);// Release the framem_pNuiSensor->NuiImageStreamReleaseFrame(m_pColorStreamHandle, &imageFrame);
}/// <summary>
/// Set the status bar message
/// </summary>
/// <param name="szMessage">message to display</param>
void CColorBasics::SetStatusMessage(WCHAR * szMessage)
{SendDlgItemMessageW(m_hWnd, IDC_STATUS, WM_SETTEXT, 0, (LPARAM)szMessage);
}/// <summary>
/// Save passed in image data to disk as a bitmap
/// </summary>
/// <param name="pBitmapBits">image data to save</param>
/// <param name="lWidth">width (in pixels) of input image data</param>
/// <param name="lHeight">height (in pixels) of input image data</param>
/// <param name="wBitsPerPixel">bits per pixel of image data</param>
/// <param name="lpszFilePath">full file path to output bitmap to</param>
/// <returns>indicates success or failure</returns>
HRESULT CColorBasics::SaveBitmapToFile(BYTE* pBitmapBits, LONG lWidth, LONG lHeight, WORD wBitsPerPixel, LPCWSTR lpszFilePath)
{DWORD dwByteCount = lWidth * lHeight * (wBitsPerPixel / 8);BITMAPINFOHEADER bmpInfoHeader = {0};bmpInfoHeader.biSize        = sizeof(BITMAPINFOHEADER);  // Size of the headerbmpInfoHeader.biBitCount    = wBitsPerPixel;             // Bit countbmpInfoHeader.biCompression = BI_RGB;                    // Standard RGB, no compressionbmpInfoHeader.biWidth       = lWidth;                    // Width in pixelsbmpInfoHeader.biHeight      = -lHeight;                  // Height in pixels, negative indicates it's stored right-side-upbmpInfoHeader.biPlanes      = 1;                         // DefaultbmpInfoHeader.biSizeImage   = dwByteCount;               // Image size in bytesBITMAPFILEHEADER bfh = {0};bfh.bfType    = 0x4D42;                                           // 'M''B', indicates bitmapbfh.bfOffBits = bmpInfoHeader.biSize + sizeof(BITMAPFILEHEADER);  // Offset to the start of pixel databfh.bfSize    = bfh.bfOffBits + bmpInfoHeader.biSizeImage;        // Size of image + headers// Create the file on disk to write toHANDLE hFile = CreateFileW(lpszFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);// Return if error opening fileif (NULL == hFile) {return E_ACCESSDENIED;}DWORD dwBytesWritten = 0;// Write the bitmap file headerif ( !WriteFile(hFile, &bfh, sizeof(bfh), &dwBytesWritten, NULL) ){CloseHandle(hFile);return E_FAIL;}// Write the bitmap info headerif ( !WriteFile(hFile, &bmpInfoHeader, sizeof(bmpInfoHeader), &dwBytesWritten, NULL) ){CloseHandle(hFile);return E_FAIL;}// Write the RGB Dataif ( !WriteFile(hFile, pBitmapBits, bmpInfoHeader.biSizeImage, &dwBytesWritten, NULL) ){CloseHandle(hFile);return E_FAIL;}    // Close the fileCloseHandle(hFile);return S_OK;
}

首先看一下,包含stdafx.h,Resource.h;这是一个VC++项目;但不是MFC项目;
程序是以wWinMain入口;

Run函数里面主要是注册窗口类;创建窗口,消息循环;
CreateDialogParam函数,根据对话框模板资源创建一个无模式的对话框。在显示对话框之前,函数把一个应用程序定义的值作为WM_INITDIALOG消息IParam参数传到对话框过程应用程序可用此值来初始化对话框控制。

在stdafx.h里,有
#include <d2d1.h>
#pragma comment ( lib, "d2d1.lib" )
也就是此程序将使用微软DirectX 2D;

在初始化对话框(WM_INITDIALOG)的时候,执行
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);
创建D2D工厂;

在CreateFirstConnected函数里主要是获取连接了几个kinect传感器(NuiGetSensorCount);
然后调用NuiCreateSensorByIndex创建传感器对象;

主要的功能是在ProcessColor函数里;
NUI_IMAGE_FRAME imageFrame是一个图像帧;
获取了图像帧以后调用D2D的功能来在窗口上进行绘制;
然后保存屏幕截图到文件;

这是kinect的基本C++示例;

微软Kinect 1.7 附带ColorBasics-D2D示例程序基本解析相关推荐

  1. 通过Jexus 部署 dotnetcore版本MusicStore 示例程序

    ASPNET Music Store application 是一个展示最新的.NET 平台(包括.NET Core/Mono等)上使用MVC 和Entity Framework的示例程序,本文将展示 ...

  2. 示例程序:关于双目视觉,标定,立体匹配(视差算法),点云,双目三维重建的原理以及代码

    Evision双目视觉 关于双目视觉的一些总结 说明 前言 相机模型 标定 视差算法:立体匹配 测量,三维重建 示例程序 参考文献 关于双目视觉的一些总结 说明 如果读者对于本文或者Evision程序 ...

  3. Caysn打印机IOS平台打印开发包、接口说明文档及示例程序_20170717

    打印机开发包,接口说明文档,打印示例程序下载地址:Caysn打印机IOS开发包.接口说明文档.打印示例程序_20170717 Framework版本要求:IOS8  Framework架构:armv7 ...

  4. Caysn打印机IOS平台打印开发包及示例程序_20170610

    打印机开发包,接口说明文档,打印示例程序:Caysn打印机IOS开发包.文档.示例程序_20170610 系统要求:IOS8 CPU架构:armv7 armv7s arm64 说明文档:(压缩包里有附 ...

  5. MindSpore部署图像分割示例程序

    MindSpore部署图像分割示例程序 本端侧图像分割Android示例程序使用Java实现,Java层主要通过Android Camera 2 API实现摄像头获取图像帧,进行相应的图像处理,之后调 ...

  6. BizTalk 2006 简单入门示例程序(附源项目文件下载)

    BizTalk 2006 简单入门示例程序(附源项目文件下载) 为初学BizTalk Server 2006的开发人员,提供一个简单入门的示例程序,包括一个Receive Port.Send Port ...

  7. 基于Struts2.3.x+Spring3.2.x+Hibernate4.2.x+EasyUI1.3.4+Maven架构的示例程序

    基于Struts2.3.x+Spring3.2.x+Hibernate4.2.x+EasyUI1.3.4+Maven架构的示例程序 不知道为什么,保存的时候显示有一个连接为违禁内容,可能是----. ...

  8. 如何编译ReactNative示例程序Examples

    通过示例程序可以看到一些基本组件的使用,对于学习ReactNative是很有帮助的. 编译示例程序需要将整个项目导入到androidStudio中,androidStudio导入项目时选择react- ...

  9. ASP.NET AJAX示例程序:实现IDragSource和IDropTarget接口将商品拖放至购物车中

    本文来自<ASP.NET AJAX程序设计--第II卷:客户端Microsoft AJAX Library相关>第9章第3节. 9.3 示例程序:实现IDragSource和IDropTa ...

最新文章

  1. 个人销售建筑服务器,建筑个人云服务器
  2. iframe解决跨域ajax请求的方法
  3. 3D打印神经电极有助于将大脑连接到电脑
  4. Coursera课程Python for everyone:chapter9
  5. apache lucene_全文搜索Apache Lucene简介
  6. Azure 和 Linux
  7. java类的成员变量和局部变量的区别
  8. NTL密码算法开源库拓展——SM2算法
  9. linux没法上网,LINUX没法上网?
  10. matlab中geoshow函数的使用/属性设置
  11. 安卓miracast花屏_EMUI 10.1 Cast+无线投屏 让你开启“0”花屏新体验
  12. 多协议充电桩平台系统小程序方案
  13. “达内”JAVA技术培训有感(一)
  14. ps改变叶子中的图片
  15. webclient是什么意思_Web 是什么意思?
  16. 基于.Net TcpListener 实现 WebSocketServer 通讯
  17. python中常用的转义字符
  18. 人社练兵比武怎样挣积分 python 源码在线答题源码
  19. 使用F11一键还原的几点心得
  20. AutoKeras代码

热门文章

  1. 电脑的cpu是怎么制作的?
  2. JavaScript中判断为整数的多种方式
  3. Python3 多线程问题:ModuleNotFoundError: No module named 'thread',原因及解决办法。
  4. CTFshow 信息收集 web16
  5. delphi项目文件说明
  6. inline函数使用容易导致出错的问题
  7. poj1061-青蛙的约会
  8. 第7周实践项目2.2 求解报数问题
  9. 判断N!中二进制中最低位1的位置
  10. Bear and Finding Criminals (模拟)