在C++中读取kinect深度文件

Reading a kinect depth file in C++

本文关键字:深度 文件 kinect 读取 C++      更新时间:2023-10-16

要读取帧的深度数据,必须跳过深度文件的前28个字节,其余的是一个由320*240个无符号短路组成的数组,即320*240*2个字节(因为每个深度帧都有320 x 240个像素)。我已经包含了用于读取深度文件的代码,但当我尝试运行它时,它总是挂起。请告诉我如何更正代码。

int main()
{
    int array_size = 76800*2;
    char *data[array_size];
    unsigned short depth[320][240];
    int i,j;
    // open the depth file in read mode.
    ifstream infile("000000.depth");
    // check for error in opening file
    if(!infile.is_open())
    {
        std::cout<< "File could not be opened";
        return 1;
    }
    std::cout << "Reading from the file" << endl;
    infile.seekg(29,ios::beg); // discarding first 28 bytes
    while(!infile.eof())
    {
        infile >> data[array_size];
    }
    // storing data in required array
    for (i=0; i = 320; i++)
    {
        for (j=0; j=240; j++)
        {
            depth[i][j] = (unsigned short)atof(data[i*j]);
            std::cout << depth[i][j] << endl;
        }
    }
    infile.close();
    getch();
    return(0);
}

Mmm,您似乎有for循环的问题。查看:

 for (i=0; i = 320; i++)

这意味着"运行循环,i从0开始,只要i = 320为true"。问题是i = 320作为一个值计算为320,这总是正确的。你想要i < 320

我认为问题在于在哪里分配char * data[array_size],请尝试char data[array_size],因为您分配的是指针的array_size,而不是内存块。此外,你的for循环应该是

for(i=0;i<320;i++)
  for(j=0;j<320;j++)
   { 
        //do your stuff here
       }

我想你的文件可能不是文本文件,所以尝试以二进制模式打开文件,即更改

 ifstream infile("000000.depth");

 ifstream infile("000000.depth", std::ios::binary);

并且使用CCD_ 9而不是CCD_。

编辑:

我还有一个问题:将数据读取到看起来像的数组data

while(!infile.eof())
{
    infile >> data[array_size];
}

应该读取char类型或char *(C样式字符串)的元素吗?

检查声明中data的类型(我想它一定是char data[array_size];),并考虑将文件读取为

 infile.get (data,array_size);

编辑2:

正如user3589654和Vincent Fourmond所说,你在循环for中有错误的条件,但也转换

 depth[i][j] = (unsigned short)atof(data[i*j]);

是潜在的问题来源:

1) atof转换为float,而不是intunsigned short

2) 表达式data[i*j]会从内存的错误部分获取数据,我想你想要data[i*240 + j](或类似的东西)

3) 如果您的文件不是以空格分隔的ASCII符号序列存储数字的文本文件,则这种读取和转换方法绝对不适合

感谢大家的投入。我已经完全更改了我的代码,现在它正在工作。我用C而不是C++写的。

如前所述,基本错误出现在for循环中。while循环也是一个错误源,没有必要先读取char,然后将其转换为无符号short。新代码如下所述;

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
unsigned short depth[320][240],x;
int i,j;
FILE *infile = fopen("000000.depth","rb");
fseek(infile, 29, SEEK_SET);
printf("Reading data from depth file");
for (i=0; i < 320; i++)
{
    for (j=0; j<240; j++)
{
        fread(&x, sizeof x, 1, infile);
        depth[i][j] = x;
        printf("n%d %d",depth[i][j],x);
}
}
fclose(infile);
getch();
return(0);
}