OpenCV 2.3.1でKinectを使ってみた

インストール

CMakeするときに、WITH_OPENNIを有効にする必要があります。

手前にある物体のみ表示するサンプル

// opencvkinecttest.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//

#include "stdafx.h"

#include <iostream>

#include <opencv2/opencv.hpp>

int _tmain(int argc, _TCHAR* argv[])
{
  try {
    char* name = "OpenCV with OpenNI Test";
    cv::namedWindow( name );
    cv::VideoCapture     capture( CV_CAP_OPENNI );
    std::vector<cv::Mat> planes; //ビデオ画像を各色に分解した色情報
    while ( 1 ) { 
      // データの更新を待つ
      capture.grab(); 

      // ビデオ画像を取得
      cv::Mat  bgrImage;
      capture.retrieve( bgrImage, CV_CAP_OPENNI_BGR_IMAGE ); 
      cv::split(bgrImage, planes);
      
      // 深度を取得
      cv::Mat depthImage;
      capture.retrieve( depthImage, CV_CAP_OPENNI_DEPTH_MAP ); 
      int rows = depthImage.rows;
      int cols = depthImage.cols;	  
      for (int y=0; y<rows; y++) {
        for (int x=0; x<cols; x++) {
	  // ビデオ画像のうち、遠い箇所は黒にする
          if (depthImage.at<ushort>(y,x) > 2200 ) {
            planes[0].at<uchar>(y,x) = 0;
            planes[1].at<uchar>(y,x) = 0;
            planes[2].at<uchar>(y,x) = 0;
          }
        }
      }
   
      // 変換したビデオ画像を表示
      cv::Mat changedBgrImage;
      cv::merge(planes, changedBgrImage);
      cv::imshow( name, changedBgrImage );

      if ( cv::waitKey( 10 ) >= 0 ) {
        break; 
      }
    }

    cv::destroyAllWindows();
  }
  catch ( ... ) {
    std::cout << "exception!!" << std::endl;
  }
}