cap_openni2.cpp 28.8 KB
Newer Older
wester committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"

#ifdef HAVE_OPENNI2

a  
Kai Westerkamp committed
47 48 49 50
#if defined TBB_INTERFACE_VERSION && TBB_INTERFACE_VERSION < 5000
# undef HAVE_TBB
#endif

wester committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#include <queue>

#ifndef i386
#  define i386 0
#endif
#ifndef __arm__
#  define __arm__ 0
#endif
#ifndef _ARC
#  define _ARC 0
#endif
#ifndef __APPLE__
#  define __APPLE__ 0
#endif

#define CV_STREAM_TIMEOUT 2000

a  
Kai Westerkamp committed
68 69
#define CV_DEPTH_STREAM 0
#define CV_COLOR_STREAM 1
wester committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

#include "OpenNI.h"
#include "PS1080.h"

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class CvCapture_OpenNI2 : public CvCapture
{
public:
    enum { DEVICE_DEFAULT=0, DEVICE_MS_KINECT=0, DEVICE_ASUS_XTION=1, DEVICE_MAX=1 };

    static const int INVALID_PIXEL_VAL = 0;
    static const int INVALID_COORDINATE_VAL = 0;

#ifdef HAVE_TBB
    static const int DEFAULT_MAX_BUFFER_SIZE = 8;
#else
    static const int DEFAULT_MAX_BUFFER_SIZE = 2;
#endif
    static const int DEFAULT_IS_CIRCLE_BUFFER = 0;
    static const int DEFAULT_MAX_TIME_DURATION = 20;

    CvCapture_OpenNI2(int index = 0);
    CvCapture_OpenNI2(const char * filename);
    virtual ~CvCapture_OpenNI2();

    virtual double getProperty(int propIdx) const;
    virtual bool setProperty(int probIdx, double propVal);
    virtual bool grabFrame();
    virtual IplImage* retrieveFrame(int outputType);

    bool isOpened() const;

protected:
    struct OutputMap
    {
    public:
        cv::Mat mat;
        IplImage* getIplImagePtr();
    private:
        IplImage iplHeader;
    };

a  
Kai Westerkamp committed
112
    static const int outputMapsTypesCount = 7;
wester committed
113

a  
Kai Westerkamp committed
114 115
    static openni::VideoMode defaultColorOutputMode();
    static openni::VideoMode defaultDepthOutputMode();
wester committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    IplImage* retrieveDepthMap();
    IplImage* retrievePointCloudMap();
    IplImage* retrieveDisparityMap();
    IplImage* retrieveDisparityMap_32F();
    IplImage* retrieveValidDepthMask();
    IplImage* retrieveBGRImage();
    IplImage* retrieveGrayImage();

    bool readCamerasParams();

    double getDepthGeneratorProperty(int propIdx) const;
    bool setDepthGeneratorProperty(int propIdx, double propVal);
    double getImageGeneratorProperty(int propIdx) const;
    bool setImageGeneratorProperty(int propIdx, double propVal);
    double getCommonProperty(int propIdx) const;
    bool setCommonProperty(int propIdx, double propVal);

    // OpenNI context
    openni::Device device;
    bool isContextOpened;
    openni::Recorder recorder;

    // Data generators with its metadata
a  
Kai Westerkamp committed
140 141 142
    openni::VideoStream depth, color, **streams;
    openni::VideoFrameRef depthFrame, colorFrame;
    cv::Mat depthImage, colorImage;
wester committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

    int maxBufferSize, maxTimeDuration; // for approx sync
    bool isCircleBuffer;
    //cv::Ptr<ApproximateSyncGrabber> approxSyncGrabber;

    // Cameras settings:
    // TODO find in OpenNI function to convert z->disparity and remove fields "baseline" and depthFocalLength_VGA
    // Distance between IR projector and IR camera (in meters)
    double baseline;
    // Focal length for the IR camera in VGA resolution (in pixels)
    int depthFocalLength_VGA;

    // The value for shadow (occluded pixels)
    int shadowValue;
    // The value for pixels without a valid disparity measurement
    int noSampleValue;

a  
Kai Westerkamp committed
160 161 162
    int currentStream;

    int numStream;
wester committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    std::vector<OutputMap> outputMaps;
};

IplImage* CvCapture_OpenNI2::OutputMap::getIplImagePtr()
{
    if( mat.empty() )
        return 0;

    iplHeader = IplImage(mat);
    return &iplHeader;
}

bool CvCapture_OpenNI2::isOpened() const
{
    return isContextOpened;
}

a  
Kai Westerkamp committed
180
openni::VideoMode CvCapture_OpenNI2::defaultColorOutputMode()
wester committed
181 182 183 184
{
    openni::VideoMode mode;
    mode.setResolution(640, 480);
    mode.setFps(30);
a  
Kai Westerkamp committed
185 186 187 188 189 190 191 192 193 194
    mode.setPixelFormat(openni::PIXEL_FORMAT_RGB888);
    return mode;
}

openni::VideoMode CvCapture_OpenNI2::defaultDepthOutputMode()
{
    openni::VideoMode mode;
    mode.setResolution(640, 480);
    mode.setFps(30);
    mode.setPixelFormat(openni::PIXEL_FORMAT_DEPTH_1_MM);
wester committed
195 196 197 198 199
    return mode;
}

CvCapture_OpenNI2::CvCapture_OpenNI2( int index )
{
a  
Kai Westerkamp committed
200
    numStream = 2;
wester committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    const char* deviceURI = openni::ANY_DEVICE;
    openni::Status status;
    int deviceType = DEVICE_DEFAULT;

    noSampleValue = shadowValue = 0;

    isContextOpened = false;
    maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
    isCircleBuffer = DEFAULT_IS_CIRCLE_BUFFER;
    maxTimeDuration = DEFAULT_MAX_TIME_DURATION;

    if( index >= 10 )
    {
        deviceType = index / 10;
        index %= 10;
    }

a  
Kai Westerkamp committed
218 219 220 221 222 223 224
    // Asus XTION and Occipital Structure Sensor do not have an image generator
    if (deviceType == DEVICE_ASUS_XTION)
        numStream = 1;

    if( deviceType > DEVICE_MAX )
        return;

wester committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    // Initialize and configure the context.
    status = openni::OpenNI::initialize();

    if (status != openni::STATUS_OK)
    {
        CV_Error(CV_StsError, cv::format("Failed to initialize:", openni::OpenNI::getExtendedError()));
        return;
    }

    status = device.open(deviceURI);
    if( status != openni::STATUS_OK )
    {
        CV_Error(CV_StsError, cv::format("OpenCVKinect: Device open failed see: %s\n", openni::OpenNI::getExtendedError()));
        openni::OpenNI::shutdown();
        return;
    }

a  
Kai Westerkamp committed
242 243 244 245 246
    //device.setDepthColorSyncEnabled(true);


    status = depth.create(device, openni::SENSOR_DEPTH);
    if (status == openni::STATUS_OK)
wester committed
247
    {
a  
Kai Westerkamp committed
248 249 250 251
        if (depth.isValid())
        {
            CV_Assert(depth.setVideoMode(defaultDepthOutputMode()) == openni::STATUS_OK); // xn::DepthGenerator supports VGA only! (Jan 2011)
        }
wester committed
252

a  
Kai Westerkamp committed
253 254 255 256 257 258 259 260 261
        status = depth.start();
        if (status != openni::STATUS_OK)
        {
            CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Couldn't start depth stream: %s\n", openni::OpenNI::getExtendedError()));
            depth.destroy();
            return;
        }
    }
    else
wester committed
262
    {
a  
Kai Westerkamp committed
263
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Couldn't find depth stream:: %s\n", openni::OpenNI::getExtendedError()));
wester committed
264 265 266
        return;
    }

a  
Kai Westerkamp committed
267 268
    streams = new openni::VideoStream*[numStream];
    streams[CV_DEPTH_STREAM] = &depth;
wester committed
269

a  
Kai Westerkamp committed
270 271 272
    // create a color object
    status = color.create(device, openni::SENSOR_COLOR);
    if (status == openni::STATUS_OK)
wester committed
273
    {
a  
Kai Westerkamp committed
274 275
        // Set map output mode.
        if (color.isValid())
wester committed
276
        {
a  
Kai Westerkamp committed
277
            CV_Assert(color.setVideoMode(defaultColorOutputMode()) == openni::STATUS_OK);
wester committed
278
        }
a  
Kai Westerkamp committed
279 280
        status = color.start();
        if (status != openni::STATUS_OK)
wester committed
281
        {
a  
Kai Westerkamp committed
282 283 284
            CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Couldn't start color stream: %s\n", openni::OpenNI::getExtendedError()));
            color.destroy();
            return;
wester committed
285
        }
a  
Kai Westerkamp committed
286 287 288 289 290 291
        streams[CV_COLOR_STREAM] = &color;
    }
    else if (numStream == 2)
    {
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Couldn't find color stream: %s\n", openni::OpenNI::getExtendedError()));
        return;
wester committed
292
    }
a  
Kai Westerkamp committed
293 294

    if( !readCamerasParams() )
wester committed
295
    {
a  
Kai Westerkamp committed
296 297
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Could not read cameras parameters\n"));
        return;
wester committed
298 299
    }

a  
Kai Westerkamp committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313
//    if( deviceType == DEVICE_ASUS_XTION )
//    {
//        //ps/asus specific
//        imageGenerator.SetIntProperty("InputFormat", 1 /*XN_IO_IMAGE_FORMAT_YUV422*/);
//        imageGenerator.SetPixelFormat(XN_PIXEL_FORMAT_RGB24);
//        depthGenerator.SetIntProperty("RegistrationType", 1 /*XN_PROCESSING_HARDWARE*/);
//    }


    outputMaps.resize( outputMapsTypesCount );

    isContextOpened = true;

    setProperty(CV_CAP_PROP_OPENNI_REGISTRATION, 1.0);
wester committed
314 315 316 317
}

CvCapture_OpenNI2::CvCapture_OpenNI2(const char * filename)
{
a  
Kai Westerkamp committed
318
    numStream = 2;
wester committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    openni::Status status;

    isContextOpened = false;
    maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
    isCircleBuffer = DEFAULT_IS_CIRCLE_BUFFER;
    maxTimeDuration = DEFAULT_MAX_TIME_DURATION;

    // Initialize and configure the context.
    status = openni::OpenNI::initialize();

    if (status != openni::STATUS_OK)
    {
        CV_Error(CV_StsError, cv::format("Failed to initialize:", openni::OpenNI::getExtendedError()));
        return;
    }

    // Open file
    status = device.open(filename);
    if( status != openni::STATUS_OK )
    {
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Failed to open input file (%s): %s\n", filename, openni::OpenNI::getExtendedError()));
        return;
    }

    if( !readCamerasParams() )
    {
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::CvCapture_OpenNI2 : Could not read cameras parameters\n"));
        return;
    }

    outputMaps.resize( outputMapsTypesCount );

    isContextOpened = true;
}

CvCapture_OpenNI2::~CvCapture_OpenNI2()
{
a  
Kai Westerkamp committed
356 357 358 359
    this->depthFrame.release();
    this->colorFrame.release();
    this->depth.stop();
    this->color.stop();
wester committed
360 361 362 363 364 365
    openni::OpenNI::shutdown();
}

bool CvCapture_OpenNI2::readCamerasParams()
{
    double pixelSize = 0;
a  
Kai Westerkamp committed
366
    if (depth.getProperty<double>(XN_STREAM_PROPERTY_ZERO_PLANE_PIXEL_SIZE, &pixelSize) != openni::STATUS_OK)
wester committed
367 368 369 370 371 372 373 374 375 376
    {
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::readCamerasParams : Could not read pixel size!\n"));
        return false;
    }

    // pixel size @ VGA = pixel size @ SXGA x 2
    pixelSize *= 2.0; // in mm

    // focal length of IR camera in pixels for VGA resolution
    int zeroPlanDistance; // in mm
a  
Kai Westerkamp committed
377
    if (depth.getProperty(XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE, &zeroPlanDistance) != openni::STATUS_OK)
wester committed
378 379 380 381 382
    {
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::readCamerasParams : Could not read virtual plane distance!\n"));
        return false;
    }

a  
Kai Westerkamp committed
383
    if (depth.getProperty<double>(XN_STREAM_PROPERTY_EMITTER_DCMOS_DISTANCE, &baseline) != openni::STATUS_OK)
wester committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    {
        CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::readCamerasParams : Could not read base line!\n"));
        return false;
    }

    // baseline from cm -> mm
    baseline *= 10;

    // focal length from mm -> pixels (valid for 640x480)
    depthFocalLength_VGA = (int)((double)zeroPlanDistance / (double)pixelSize);

    return true;
}

double CvCapture_OpenNI2::getProperty( int propIdx ) const
{
    double propValue = 0;

    if( isOpened() )
    {
        int purePropIdx = propIdx & ~CV_CAP_OPENNI_GENERATORS_MASK;

        if( (propIdx & CV_CAP_OPENNI_GENERATORS_MASK) == CV_CAP_OPENNI_IMAGE_GENERATOR )
        {
            propValue = getImageGeneratorProperty( purePropIdx );
        }
        else if( (propIdx & CV_CAP_OPENNI_GENERATORS_MASK) == CV_CAP_OPENNI_DEPTH_GENERATOR )
        {
            propValue = getDepthGeneratorProperty( purePropIdx );
        }
        else
        {
            propValue = getCommonProperty( purePropIdx );
        }
    }

    return propValue;
}

bool CvCapture_OpenNI2::setProperty( int propIdx, double propValue )
{
    bool isSet = false;
    if( isOpened() )
    {
        int purePropIdx = propIdx & ~CV_CAP_OPENNI_GENERATORS_MASK;

        if( (propIdx & CV_CAP_OPENNI_GENERATORS_MASK) == CV_CAP_OPENNI_IMAGE_GENERATOR )
        {
            isSet = setImageGeneratorProperty( purePropIdx, propValue );
        }
        else if( (propIdx & CV_CAP_OPENNI_GENERATORS_MASK) == CV_CAP_OPENNI_DEPTH_GENERATOR )
        {
            isSet = setDepthGeneratorProperty( purePropIdx, propValue );
        }
        else
        {
            isSet = setCommonProperty( purePropIdx, propValue );
        }
    }

    return isSet;
}

double CvCapture_OpenNI2::getCommonProperty( int propIdx ) const
{
    double propValue = 0;

    switch( propIdx )
    {
a  
Kai Westerkamp committed
453 454 455 456 457 458
    // There is a set of properties that correspond to depth generator by default
    // (is they are pass without particular generator flag). Two reasons of this:
    // 1) We can assume that depth generator is the main one for depth sensor.
    // 2) In the initial vertions of OpenNI integration to OpenCV the value of
    //    flag CV_CAP_OPENNI_DEPTH_GENERATOR was 0 (it isn't zero now).
    case CV_CAP_PROP_OPENNI_GENERATOR_PRESENT :
wester committed
459 460 461 462 463 464 465 466 467 468 469 470 471
    case CV_CAP_PROP_FRAME_WIDTH :
    case CV_CAP_PROP_FRAME_HEIGHT :
    case CV_CAP_PROP_FPS :
    case CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH :
    case CV_CAP_PROP_OPENNI_BASELINE :
    case CV_CAP_PROP_OPENNI_FOCAL_LENGTH :
    case CV_CAP_PROP_OPENNI_REGISTRATION :
        propValue = getDepthGeneratorProperty( propIdx );
        break;
    case CV_CAP_PROP_OPENNI2_SYNC :
        propValue = const_cast<CvCapture_OpenNI2 *>(this)->device.getDepthColorSyncEnabled();
    case CV_CAP_PROP_OPENNI2_MIRROR:
    {
a  
Kai Westerkamp committed
472
        bool isMirroring = color.getMirroringEnabled() && depth.getMirroringEnabled();
wester committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
        propValue = isMirroring ? 1.0 : 0.0;
        break;
    }
    default :
        CV_Error( CV_StsBadArg, cv::format("Such parameter (propIdx=%d) isn't supported for getting.\n", propIdx) );
    }

    return propValue;
}

bool CvCapture_OpenNI2::setCommonProperty( int propIdx, double propValue )
{
    bool isSet = false;

    switch( propIdx )
    {
    case CV_CAP_PROP_OPENNI2_MIRROR:
    {
        bool mirror = propValue > 0.0 ? true : false;
a  
Kai Westerkamp committed
492 493
        isSet = color.setMirroringEnabled(mirror) == openni::STATUS_OK;
        isSet = depth.setMirroringEnabled(mirror) == openni::STATUS_OK;
wester committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    }
        break;
    // There is a set of properties that correspond to depth generator by default
    // (is they are pass without particular generator flag).
    case CV_CAP_PROP_OPENNI_REGISTRATION:
        isSet = setDepthGeneratorProperty( propIdx, propValue );
        break;
    case CV_CAP_PROP_OPENNI2_SYNC:
        isSet = device.setDepthColorSyncEnabled(propValue > 0.0) == openni::STATUS_OK;
        break;
    default:
        CV_Error( CV_StsBadArg, cv::format("Such parameter (propIdx=%d) isn't supported for setting.\n", propIdx) );
    }

    return isSet;
}

double CvCapture_OpenNI2::getDepthGeneratorProperty( int propIdx ) const
{
    double propValue = 0;
a  
Kai Westerkamp committed
514
    if( !depth.isValid() )
wester committed
515 516 517 518 519 520
        return propValue;

    openni::VideoMode mode;

    switch( propIdx )
    {
a  
Kai Westerkamp committed
521 522 523
    case CV_CAP_PROP_OPENNI_GENERATOR_PRESENT :
        CV_DbgAssert(depth.isValid());
        propValue = 1.;
wester committed
524 525
        break;
    case CV_CAP_PROP_FRAME_WIDTH :
a  
Kai Westerkamp committed
526
        propValue = depth.getVideoMode().getResolutionX();
wester committed
527 528
        break;
    case CV_CAP_PROP_FRAME_HEIGHT :
a  
Kai Westerkamp committed
529
            propValue = depth.getVideoMode().getResolutionY();
wester committed
530 531
        break;
    case CV_CAP_PROP_FPS :
a  
Kai Westerkamp committed
532
        mode = depth.getVideoMode();
wester committed
533 534 535
        propValue = mode.getFps();
        break;
    case CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH :
a  
Kai Westerkamp committed
536
        propValue = depth.getMaxPixelValue();
wester committed
537 538 539 540 541 542 543 544 545 546 547
        break;
    case CV_CAP_PROP_OPENNI_BASELINE :
        propValue = baseline;
        break;
    case CV_CAP_PROP_OPENNI_FOCAL_LENGTH :
        propValue = (double)depthFocalLength_VGA;
        break;
    case CV_CAP_PROP_OPENNI_REGISTRATION :
        propValue = device.getImageRegistrationMode();
        break;
    case CV_CAP_PROP_POS_MSEC :
a  
Kai Westerkamp committed
548
        propValue = (double)depthFrame.getTimestamp();
wester committed
549 550
        break;
    case CV_CAP_PROP_POS_FRAMES :
a  
Kai Westerkamp committed
551
        propValue = depthFrame.getFrameIndex();
wester committed
552 553 554 555 556 557 558 559 560 561 562 563
        break;
    default :
        CV_Error( CV_StsBadArg, cv::format("Depth generator does not support such parameter (propIdx=%d) for getting.\n", propIdx) );
    }

    return propValue;
}

bool CvCapture_OpenNI2::setDepthGeneratorProperty( int propIdx, double propValue )
{
    bool isSet = false;

a  
Kai Westerkamp committed
564 565
    CV_Assert( depth.isValid() );

wester committed
566 567 568 569 570 571 572 573
    switch( propIdx )
    {
    case CV_CAP_PROP_OPENNI_REGISTRATION:
        {
            if( propValue != 0.0 ) // "on"
            {
                // if there isn't image generator (i.e. ASUS XtionPro doesn't have it)
                // then the property isn't avaliable
a  
Kai Westerkamp committed
574
                if ( color.isValid() )
wester committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
                {
                    openni::ImageRegistrationMode mode = propValue != 0.0 ? openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR : openni::IMAGE_REGISTRATION_OFF;
                    if( !device.getImageRegistrationMode() == mode )
                    {
                        if (device.isImageRegistrationModeSupported(mode))
                        {
                            openni::Status status = device.setImageRegistrationMode(mode);
                            if( status != openni::STATUS_OK )
                                CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::setDepthGeneratorProperty : %s\n", openni::OpenNI::getExtendedError()));
                            else
                                isSet = true;
                        }
                        else
                            CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::setDepthGeneratorProperty : Unsupported viewpoint.\n"));
                    }
                    else
                        isSet = true;
                }
            }
            else // "off"
            {
                openni::Status status = device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_OFF);
                if( status != openni::STATUS_OK )
                    CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::setDepthGeneratorProperty : %s\n", openni::OpenNI::getExtendedError()));
                else
                    isSet = true;
            }
        }
        break;
    default:
        CV_Error( CV_StsBadArg, cv::format("Depth generator does not support such parameter (propIdx=%d) for setting.\n", propIdx) );
    }

    return isSet;
}

double CvCapture_OpenNI2::getImageGeneratorProperty( int propIdx ) const
{
    double propValue = 0.;
a  
Kai Westerkamp committed
614
    if( !color.isValid() )
wester committed
615 616 617 618 619
        return propValue;

    openni::VideoMode mode;
    switch( propIdx )
    {
a  
Kai Westerkamp committed
620 621 622
    case CV_CAP_PROP_OPENNI_GENERATOR_PRESENT :
        CV_DbgAssert( color.isValid() );
        propValue = 1.;
wester committed
623 624
        break;
    case CV_CAP_PROP_FRAME_WIDTH :
a  
Kai Westerkamp committed
625
            propValue = color.getVideoMode().getResolutionX();
wester committed
626 627
        break;
    case CV_CAP_PROP_FRAME_HEIGHT :
a  
Kai Westerkamp committed
628
            propValue = color.getVideoMode().getResolutionY();
wester committed
629 630
        break;
    case CV_CAP_PROP_FPS :
a  
Kai Westerkamp committed
631
            propValue = color.getVideoMode().getFps();
wester committed
632 633
        break;
    case CV_CAP_PROP_POS_MSEC :
a  
Kai Westerkamp committed
634
        propValue = (double)colorFrame.getTimestamp();
wester committed
635 636
        break;
    case CV_CAP_PROP_POS_FRAMES :
a  
Kai Westerkamp committed
637
        propValue = (double)colorFrame.getFrameIndex();
wester committed
638 639 640 641 642 643 644 645 646 647 648
        break;
    default :
        CV_Error( CV_StsBadArg, cv::format("Image generator does not support such parameter (propIdx=%d) for getting.\n", propIdx) );
    }

    return propValue;
}

bool CvCapture_OpenNI2::setImageGeneratorProperty(int propIdx, double propValue)
{
    bool isSet = false;
a  
Kai Westerkamp committed
649 650
        if( !color.isValid() )
            return isSet;
wester committed
651 652 653 654 655

        switch( propIdx )
        {
        case CV_CAP_PROP_OPENNI_OUTPUT_MODE :
        {
a  
Kai Westerkamp committed
656
            openni::VideoMode mode = color.getVideoMode();
wester committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683

            switch( cvRound(propValue) )
            {
            case CV_CAP_OPENNI_VGA_30HZ :
                mode.setResolution(640,480);
                mode.setFps(30);
                break;
            case CV_CAP_OPENNI_SXGA_15HZ :
                mode.setResolution(1280, 960);
                mode.setFps(15);
                break;
            case CV_CAP_OPENNI_SXGA_30HZ :
                mode.setResolution(1280, 960);
                mode.setFps(30);
                break;
            case CV_CAP_OPENNI_QVGA_30HZ :
                mode.setResolution(320, 240);
                mode.setFps(30);
                 break;
            case CV_CAP_OPENNI_QVGA_60HZ :
                mode.setResolution(320, 240);
                mode.setFps(60);
                 break;
            default :
                CV_Error( CV_StsBadArg, "Unsupported image generator output mode.\n");
            }

a  
Kai Westerkamp committed
684
            openni::Status status = color.setVideoMode( mode );
wester committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
            if( status != openni::STATUS_OK )
                CV_Error(CV_StsError, cv::format("CvCapture_OpenNI2::setImageGeneratorProperty : %s\n", openni::OpenNI::getExtendedError()));
            else
                isSet = true;
            break;
        }
        default:
            CV_Error( CV_StsBadArg, cv::format("Image generator does not support such parameter (propIdx=%d) for setting.\n", propIdx) );
        }

    return isSet;
}

bool CvCapture_OpenNI2::grabFrame()
{
    if( !isOpened() )
        return false;

    bool isGrabbed = false;

a  
Kai Westerkamp committed
705
    openni::Status status = openni::OpenNI::waitForAnyStream(streams, numStream, &currentStream, CV_STREAM_TIMEOUT);
wester committed
706 707 708
    if( status != openni::STATUS_OK )
        return false;

a  
Kai Westerkamp committed
709 710 711 712
    if( depth.isValid() )
        depth.readFrame(&depthFrame);
    if (color.isValid())
        color.readFrame(&colorFrame);
wester committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    isGrabbed = true;

    return isGrabbed;
}

inline void getDepthMapFromMetaData(const openni::VideoFrameRef& depthMetaData, cv::Mat& depthMap, int noSampleValue, int shadowValue)
{
    depthMap.create(depthMetaData.getHeight(), depthMetaData.getWidth(), CV_16UC1);
    depthMap.data = (uchar*)depthMetaData.getData();

    cv::Mat badMask = (depthMap == (double)noSampleValue) | (depthMap == (double)shadowValue) | (depthMap == 0);

    // mask the pixels with invalid depth
    depthMap.setTo( cv::Scalar::all( CvCapture_OpenNI2::INVALID_PIXEL_VAL ), badMask );
}

IplImage* CvCapture_OpenNI2::retrieveDepthMap()
{
a  
Kai Westerkamp committed
731
    if( !depth.isValid() )
wester committed
732 733
        return 0;

a  
Kai Westerkamp committed
734
    getDepthMapFromMetaData( depthFrame, outputMaps[CV_CAP_OPENNI_DEPTH_MAP].mat, noSampleValue, shadowValue );
wester committed
735 736 737 738 739 740

    return outputMaps[CV_CAP_OPENNI_DEPTH_MAP].getIplImagePtr();
}

IplImage* CvCapture_OpenNI2::retrievePointCloudMap()
{
a  
Kai Westerkamp committed
741
    if( !depthFrame.isValid() )
wester committed
742 743 744
        return 0;

    cv::Mat depthImg;
a  
Kai Westerkamp committed
745
    getDepthMapFromMetaData(depthFrame, depthImg, noSampleValue, shadowValue);
wester committed
746 747 748

    const int badPoint = INVALID_PIXEL_VAL;
    const float badCoord = INVALID_COORDINATE_VAL;
a  
Kai Westerkamp committed
749
    int cols = depthFrame.getWidth(), rows = depthFrame.getHeight();
wester committed
750 751 752 753 754 755 756
    cv::Mat pointCloud_XYZ( rows, cols, CV_32FC3, cv::Scalar::all(badPoint) );

    float worldX, worldY, worldZ;
    for( int y = 0; y < rows; y++ )
    {
        for (int x = 0; x < cols; x++)
        {
a  
Kai Westerkamp committed
757
            openni::CoordinateConverter::convertDepthToWorld(depth, x, y, depthImg.at<unsigned short>(y, x), &worldX, &worldY, &worldZ);
wester committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

            if (depthImg.at<unsigned short>(y, x) == badPoint) // not valid
                pointCloud_XYZ.at<cv::Point3f>(y, x) = cv::Point3f(badCoord, badCoord, badCoord);
            else
            {
                pointCloud_XYZ.at<cv::Point3f>(y, x) = cv::Point3f(worldX*0.001f, worldY*0.001f, worldZ*0.001f); // from mm to meters
            }
        }
    }

    outputMaps[CV_CAP_OPENNI_POINT_CLOUD_MAP].mat = pointCloud_XYZ;

    return outputMaps[CV_CAP_OPENNI_POINT_CLOUD_MAP].getIplImagePtr();
}

static void computeDisparity_32F( const openni::VideoFrameRef& depthMetaData, cv::Mat& disp, double baseline, int F, int noSampleValue, int shadowValue)
{
    cv::Mat depth;
    getDepthMapFromMetaData( depthMetaData, depth, noSampleValue, shadowValue );
    CV_Assert( depth.type() == CV_16UC1 );

    // disparity = baseline * F / z;

    float mult = (float)(baseline /*mm*/ * F /*pixels*/);

    disp.create( depth.size(), CV_32FC1);
    disp = cv::Scalar::all( CvCapture_OpenNI2::INVALID_PIXEL_VAL );
    for( int y = 0; y < disp.rows; y++ )
    {
        for( int x = 0; x < disp.cols; x++ )
        {
            unsigned short curDepth = depth.at<unsigned short>(y,x);
            if( curDepth != CvCapture_OpenNI2::INVALID_PIXEL_VAL )
                disp.at<float>(y,x) = mult / curDepth;
        }
    }
}

IplImage* CvCapture_OpenNI2::retrieveDisparityMap()
{
a  
Kai Westerkamp committed
798
    if (!depthFrame.isValid())
wester committed
799 800 801
        return 0;

    cv::Mat disp32;
a  
Kai Westerkamp committed
802
    computeDisparity_32F(depthFrame, disp32, baseline, depthFocalLength_VGA, noSampleValue, shadowValue);
wester committed
803 804 805 806 807 808 809 810

    disp32.convertTo( outputMaps[CV_CAP_OPENNI_DISPARITY_MAP].mat, CV_8UC1 );

    return outputMaps[CV_CAP_OPENNI_DISPARITY_MAP].getIplImagePtr();
}

IplImage* CvCapture_OpenNI2::retrieveDisparityMap_32F()
{
a  
Kai Westerkamp committed
811
    if (!depthFrame.isValid())
wester committed
812 813
        return 0;

a  
Kai Westerkamp committed
814
    computeDisparity_32F(depthFrame, outputMaps[CV_CAP_OPENNI_DISPARITY_MAP_32F].mat, baseline, depthFocalLength_VGA, noSampleValue, shadowValue);
wester committed
815 816 817 818 819 820

    return outputMaps[CV_CAP_OPENNI_DISPARITY_MAP_32F].getIplImagePtr();
}

IplImage* CvCapture_OpenNI2::retrieveValidDepthMask()
{
a  
Kai Westerkamp committed
821
    if (!depthFrame.isValid())
wester committed
822 823 824
        return 0;

    cv::Mat d;
a  
Kai Westerkamp committed
825
    getDepthMapFromMetaData(depthFrame, d, noSampleValue, shadowValue);
wester committed
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846

    outputMaps[CV_CAP_OPENNI_VALID_DEPTH_MASK].mat = d != CvCapture_OpenNI2::INVALID_PIXEL_VAL;

    return outputMaps[CV_CAP_OPENNI_VALID_DEPTH_MASK].getIplImagePtr();
}

inline void getBGRImageFromMetaData( const openni::VideoFrameRef& imageMetaData, cv::Mat& bgrImage )
{
   cv::Mat bufferImage;
   if( imageMetaData.getVideoMode().getPixelFormat() != openni::PIXEL_FORMAT_RGB888 )
        CV_Error( CV_StsUnsupportedFormat, "Unsupported format of grabbed image\n" );

   bgrImage.create(imageMetaData.getHeight(), imageMetaData.getWidth(), CV_8UC3);
   bufferImage.create(imageMetaData.getHeight(), imageMetaData.getWidth(), CV_8UC3);
   bufferImage.data = (uchar*)imageMetaData.getData();

   cv::cvtColor(bufferImage, bgrImage, cv::COLOR_RGB2BGR);
}

IplImage* CvCapture_OpenNI2::retrieveBGRImage()
{
a  
Kai Westerkamp committed
847
    if( !color.isValid() )
wester committed
848 849
        return 0;

a  
Kai Westerkamp committed
850
    getBGRImageFromMetaData( colorFrame, outputMaps[CV_CAP_OPENNI_BGR_IMAGE].mat );
wester committed
851 852 853 854 855 856

    return outputMaps[CV_CAP_OPENNI_BGR_IMAGE].getIplImagePtr();
}

IplImage* CvCapture_OpenNI2::retrieveGrayImage()
{
a  
Kai Westerkamp committed
857
    if (!colorFrame.isValid())
wester committed
858 859
        return 0;

a  
Kai Westerkamp committed
860
    CV_Assert(colorFrame.getVideoMode().getPixelFormat() == openni::PIXEL_FORMAT_RGB888); // RGB
wester committed
861 862

    cv::Mat rgbImage;
a  
Kai Westerkamp committed
863
    getBGRImageFromMetaData(colorFrame, rgbImage);
wester committed
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
    cv::cvtColor( rgbImage, outputMaps[CV_CAP_OPENNI_GRAY_IMAGE].mat, CV_BGR2GRAY );

    return outputMaps[CV_CAP_OPENNI_GRAY_IMAGE].getIplImagePtr();
}

IplImage* CvCapture_OpenNI2::retrieveFrame( int outputType )
{
    IplImage* image = 0;
    CV_Assert( outputType < outputMapsTypesCount && outputType >= 0);

    if( outputType == CV_CAP_OPENNI_DEPTH_MAP )
    {
        image = retrieveDepthMap();
    }
    else if( outputType == CV_CAP_OPENNI_POINT_CLOUD_MAP )
    {
        image = retrievePointCloudMap();
    }
    else if( outputType == CV_CAP_OPENNI_DISPARITY_MAP )
    {
        image = retrieveDisparityMap();
    }
    else if( outputType == CV_CAP_OPENNI_DISPARITY_MAP_32F )
    {
        image = retrieveDisparityMap_32F();
    }
    else if( outputType == CV_CAP_OPENNI_VALID_DEPTH_MASK )
    {
        image = retrieveValidDepthMask();
    }
    else if( outputType == CV_CAP_OPENNI_BGR_IMAGE )
    {
        image = retrieveBGRImage();
    }
    else if( outputType == CV_CAP_OPENNI_GRAY_IMAGE )
    {
        image = retrieveGrayImage();
    }

    return image;
}

CvCapture* cvCreateCameraCapture_OpenNI2( int index )
{
    CvCapture_OpenNI2* capture = new CvCapture_OpenNI2( index );

    if( capture->isOpened() )
        return capture;

    delete capture;
    return 0;
}

a  
Kai Westerkamp committed
917
CvCapture* cvCreateFileCapture_OpenNI( const char* filename )
wester committed
918 919 920 921 922 923 924 925 926 927 928
{
    CvCapture_OpenNI2* capture = new CvCapture_OpenNI2( filename );

    if( capture->isOpened() )
        return capture;

    delete capture;
    return 0;
}

#endif