写在前面:自知水平有限,文章中可能有错误,欢迎各位留言指正
一、程序思路
二、例程
#include <iostream> #include <Windows.h> #include <opencv.hpp> #include <Kinect.h> using namespace std; using namespace cv; int main(int argc, char* argv[]) { namedWindow("Color", 0); IKinectSensor *sensor = nullptr;//创建KinectSensor空指针 IColorFrameSource *source = nullptr; IColorFrameReader *reader = nullptr; IColorFrame *frame = nullptr; IFrameDescription *description = nullptr; int height = 0, width = 0; unsigned int bytesPerPixel = 0; HRESULT result; result = GetDefaultKinectSensor( &sensor );//获取默认Kinect Device if (SUCCEEDED(result))//判断是否正确获取Kinect { cout << "Found Kinect Device" << endl; } else { return result; } result = sensor->Open();//打开Kinect Sleep(500);//等待500ms,保证Kinect正确打开 if (SUCCEEDED(result)) { cout << "Success to open Kinect" << endl; } else { return result; } result = sensor->get_ColorFrameSource(&source);//获取ColorFrameSource if (SUCCEEDED(result)) { cout << "Get Color Source" << endl; } else { return result; } source->get_FrameDescription(&description);//获取帧格式描述 description->get_Height(&height);//帧高度 description->get_Width(&width);//帧宽度 description->get_BytesPerPixel(&bytesPerPixel);//每一像素的大小,单位Byte cout << height << endl << width << endl<< bytesPerPixel << endl; //Sleep(15000); //return -1; result = source->OpenReader(&reader);//获取彩色图像Reader if (SUCCEEDED(result)) { cout << "Get Color Reader" << endl; } else { return result; } Mat colorImage(height, width, CV_8UC4);//创建Mat,用来放彩色图像数据 while (1) { result = reader->AcquireLatestFrame(&frame);//获取最新的彩色帧 if (FAILED(result) || !frame)//检测是否成功获取帧数据,并不是每一次都能成功获取的 { cout << "Lose data" << endl; continue; } else { cout << "Got it" << endl; frame->CopyConvertedFrameDataToArray(height * width * 4 * sizeof(BYTE), reinterpret_cast<BYTE*>(colorImage.data), ColorImageFormat_Bgra);//图像数据流转换 frame->Release();//每一次获取帧后都要释放 imshow("Color", colorImage);//绘制图像 } if (waitKey(40) > 0)//按任意键退出程序 break; } reader->Release();//释放指针 source->Release(); sensor->Close();//sensor记得要先Close再释放 sensor->Release(); return 0; }
三、重要函数
public:
HRESULT CopyConvertedFrameDataToArray(
UINT capacity,
BYTE *frameData,
ColorImageFormat colorFormat
)
功能:将Kinect的彩色帧数据以指定格式复制到byte array 矩阵中
Parameters//参数@capacity//容量
Type: UINT
When this method returns, contains the size of the frame data buffer in bytes.
图像帧的大小,单位BYTE
Type: BYTE
[out] The array to which to copy the converted color frame data.
存放图像帧数据的矩阵的指针,矩阵类型:BYTE,这里用了reinterpret_cast<BYTE*>做强制类型转换
@colorFormatType: ColorImageFormat
The image format to which to convert the color frame data.
指定图像数据在矩阵中的存放格式,有以下几种:
enum _ColorImageFormat
{
ColorImageFormat_None = 0,
ColorImageFormat_Rgba = 1,
ColorImageFormat_Yuv = 2,
ColorImageFormat_Bgra = 3,
ColorImageFormat_Bayer = 4,
ColorImageFormat_Yuy2 = 5
} ;
Type: HRESULT
Returns S_OK if successful; otherwise, returns a failure code.
返回函数执行结果,成功,返回S_OK,否则转换失败