ni-simple-read

Overview

This example demonstrate how to get the distance (depth) value from camera for a specific point

Expect Output

...
Distance is      492 mm
Distance is      495 mm
Distance is      497 mm
Distance is      499 mm
Distance is      503 mm
Distance is      505 mm
Distance is      511 mm
...

Tutorial

  • Import openni header

#include <openni2/OpenNI.h>
  • Initialize SDK

if (openni::OpenNI::initialize() != openni::STATUS_OK)
{
    printf("Initialize Failed:%s\n", openni::OpenNI::getExtendedError());
    return -1;
}
  • Connect to camera

Device device;
 if (device.open(ANY_DEVICE) != STATUS_OK)
 {
   printf("Couldn't open device\n%s\n", OpenNI::getExtendedError());
   return 2;
 }
  • Create depth stream and start it

VideoStream depth;
if (depth.create(device, SENSOR_DEPTH) != STATUS_OK)
{
  printf("Couldn't create depth stream\n%s\n", OpenNI::getExtendedError());
  return 3;
}
if (depth.start() != STATUS_OK)
{
  printf("Couldn't start the depth stream\n%s\n", OpenNI::getExtendedError());
  return 4;
}
  • Read frame from camera and retrieve the depth data

if (depth.readFrame(&frame) != STATUS_OK)
{
  printf("Read failed!\n%s\n", OpenNI::getExtendedError());
  continue;
}
DepthPixel *pDepth = (DepthPixel *)frame.getData();
  • Depth data is store in ordered, from top left to bottom right. We calculate the index of the center point of the frame according to the width and height. Then get the value of it.

int middleIndex = (frame.getHeight() + 1) * frame.getWidth() / 2;
printf("Distance is %5d mm\n", pDepth[middleIndex]);

Full code

ni-simple-read.cpp

Last updated