c++ - 如何使用 vtkImageImport 创建在删除 vtkImageImport 后仍然存在的 vtkImageData?

标签 c++ c vtk

我有一个简单的 C 指针,其中包含一些 RGBA 图像数据,我想将其用作 vtkImageData 来添加为 vtkActor 上的纹理。为此,我有一些代码,例如

vtkSmartPointer<vtkActor> myActor; // initialized elsewhere

setActorTexture( unsigned char* pData, int width, int height )
{
    vtkSmartPointer<vtkImageData> imageData;

    if( pData )
    {
        vtkSmartPointer<vtkImageImport> imageImport = vtkSmartPointer<vtkImageImport>::New();
        imageImport->SetWholeExtent( 0, width - 1, 0, height - 1, 0, 0 );
        imageImport->SetDataExtentToWholeExtent();
        imageImport->SetDataScalarTypeToUnsignedChar();
        imageImport->SetNumberOfScalarComponents( 4 );
        imageImport->CopyImportVoidPointer( pData, width * height * 4 );

        imageData = vtkSmartPointer<vtkImageData>::New();
        imageData = imageImport->GetOutput();
    }

    if( imageData != nullptr )
    {
        vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New();
        texture->SetInputData( imageData );
        myActor->SetTexture( texture );
    }
}

遗憾的是,当图像数据稍后用于渲染时,这会导致内存异常。一旦 imageImport 对象超出范围,imageData 对象就会变得无效。

如何阻止 imageImport 对象在超出范围时删除自身? texture->SetInputData()myActor->SetTexture() 函数注册其参数,以便 vtkObject 正确设置其引用计数。我认为我需要做一些事情,以便 imageImport 也正确设置其引用计数,以反射(reflect) imageData 的需要。

最佳答案

您是否尝试过 DeepCopy 输出?

setActorTexture( unsigned char* pData, int width, int height )
{
    vtkSmartPointer<vtkImageData> imageData;

    if( pData )
    {
        vtkSmartPointer<vtkImageImport> imageImport = vtkSmartPointer<vtkImageImport>::New();
        imageImport->SetWholeExtent( 0, width - 1, 0, height - 1, 0, 0 );
        imageImport->SetDataExtentToWholeExtent();
        imageImport->SetDataScalarTypeToUnsignedChar();
        imageImport->SetNumberOfScalarComponents( 4 );
        imageImport->CopyImportVoidPointer( pData, width * height * 4 );

        imageData = vtkSmartPointer<vtkImageData>::New();
        imageImport->Update(); //important
        imageData->DeepCopy( imageImport->GetOutput() );
    }

    if( imageData != nullptr )
    {
       vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New();
       texture->SetInputData( imageData );
       myActor->SetTexture( texture );
    }
}

请注意,id 没有测试此代码,但它应该可以工作。您需要在深度复制之前进行更新,以便 ImageImport 真正完成其工作。

关于c++ - 如何使用 vtkImageImport 创建在删除 vtkImageImport 后仍然存在的 vtkImageData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45798162/

相关文章:

android - 在 NDK r17c 上将 VTK 与 ndk-build 链接会产生 'undefined references' 错误

c++ - 如何正确地从函数中给出 vector (type_traits)

c++ - 在 C++ 中将命令行参数作为函数调用的简单方法?

c - Solaris 上的 'p' 的存储大小未知 (sys/procfs.h struct psinfo p) 错误

c++ - 来自 OpenCV 的 VTK 相机姿势来自 solvePnP 的估计姿势

c++ - 如何自动关闭打开的 vtk 窗口?

c++ - 为什么在使用 MinGW 添加 ltalloc 时会出现段错误

c++ - 测试树是否为二叉搜索树

按位运算中的字符转换

c - do-while 循环只迭代一次月供