[Insight-users] Reading MINC1 and MINC2 and then converting them to VTK for image visualization

Luis Ibanez luis.ibanez at kitware.com
Thu Sep 24 12:51:41 EDT 2009


Hi Ricardo,

A segmentation fault is an indication that you are using pointers
for accessing unallocated regions of memory.

Please run your program in a Debugger and report to the list the
line of code in which the debugger finds the segmentation fault.


     Thanks


        Luis


-----------------------
Ricardo Ferrari wrote:
> Dear All,
> 
> I am working in a project which requires to read images in MINC1 and 
> MINC2 formats. For that I have coded a few template functions that I 
> have copied bellow. The program compiles and links without any problem. 
> However, when I try to run it gives segmentation fault (please see bellow).
> 
> "ImageDataMINC2.mnc" is the MINC image file downloaded from 
> http://www.insight-journal.org/browse/publication/64
> 
> Could anybody please pointed out or provide any indication on what I am 
> doing wrong?
> 
> Thank you very much,
> Ricardo
> 
> 
> 
> 
> ----------------------- Output result ------------------------------
> 
> ferrari at ferrari-workstation:~/Workspace/MIP_PROJECTS$ bin/bin/iotests
> Image (0x15c41f0)
>   RTTI typeinfo:   itk::Image<short, 3u>
>   Reference Count: 2
>   Modified Time: 48
>   Debug: Off
>   Observers:
>     none
>   Source: (none)
>   Source output index:  0
>   Release Data: Off
>   Data Released: False
>   Global Release Data: Off
>   PipelineMTime: 12
>   UpdateMTime: 47
>   LargestPossibleRegion:
>     Dimension: 3
>     Index: [0, 0, 0]
>     Size: [203, 296, 147]
>   BufferedRegion:
>     Dimension: 3
>     Index: [0, 0, 0]
>     Size: [203, 296, 147]
>   RequestedRegion:
>     Dimension: 3
>     Index: [0, 0, 0]
>     Size: [203, 296, 147]
>   Spacing: [0.06, 0.06, 0.06]
>   Origin: [-6.07, -11.243, -2.2]
>   Direction:
> 1 0 0
> 0 1 0
> 0 0 1
> 
>   IndexToPointMatrix:
>   0.06 0 0
> 0 0.06 0
> 0 0 0.06
> 
>   PointToIndexMatrix:
>   16.6667 0 0
> 0 16.6667 0
> 0 0 16.6667
> 
>   PixelContainer:
>     ImportImageContainer (0x15be750)
>       RTTI typeinfo:   itk::ImportImageContainer<unsigned long, short>
>       Reference Count: 1
>       Modified Time: 44
>       Debug: Off
>       Observers:
>         none
>       Pointer: 0x7ff3d2e32010
>       Container manages memory: true
>       Size: 8832936
>       Capacity: 8832936
> 
> Segmentation fault
> ferrari at ferrari-workstation:~/Workspace/MIP_PROJECTS$
> 
> 
> 
> 
> 
> ------------------------ File main.cpp ---------------------------
> 
> 
> #include "io.h"
> 
> #include "wxVTKRenderWindowInteractor.h"
> #include "vtkCamera.h"
> #include "vtkRenderer.h"
> #include "vtkRenderWindow.h"
> #include "vtkConeSource.h"
> #include "vtkPolyDataMapper.h"
> #include "vtkActor.h"
> #include "vtkPolyDataReader.h"
> 
> #include "vtkPNGReader.h"
> #include "vtkImageMapper.h"
> #include "vtkImageShiftScale.h"
> #include "vtkInteractorStyleImage.h"
> #include "vtkActor2D.h"
> 
> #include "vtkImageViewer2.h"
> #include "vtkImageData.h"
> #include "vtkTesting.h"
> #include "vtkTestUtilities.h"
> 
> 
> 
> 
> /// Pixel type definition
> typedef signed short                     PixelType;
> 
> /// Define type of the input and output images
> typedef itk::Image< PixelType, 3 >         ImageType;
> 
> 
> 
> using namespace std;
> 
> 
> 
> class MyApp;
> class MyFrame;
> 
> // Define a new application type, each program should derive a class 
> from wxApp
> class MyApp : public wxApp
> {
> public:
>     // this one is called on application startup and is a good place for 
> the app
>     // initialization (doing it here and not in the ctor allows to have 
> an error
>     // return: if OnInit() returns false, the application terminates)
>     virtual bool OnInit();
> };
> 
> // Define a new frame type: this is going to be our main frame
> class MyFrame : public wxFrame
> {
> public:
>     // ctor(s)
>     MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
>     ~MyFrame();
> 
>     // event handlers (these functions should _not_ be virtual)
>     void OnQuit(wxCommandEvent& event);
>     void OnAbout(wxCommandEvent& event);
> 
> protected:
>     void ConstructVTK();
>     void ConfigureVTK();
>     void DestroyVTK();
> 
> private:
>   wxVTKRenderWindowInteractor *m_pVTKWindow;
> 
>   // vtk classes
>   vtkRenderer       *pRenderer;
>   vtkRenderWindow   *pRenderWindow;
>   vtkPolyDataMapper *pConeMapper;
>   vtkActor          *pConeActor;
>   vtkConeSource     *pConeSource;
>   vtkImageViewer2   *viewer;
>   vtkPNGReader      *reader;
> 
> private:
>     // any class wishing to process wxWindows events must use this macro
>     DECLARE_EVENT_TABLE()
> };
> 
> // IDs for the controls and the menu commands
> enum
> {
>     // menu items
>     Minimal_Quit = 1,
>     Minimal_About
> };
> 
> #define MY_FRAME      101
> #define MY_VTK_WINDOW 102
> 
> // the event tables connect the wxWindows events with the functions (event
> // handlers) which process them. It can be also done at run-time, but 
> for the
> // simple menu events like this the static method is much simpler.
> BEGIN_EVENT_TABLE(MyFrame, wxFrame)
>     EVT_MENU(Minimal_Quit,  MyFrame::OnQuit)
>     EVT_MENU(Minimal_About, MyFrame::OnAbout)
> END_EVENT_TABLE()
> 
> // Create a new application object: this macro will allow wxWindows to 
> create
> // the application object during program execution (it's better than using a
> // static object for many reasons) and also declares the accessor function
> // wxGetApp() which will return the reference of the right type (i.e. 
> MyApp and
> // not wxApp)
> IMPLEMENT_APP(MyApp)
> 
> // 'Main program' equivalent: the program execution "starts" here
> bool MyApp::OnInit()
> {
>     // create the main application window
>     MyFrame *frame = new MyFrame(_T("wxWindows-VTK App"),
>                                  wxPoint(50, 50), wxSize(450, 340));
> 
>     // and show it (the frames, unlike simple controls, are not shown when
>     // created initially)
>     frame->Show(TRUE);
> 
>     // success: wxApp::OnRun() will be called which will enter the main 
> message
>     // loop and the application will run. If we returned FALSE here, the
>     // application would exit immediately.
>     return TRUE;
> }
> 
> // frame constructor
> MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const 
> wxSize& size)
>        : wxFrame((wxFrame *)NULL, -1, title, pos, size)
> {
> #ifdef __WXMAC__
>     // we need this in order to allow the about menu relocation, since 
> ABOUT is
>     // not the default id of the about menu
>     wxApp::s_macAboutMenuItemId = Minimal_About;
> #endif
> 
>     // create a menu bar
>     wxMenu *menuFile = new wxMenu(_T(""), wxMENU_TEAROFF);
> 
>     // the "About" item should be in the help menu
>     wxMenu *helpMenu = new wxMenu;
>     helpMenu->Append(Minimal_About, _T("&About...\tCtrl-A"), _T("Show 
> about dialog"));
> 
>     menuFile->Append(Minimal_Quit, _T("E&xit\tAlt-X"), _T("Quit this 
> program"));
> 
>     // now append the freshly created menu to the menu bar...
>     wxMenuBar *menuBar = new wxMenuBar();
>     menuBar->Append(menuFile, _T("&File"));
>     menuBar->Append(helpMenu, _T("&Help"));
> 
>     // ... and attach this menu bar to the frame
>     SetMenuBar(menuBar);
> 
> #if wxUSE_STATUSBAR
>     // create a status bar just for fun (by default with 1 pane only)
>     CreateStatusBar(2);
>     SetStatusText(_T("Drag the mouse here! (wxWindows 2.4.0)"));
> #endif // wxUSE_STATUSBAR
> 
>     m_pVTKWindow = new wxVTKRenderWindowInteractor(this, MY_VTK_WINDOW);
>     //turn on mouse grabbing if possible
>     m_pVTKWindow->UseCaptureMouseOn();
>     ConstructVTK();
>     ConfigureVTK();
> }
> 
> MyFrame::~MyFrame()
> {
>   if(m_pVTKWindow) m_pVTKWindow->Delete();
>   DestroyVTK();
> }
> 
> void MyFrame::ConstructVTK()
> {
>   viewer = vtkImageViewer2::New();
> }
> 
> void MyFrame::ConfigureVTK()
> {
>     string inputFileName = "ImageDataMINC2.mnc";
> 
>     ImageType::Pointer itkImage1 = ReadMinc2Image< ImageType >( 
> inputFileName );
> 
>     cout << itkImage1 << endl;
> 
>     vtkImageData *vtkImage = ConvertItkToVtk< ImageType >( itkImage1 );
> 
>     viewer->SetInput( vtkImage );
> 
> //    vtkMINCImageReader *reader = vtkMINCImageReader::New();
> //    reader->SetFileName( inputFileName.c_str() );
> //  reader->Update();
> //    viewer->SetInput ( reader->GetOutput() );
> 
>     viewer->SetColorWindow ( 150 );
>     viewer->SetColorLevel ( 170 );
> 
>     //Call vtkImageViewer2::SetInput before
>     viewer->SetupInteractor (  m_pVTKWindow );
> }
> 
> void MyFrame::DestroyVTK()
> {
>   if (viewer != 0)
>     viewer->Delete();
> }
> 
> // event handlers
> 
> void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
> {
>     // TRUE is to force the frame to close
>     Close(TRUE);
> }
> 
> void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
> {
>     wxString msg;
>     msg.Printf( _T("This is the about dialog of wx-vtk sample.\n"));
> 
>     wxMessageBox(msg, _T("About wx-vtk"), wxOK | wxICON_INFORMATION, this);
> }
> 
> 
> 
> 
> 
> 
> 
> ------------------------- FILE  io.h ----------------------------
> 
> #ifndef __MIP_IO_H__
> #define __MIP_IO_H__
> 
> #include <iostream>
> 
> #include "itkImage.h"
> #include "itkImageIOFactory.h"
> #include "itkMINC2ImageIOFactory.h"
> #include "itkMINC2ImageIO.h"
> #include "itkCastImageFilter.h"
> #include "itkVTKImageToImageFilter.h"
> #include "itkImageToVTKImageFilter.h"
> #include "itkImageFileReader.h"
> #include "itkImageFileWriter.h"
> #include "itkCastImageFilter.h"
> #include "itkVTKImageExport.h"
> #include "itkGDCMImageIO.h"
> #include "itkVTKImageIO.h"
> #include "itkAnalyzeImageIO.h"
> #include "itkVTKImageExport.h"
> #include "itkVTKImageImport.h"
> 
> #include "vtkImageData.h"
> #include "vtkMINCImageReader.h"
> #include "vtkMINCImageWriter.h"
> #include "vtkImageReader.h"
> #include "vtkImageWriter.h"
> #include "vtkSmartPointer.h"
> 
> 
> /// 
> ************************************************************************************************************
> /// This function will connect the given itk::VTKImageExport filter to 
> the given vtkImageImport filter.
> /// 
> ************************************************************************************************************
> template <typename ITK_Exporter, typename VTK_Importer>
> void ConnectPipelines( ITK_Exporter exporter, VTK_Importer* importer )
> {
>     importer->SetUpdateInformationCallback( 
> exporter->GetUpdateInformationCallback() );
>     importer->SetPipelineModifiedCallback( 
> exporter->GetPipelineModifiedCallback() );
>     importer->SetWholeExtentCallback( exporter->GetWholeExtentCallback() );
>     importer->SetSpacingCallback( exporter->GetSpacingCallback() );
>     importer->SetOriginCallback( exporter->GetOriginCallback() );
>     importer->SetScalarTypeCallback( exporter->GetScalarTypeCallback() );
>     importer->SetNumberOfComponentsCallback( 
> exporter->GetNumberOfComponentsCallback() );
>     importer->SetPropagateUpdateExtentCallback( 
> exporter->GetPropagateUpdateExtentCallback() );
>     importer->SetUpdateDataCallback( exporter->GetUpdateDataCallback() );
>     importer->SetDataExtentCallback( exporter->GetDataExtentCallback() );
>     importer->SetBufferPointerCallback( 
> exporter->GetBufferPointerCallback() );
>     importer->SetCallbackUserData( exporter->GetCallbackUserData() );
> }
> 
> /// 
> ************************************************************************************************************
> /// This function will connect the given vtkImageExport filter to the 
> given itk::VTKImageImport filter.
> /// 
> ************************************************************************************************************
> template <typename VTK_Exporter, typename ITK_Importer>
> void ConnectPipelines( VTK_Exporter* exporter, ITK_Importer importer )
> {
>     importer->SetUpdateInformationCallback( 
> exporter->GetUpdateInformationCallback() );
>     importer->SetPipelineModifiedCallback( 
> exporter->GetPipelineModifiedCallback() );
>     importer->SetWholeExtentCallback( exporter->GetWholeExtentCallback() );
>     importer->SetSpacingCallback( exporter->GetSpacingCallback() );
>     importer->SetOriginCallback( exporter->GetOriginCallback() );
>     importer->SetScalarTypeCallback( exporter->GetScalarTypeCallback() );
>     importer->SetNumberOfComponentsCallback( 
> exporter->GetNumberOfComponentsCallback() );
>     importer->SetPropagateUpdateExtentCallback( 
> exporter->GetPropagateUpdateExtentCallback() );
>     importer->SetUpdateDataCallback( exporter->GetUpdateDataCallback() );
>     importer->SetDataExtentCallback( exporter->GetDataExtentCallback() );
>     importer->SetBufferPointerCallback( 
> exporter->GetBufferPointerCallback() );
>     importer->SetCallbackUserData( exporter->GetCallbackUserData() );
> }
> 
> /// 
> ************************************************************************************************************
> ///
> /// 
> ************************************************************************************************************
> template< typename InputImageType >
> typename InputImageType::Pointer ConvertVtkToItk( vtkImageData *img )
> {
>     vtkImageExport* vtkExporter = vtkImageExport::New();
>     vtkExporter->SetInput( img );
> 
>     typedef itk::VTKImageImport< InputImageType > ImageImportType;
>     typename ImageImportType::Pointer itkImporter = ImageImportType::New();
>     ConnectPipelines( vtkExporter, itkImporter );
> 
>     itkImporter->Update();
>     return itkImporter->GetOutput();
> }
> 
> /// 
> ************************************************************************************************************
> ///
> /// 
> ************************************************************************************************************
> template< typename TImageType >
> typename TImageType::Pointer ReadMinc1Image( const std::string fileName )
> {
>     vtkMINCImageReader *reader = vtkMINCImageReader::New();
>     reader->SetFileName( fileName.c_str() );
> 
>     try
>     {
>         reader->Update();
>     }
>     catch ( itk::ExceptionObject & err )
>     {
>         std::cout << "Caught an exception: " << std::endl;
>         std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl;
>         throw err;
>     }
>     catch (... )
>     {
>         std::cout << "Error while reading in image" << fileName << 
> std::endl;
>         throw;
>     }
> 
>     return ConvertVtkToItk< TImageType >( reader->GetOutput() );
> }
> 
> /// 
> ************************************************************************************************************
> ///
> /// 
> ************************************************************************************************************
> template< typename TImageType >
> typename TImageType::Pointer ReadMinc2Image( const std::string fileName )
> {
>     typedef itk::ImageFileReader< TImageType >    ImageFileReader;
>     typedef itk::MINC2ImageIO ImageIOType;
>     ImageIOType::Pointer minc2ImageIO = ImageIOType::New();
>     typename ImageFileReader::Pointer reader = ImageFileReader::New();
>     reader->SetFileName( fileName );
>     reader->SetImageIO( minc2ImageIO );
> 
>     try
>     {
>         reader->Update();
>     }
>     catch ( itk::ExceptionObject & err )
>     {
>         std::cout << "Caught an exception: " << std::endl;
>         std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl;
>         throw err;
>     }
>     catch (... )
>     {
>         std::cout << "Error while reading in image" << fileName << 
> std::endl;
>         throw;
>     }
> 
>     return reader->GetOutput();
> }
> 
> 
> #endif
> 
> 
> ------------------------- File CMakeLists.txt __________________________
> 
> 
> CMAKE_MINIMUM_REQUIRED(VERSION 2.7)
> 
> SET( ProgramName "iotests" )
> 
> PROJECT( ${ProgramName} )
> 
> FIND_PACKAGE (ITK REQUIRED)
> IF (ITK_FOUND)
>     INCLUDE( ${USE_ITK_FILE} )
>     SET(ITK_LIBRARIES ITKCommon ITKBasicFilters ITKIO ITKIOMINC2 
> ITKMetaIO ITKNumerics ITKStatistics)
> ENDIF(ITK_FOUND)
> 
> FIND_PACKAGE (VTK REQUIRED)
> IF (VTK_FOUND)
>     INCLUDE( ${USE_VTK_FILE} )
>     SET(VTK_LIBRARIES vtkRendering vtkGraphics vtkWidgets vtkHybrid 
> vtkImaging vtkIO vtkFiltering vtkCommon)
> ENDIF( VTK_FOUND)
> 
> #
> # The following allows you to access wxGLCanvas for GTK
> #
> IF(WIN32)
>     SET( GUI_EXECUTABLE WIN32 )
> ELSE(WIN32)
>       IF(APPLE)
>         SET( GUI_EXECUTABLE MACOSX_BUNDLE )
>         IF(VTK_USE_COCOA)
>               SET_SOURCE_FILES_PROPERTIES( 
> wxVtkWidgets/wxVTKRenderWindowInteractor.cxx PROPERTIES COMPILE_FLAGS 
> "-ObjC++" )
>         ENDIF(VTK_USE_COCOA)
>       ELSE(APPLE)
>         #
>         # CMake 2.6: technically those packages are not required since 
> one can still use the Motif/X11 version and not the gtk one:
>         #
>         FIND_PACKAGE(PkgConfig REQUIRED)
>         pkg_check_modules (GTK2 gtk+-2.0)
>         INCLUDE_DIRECTORIES(${GTK2_INCLUDE_DIRS})
>         LINK_LIBRARIES(${GTK2_LIBRARIES})
>        
>         #
>         # Can I require all my user to have the gl lib on linux, even if 
> they do not really need it...
>         #
>         SET( WXGLCANVASLIBS "gl" )
>       ENDIF(APPLE)
> ENDIF(WIN32)
> 
> 
> #
> # wxWidgets is required to build the project
> #
> # For GTK we need a couple of stuff:
> #     gl: GLCanvas
> #     adv: wxSashLayoutWindow and such...
> #
> FIND_PACKAGE( wxWidgets COMPONENTS base core adv ${WXGLCANVASLIBS} 
> REQUIRED )
> IF(wxWidgets_FOUND)
>     INCLUDE(${wxWidgets_USE_FILE})
> ENDIF(wxWidgets_FOUND)
> 
> INCLUDE_DIRECTORIES(
>     ${CMAKE_CURRENT_SOURCE_DIR}
>     ${CMAKE_CURRENT_SOURCE_DIR}/../itkVtk 
>                   #
>                   # itkVtk folder contains the followin files:
>                   #
>                   # itkImageToVTKImageFilter.h  
> itkImageToVTKImageFilter.txx
>                   # itkVTKImageToImageFilter.h  itkVTKImageToImageFilter.txx
> )
> 
> SET( SRCS
>     
> ${CMAKE_CURRENT_SOURCE_DIR}/../../viewer/wxVtkWidgets/wxVTKRenderWindowInteractor.cxx
> )
> 
> ADD_EXECUTABLE( ${ProgramName}
>     main.cpp
>     ${SRCS}
> )
> 
> TARGET_LINK_LIBRARIES( ${ProgramName}
>        ${VTK_LIBRARIES}
>        ${ITK_LIBRARIES}
>        ${wxWidgets_LIBRARIES}      
> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _____________________________________
> Powered by www.kitware.com
> 
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
> 
> Please keep messages on-topic and check the ITK FAQ at: http://www.itk.org/Wiki/ITK_FAQ
> 
> Follow this link to subscribe/unsubscribe:
> http://www.itk.org/mailman/listinfo/insight-users


More information about the Insight-users mailing list