]> Creatis software - creaImageIO.git/blob - src/creaImageIOWxISimpleDlg.hpp
#3185 creaImageIO Feature New Normal - Clean code
[creaImageIO.git] / src / creaImageIOWxISimpleDlg.hpp
1 /*
2 # ---------------------------------------------------------------------
3 #
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image 
5 #                        pour la Santé)
6 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
9 #
10 #  This software is governed by the CeCILL-B license under French law and 
11 #  abiding by the rules of distribution of free software. You can  use, 
12 #  modify and/ or redistribute the software under the terms of the CeCILL-B 
13 #  license as circulated by CEA, CNRS and INRIA at the following URL 
14 #  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html 
15 #  or in the file LICENSE.txt.
16 #
17 #  As a counterpart to the access to the source code and  rights to copy,
18 #  modify and redistribute granted by the license, users are provided only
19 #  with a limited warranty  and the software's author,  the holder of the
20 #  economic rights,  and the successive licensors  have only  limited
21 #  liability. 
22 #
23 #  The fact that you are presently reading this means that you have had
24 #  knowledge of the CeCILL-B license and that you accept its terms.
25 # ------------------------------------------------------------------------
26 */
27
28
29 #ifndef __creaImageIOWxSimpleDlg_hpp_INCLUDED__
30 #define __creaImageIOWxSimpleDlg_hpp_INCLUDED__
31
32
33 //#include "creaImageIOWxISimpleDlg.h"
34
35 #include "creaImageIOWxGimmickReaderDialog.h"
36 #include <itkAnalyzeImageIO.h>
37 #include <itkImageFileReader.h>
38 #include <itkImageSeriesReader.h>
39 #include <itkImage.h>
40 #include <itkImageSeriesWriter.h>
41 #include <itkGDCMImageIO.h>
42 #include <itkDICOMSeriesFileNames.h>
43 #include <itkNumericSeriesFileNames.h>
44 #include <itkVectorImage.h>
45 #include <itkMetaImageIO.h>
46 #include <itkOrientedImage.h>
47 #include <vtkImageReader2.h>
48 #include <vtkMetaImageReader.h>
49 #include <boost/filesystem/path.hpp>
50 #include <boost/filesystem.hpp>
51 #include <boost/utility.hpp>
52 #include <creaVtkBasicSlicer.h>
53
54 namespace creaImageIO
55 {
56   template <typename TImage2> 
57   typename TImage2::Pointer ReadImage( const std::string &fileName) 
58   { 
59     typename TImage2::Pointer image; 
60
61     typedef itk::ImageFileReader<TImage2> ReaderType; 
62     typename ReaderType::Pointer reader = ReaderType::New(); 
63     reader->SetFileName( fileName.c_str() ); 
64     try 
65       { 
66       reader->Update(); 
67       } 
68     catch( itk::ExceptionObject & err ) 
69       { 
70       std::cout << "Caught an exception reading" << fileName << ": " << std::endl; 
71       std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl; 
72       throw err; 
73       } 
74     catch(...) 
75       { 
76       std::cout << "Error while reading image " << fileName << std::endl; 
77       throw; 
78       } 
79      image = reader->GetOutput(); 
80     
81     return image; 
82   } 
83
84
85   ///Ctor
86   template <typename TImage> 
87    WxISimpleDlg<TImage>::WxISimpleDlg(wxWindow *parent, 
88                                       wxString i_title,  
89                                       const std::string i_namedescp , 
90                                       const std::string i_namedb)
91     : wxDialog(parent, -1,_T("SELECT IMAGE(S)"), wxDefaultPosition, wxSize(230,150))
92    {
93            namedescp = i_namedescp; 
94            namedb    = i_namedb;
95
96        if(!i_title.empty())
97        {
98            this->SetTitle(i_title);
99        }
100        // Button to select file(s)
101        wxButton *fileBut = new wxButton(this, -1,_T("Select a file to display"), wxPoint(10,7) );
102        Connect( fileBut->GetId(), wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &WxISimpleDlg::OnReadFile ); 
103
104        // Button to select directory
105        wxButton *directoryBut = new wxButton(this, -1,_T("Select a directory to display"), wxPoint(10,40) );
106        Connect( directoryBut->GetId(), wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &WxISimpleDlg::OnReadDirectory ); 
107
108        // button to select creaImageIO
109        wxButton *gimmickBut = new wxButton(this, -1,_T("Select Gimmick"), wxPoint(10,70) );
110        Connect( gimmickBut->GetId(), wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &WxISimpleDlg::OnReadGimmick ); 
111
112        /// \TODO  Button to select Bruker directory
113        m_dicom = true;
114        Layout(); 
115     
116     }
117 //////////////////////////////////////////////////////////////////////
118 //                                                                  //
119 //////////////////////////////////////////////////////////////////////
120      template <typename TImage> 
121       void WxISimpleDlg<TImage>::OnReadFile(wxCommandEvent& event)
122       {
123           int resultShowModal;
124           wxFileDialog* fileDlg = new wxFileDialog( 0,  _T("Select file"), _T(""), _T(""), crea::std2wx("*"), wxOPEN |wxFD_MULTIPLE, wxDefaultPosition);
125     
126           resultShowModal = fileDlg->ShowModal();
127           if ( resultShowModal==wxID_OK )
128             {
129                 wxArrayString wxArray;
130                 fileDlg->GetPaths(wxArray);
131                 if(wxArray.size() >0)
132                 {
133                     for( int i = 0; i < wxArray.GetCount(); i++)
134                     {
135                         readImg( crea::wx2std(wxArray[i]));
136                     }
137                 } 
138                 else {
139                     /// \TODO WARNING MESSAGES
140                 }
141             }
142          SetReturnCode( resultShowModal );
143 //       Close();
144          EndModal( resultShowModal );
145       }
146
147
148         template <typename TImage> 
149         void WxISimpleDlg<TImage>::setExts(std::vector<std::string> i_exts)
150         {
151             m_exts = i_exts;
152         }
153 //////////////////////////////////////////////////////////////////////
154 //                                                                  //
155 //////////////////////////////////////////////////////////////////////
156    template <typename TImage> 
157       void WxISimpleDlg<TImage>::OnReadDirectory(wxCommandEvent &event)
158       {
159          int resultShowModal;
160          bool bvalid = false;
161          long style = wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST;
162          wxDirDialog* dirDlg = new wxDirDialog( 0, _T("Select the directory to display"), _T(""), style);
163          
164          resultShowModal = dirDlg->ShowModal();
165          if ( resultShowModal==wxID_OK )
166          {  
167             std::string path = crea::wx2std(dirDlg->GetPath());
168             typedef boost::filesystem::directory_iterator dir_it;
169             dir_it itr(path);
170             dir_it end_itr;
171             /*if (boost::filesystem::exists(path))
172             {*/
173                 for(;itr != end_itr; ++itr)
174                 {
175                        bvalid = m_exts.size() == 0? true : false;
176                        std::vector<std::string>::iterator it = m_exts.begin();
177                        std::string ext = itr->filename().substr(itr->filename().find_last_of("."));
178                        for(; it != m_exts.end(); it++)
179                        {
180                            if(ext == (*it) )
181                            {
182                                bvalid = true;
183                                break;
184                            }
185                        }
186                     if (!boost::filesystem::is_directory(itr->status()) && bvalid)
187                     {
188                         readImg(itr->string().c_str());
189                     }
190                 }
191          }
192          SetReturnCode( resultShowModal );
193 //         Close();
194          EndModal( resultShowModal );
195       }
196
197 //////////////////////////////////////////////////////////////////////
198 //                                                                  //
199 //////////////////////////////////////////////////////////////////////
200             template <typename TImage> 
201       void WxISimpleDlg<TImage>::OnReadGimmick(wxCommandEvent &event)
202       {
203           // Run Gimmick
204            WxGimmickReaderDialog dlg(0,-1, 
205                    namedescp,
206                    namedb, 
207                    _T("Select image(s)        - Gimmick! (c) CREATIS-LRMN 2008"),
208                    wxDefaultPosition,
209                    wxSize(810,750),
210                    GIMMICK_2D_IMAGE_SELECTION,
211                    GIMMICK_3D_IMAGE_SELECTION,
212                    _3D,
213                    1);
214          dlg.ShowModal();
215          if (dlg.GetReturnCode() == wxID_OK)
216          {
217             std::vector<std::string> out;
218             dlg.stopReading();
219             dlg.GetSelectedFiles(out);
220             if(m_dicom)
221             {
222                 readDicomImg( out);
223             }
224             else
225             {
226                 std::vector<std::string>::iterator ii = out.begin();
227                 for (;ii != out.end();ii++)
228                 {
229                     readImg( (*ii).c_str() );
230                 }
231             }
232             dlg.OnExit();
233          }
234          SetReturnCode( dlg.GetReturnCode() );
235 //         Close();
236          EndModal( dlg.GetReturnCode() );
237        }
238
239
240      template <typename TImage> 
241      wxString WxISimpleDlg<TImage>::getInfoImage()
242     {
243         return infoimage;
244     }
245
246
247     //////////////////////////////////////////////////////////////////////
248     // Return the results vector                                        //
249     //////////////////////////////////////////////////////////////////////
250          template <typename TImage>  
251          std::vector<typename TImage::Pointer> WxISimpleDlg<TImage>::getImagesSelected()
252           {
253                   return m_Iresults;
254           }
255
256           template <typename TImage> 
257           void WxISimpleDlg<TImage>::readImg(const std::string &i_name)
258           {
259                     // FCY : just to check but not needed, we hardly suppose that we load only same type and dim of images
260                     // uncomment to test
261                         /*typedef itk::ImageIOBase::IOComponentType ScalarPixelType;
262                         itk::ImageIOBase::Pointer imageIO =  itk::ImageIOFactory::CreateImageIO(i_name.c_str(), itk::ImageIOFactory::ReadMode);
263                     imageIO->SetFileName(i_name.c_str());
264                         imageIO->ReadImageInformation();
265                         ScalarPixelType pixelType = imageIO->GetComponentType();
266                         const size_t dims =  imageIO->GetNumberOfDimensions();*/
267
268                         typedef itk::ImageFileReader<TImage> ReaderType; 
269                     typename ReaderType::Pointer reader = ReaderType::New(); 
270                         reader->SetFileName( i_name ); 
271                         try 
272                         { 
273                                 reader->Update(); 
274                         } 
275                         catch( itk::ExceptionObject & err ) 
276                         { 
277                                 std::cout << "Caught an exception reading" << i_name << ": " << std::endl; 
278                                 std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl; 
279                                 throw err; 
280                         } 
281                         catch(...) 
282                         { 
283                                 std::cout << "Error while reading image " << i_name << std::endl; 
284                                 throw; 
285                         } 
286                         m_Iresults.push_back(reader->GetOutput()); 
287     
288           }
289
290
291
292           template <typename TImage> 
293           void WxISimpleDlg<TImage>::readDicomImg(const std::vector<std::string> &i_names)
294           {
295                   typedef itk::GDCMImageIO GDCMType;
296                   typedef itk::DICOMSeriesFileNames dicnames;
297                   GDCMType::Pointer gdcmIO = GDCMType::New(); 
298                   dicnames::Pointer generator = dicnames::New();
299 //                generator->SetInput(i_names);
300                         typedef itk::ImageSeriesReader<TImage> ReaderType; 
301                     typename ReaderType::Pointer reader = ReaderType::New(); 
302                         reader->SetImageIO(gdcmIO);
303                         reader->SetFileNames(i_names);
304                 //      reader->SetFileName( i_name ); 
305                         try 
306                         { 
307                                 reader->Update(); 
308                         } 
309                         catch( itk::ExceptionObject & err ) 
310                         { 
311                         //      std::cout << "Caught an exception reading" << i_name << ": " << std::endl; 
312                                 std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl; 
313                                 throw err; 
314                         } 
315                         catch(...) 
316                         { 
317                                 //std::cout << "Error while reading image " << i_name << std::endl; 
318                                 throw; 
319                         } 
320                         m_Iresults.push_back(reader->GetOutput()); 
321     
322           }
323
324
325
326
327           template <typename TImage> 
328           void WxISimpleDlg<TImage>::split3Din3Dvtk()
329           {
330                   if ((m_Iresults).size() != 0)
331                   {
332                           typedef itk::ImageToVTKImageFilter<  TImage > ConnectorType;
333                           ConnectorType::Pointer          connector = ConnectorType::New();
334               for(unsigned int i = 0 ;i < m_Iresults.size(); i++)
335                       {
336                                         connector->SetInput(m_Iresults[i]);
337                                         connector->GetImporter()->SetDataScalarTypeToUnsignedChar();
338                                         connector->Update();
339                                         vtkImageData *im = vtkImageData::New();
340                                         im->ShallowCopy(connector->GetOutput());
341                                         im->Update();
342                                         m_Vresults.push_back(im);
343                      }
344                   }
345           }
346
347
348
349           template <typename TImage> 
350           void WxISimpleDlg<TImage>::split4Din3Dvtk(const std::string &i_dir)
351           {
352                         if ((m_Iresults).size() != 0)
353                         {
354                             typename TImage::Pointer image = m_Iresults[0];
355                         
356                                  if(image->GetImageDimension() == 4)
357                                  {
358                                                         boost::any a1(image);
359                                                         m_AnyImages.push_back(a1);
360                                          // size of fourth dimension 
361                                          int dsize = image->GetLargestPossibleRegion().GetSize(3);
362                                          // Output Type
363                                          typedef itk::Image<unsigned char,3> ImageOutputType;  
364                                          typedef itk::ImageSeriesWriter<TImage, ImageOutputType >  SeriesWriterType;
365                                          typedef itk::MetaImageIO MetaImageType;
366                                          MetaImageType::Pointer metaIO;
367                                          SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New();
368                         
369                                          // from JPR file to generate output files
370                                          typedef itk::NumericSeriesFileNames NamesGeneratorType;
371                                          NamesGeneratorType::Pointer namesGenerator = NamesGeneratorType::New();
372                                          namesGenerator->SetStartIndex(0);
373                                          namesGenerator->SetEndIndex(dsize-1); 
374                                          namesGenerator->SetIncrementIndex(1);
375                                          std::string format = i_dir;
376                                          format += "/image%03d.mhd";
377                                          namesGenerator->SetSeriesFormat( format.c_str() );
378                                         
379                                          const std::vector<std::string> names = namesGenerator->GetFileNames();
380                                          seriesWriter->SetFileNames( names );
381                                          seriesWriter->SetInput(image);
382                                          seriesWriter->SetImageIO(metaIO);
383                                          try
384                                         {
385                                                 seriesWriter->Update();
386                                                 vtkMetaImageReader *vReader = vtkMetaImageReader::New();
387                                                 std::vector<std::string>::const_iterator it = names.begin();
388                                                 for( ;it !=  names.end(); ++it)
389                                                 {
390                                                         vReader->SetFileName((*it).c_str());
391                                                         vReader->Update();
392                                                         m_Vresults.push_back(vReader->GetOutput());
393                                                         
394                                                 }
395                                         }
396                                         catch( itk::ExceptionObject & excp )
397                                         {
398                                                 std::cerr << "Exception thrown while writing the series " << std::endl;
399                                                 std::cerr << excp << std::endl;
400                                                 //return EXIT_FAILURE;
401                                         }
402                                  }
403                           }
404
405           }
406
407  }// namespace end
408
409 #endif //__creaImageIOWxSimpleDlg_hpp_INCLUDED__
410