使用C代码读取MATLAB创建的netCDF文件会产生错误的数据

时间:2016-06-13 16:44:48

标签: c++ matlab netcdf

我在MATLAB中创建了一个具有以下属性的nc文件:

  • 格式:netcdf4_classic
  • 尺寸:xPx = 256,yPx = 256,polCoeff = 5
  • 变量:IntLinCorr
  • 尺寸:256x256x5
  • 尺寸:xPx,yPx,polCoeff
  • 数据类型:double

我已在MATLAB中读取该文件并检查它是否正确。

现在我想用C ++读取文件,使用Microsoft Visual Studio 10.我已经安装了netCDF 4.4.0 C库。这是我的代码段:

std::shared_ptr<CImg<double>> GUIModImag::doIntLinCorrection(std::shared_ptr<CImg<double>> image){
//image is an image of size 256x256 

// We are reading 3D data, a xPx x yPx x pNum grid. 
    static const int xPx = image->width(); //image width
    static const int yPx = image->height(); //image height
    static const int pNum = 5; //Number of coefficients from polynom fit
// This will be the netCDF ID for the file and data variable.
int nc_id, retval, var_id;

// Path of the used files
std::string fileName(QString("...."));

// This is the array we will read.
std::unique_ptr<double> dataIn(new double[xPx*yPx*pNum]);

// Open the file for read access (NC_NOWRITE)
if ((retval = nc_open(fileName.c_str(), NC_NOWRITE, &nc_id)))
    ERR(retval); // Makro for ERRORS

// Get the variable id of the data variable, based on its name
if ((retval = nc_inq_varid(nc_id, "IntLinCorr", &var_id)))
    ERR(retval);

// Read the data
if ((retval = nc_get_var_double(nc_id, var_id, &(dataIn.get()[0*0*0]))))
    ERR(retval);

// Work with data

double* p_FirstPixelImage = &(image->front());

for (int y=0; y<yPx; y++){
    for (int x=0; x<xPx; x++){

        *(p_FirstPixelImage+x+y)= dataIn.get()[x*y*0] * pow(*(p_FirstPixelImage+x+y),4)
                                + dataIn.get()[x*y*1] * pow(*(p_FirstPixelImage+x+y),3)
                                + dataIn.get()[x*y*2] * pow(*(p_FirstPixelImage+x+y),2)
                                + dataIn.get()[x*y*3] * pow(*(p_FirstPixelImage+x+y),1)
                                + dataIn.get()[x*y*4];
    }
}

return image;

// Close the file, freeing all resources. 
if ((retval = nc_close(nc_id)))
    ERR(retval);

}

原则上,代码工作正常,不会出现错误。但是,我用

读取的数据
dataIn.get()[x*y*0]

与我写入nc文件的那个不一样。实际上,我读取的双值在e-20的范围内,而我写的数据在e-18到e-0的范围内。

我想我的netCDF格式可能有问题。

有没有人有想法我能做些什么来正确读取数据?

非常感谢!

0 个答案:

没有答案