简体   繁体   English

为什么我不能访问main中的imagedata?

[英]why can't I access imagedata in main?

I am trying to write a programme to read MRI data by using VTK and C++. 我正在尝试编写一个使用VTK和C ++读取MRI数据的程序。 But I can't get spacing of MRI raw data in main. 但是我无法获得MRI原始数据的间隔。 The "GetSpacing" only works in "ReadImageData" function. “ GetSpacing”仅在“ ReadImageData”功能中起作用。 I think I made some mistake in C++ programming. 我想我在C ++编程中犯了一些错误。 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. 假设vtkSmartPointer<vtkMetaImageReader>都是一种智能指针,则当ReadImageData返回时, reader指向的函数将被破坏。 That includes what metaimage is pointing to. 这包括元metaimage所指向的内容。

    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 . 一个好的解决方案是返回智能指针而不是metaimage That way what is pointed to by reader will not be destructed when ReadImageData returns and will be available in main. 这样,当ReadImageData返回时,不会破坏reader指向的内容,并且可以在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. 它看起来像你忘了传递数组作为参数传递给GetSpacingmain ,所以调用返回过载double* ,让你的阵列不变。

You're also printing an array called spacing although it looks like you want the spacing in sp2 . 您也正在打印一个名为spacing的数组,尽管看起来像您想要在sp2中的sp2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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