简体   繁体   中英

why can't I access imagedata in main?

I am trying to write a programme to read MRI data by using VTK and C++. But I can't get spacing of MRI raw data in main. The "GetSpacing" only works in "ReadImageData" function. I think I made some mistake in C++ programming. But I don't know where it is.

vtkImageData* ReadImageData(string mri_imagedata_file)
{
    vtkSmartPointer<vtkMetaImageReader> reader =
        vtkSmartPointer<vtkMetaImageReader>::New();
    reader->SetFileName(mri_imagedata_file.c_str());
    reader->Update();
    vtkImageData* metaimage = reader->GetOutput();
    double sp[3];
    metaimage->GetSpacing(sp);
    cout << sp[0] << " " << sp[1] << " " << sp[2] <<endl; //<----------It works here.
    return metaimage;
}

int main (int argc, char *argv[])
{
    if(argc != 2)
    {
        cerr << "Usage: " << argv[0] << " MRI image data" <<endl;
        return EXIT_FAILURE;
    }
    string mri_imagedata_file = argv[1];// Input "prost00.mhd"

    vtkImageData* metaimage = ReadImageData(mri_imagedata_file);
    double sp2[3];
    metaimage->GetSpacing(sp2);
    cout << sp2[0] << " " << sp2[1] << " " << sp2[2] << endl; //<-----It doesn't work here

}

Thank you for your attention.

我的假设是, vtkMetaImageReader::GetOutput()返回指针一些vtkMetaImageReader内部数据,所以当你退出ReadImageData您的reader被破坏,返回指针变为无效。

Assuming vtkSmartPointer<vtkMetaImageReader> is a kind of smart pointer whatever, reader points to in the function is destructed when ReadImageData returns. That includes what metaimage is pointing to.

    return metaimage;
    // reader->~();  // Destructed here. Including what is pointed to by metaimage. 
}

A good solution would be to return the smart pointer instead of metaimage . That way what is pointed to by reader will not be destructed when ReadImageData returns and will be available in main.

It looks like you forgot to pass the array as a parameter to GetSpacing in main , so it calls the overload that returns a double* , leaving your array untouched.

You're also printing an array called spacing although it looks like you want the spacing in sp2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM