]> Creatis software - clitk.git/blob - tools/clitkWriteDicomSeriesGenericFilter.txx
GDCM 1.x compatibility
[clitk.git] / tools / clitkWriteDicomSeriesGenericFilter.txx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to:
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17 ===========================================================================**/
18 #ifndef clitkWriteDicomSeriesGenericFilter_txx
19 #define clitkWriteDicomSeriesGenericFilter_txx
20
21 /* =================================================
22  * @file   clitkWriteDicomSeriesGenericFilter.txx
23  * @author
24  * @date
25  *
26  * @brief
27  *
28  ===================================================*/
29
30 // clitk
31 #include "clitkResampleImageWithOptionsFilter.h"
32 #if GDCM_MAJOR_VERSION >= 2
33 #include "gdcmUIDGenerator.h"
34 #else
35 #include "gdcmFile.h"
36 #include "gdcmUtil.h"
37 #endif
38
39
40 namespace clitk
41 {
42
43
44 //-----------------------------------------------------------
45 // Constructor
46 //-----------------------------------------------------------
47 template<class args_info_type>
48 WriteDicomSeriesGenericFilter<args_info_type>::WriteDicomSeriesGenericFilter()
49 {
50   m_Verbose=false;
51   m_InputFileName="";
52 }
53
54
55 //-----------------------------------------------------------
56 // Update
57 //-----------------------------------------------------------
58 template<class args_info_type>
59 void WriteDicomSeriesGenericFilter<args_info_type>::Update()
60 {
61   // Read the Dimension and PixelType
62   int Dimension;
63   std::string PixelType;
64   ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType);
65
66
67   // Call UpdateWithDim
68   if(Dimension==2) UpdateWithDim<2>(PixelType);
69   else if(Dimension==3) UpdateWithDim<3>(PixelType);
70   // else if (Dimension==4)UpdateWithDim<4>(PixelType);
71   else {
72     std::cout<<"Error, Only for 2 or 3  Dimensions!!!"<<std::endl ;
73     return;
74   }
75 }
76
77 //-------------------------------------------------------------------
78 // Update with the number of dimensions
79 //-------------------------------------------------------------------
80 template<class args_info_type>
81 template<unsigned int Dimension>
82 void
83 WriteDicomSeriesGenericFilter<args_info_type>::UpdateWithDim(std::string PixelType)
84 {
85   if (m_Verbose) std::cout << "Image was detected to be "<<Dimension<<"D and "<< PixelType<<"..."<<std::endl;
86
87   if(PixelType == "short") {
88     if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed short..." << std::endl;
89     UpdateWithDimAndPixelType<Dimension, signed short>();
90   }
91   else if(PixelType == "unsigned_short"){
92     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl;
93     UpdateWithDimAndPixelType<Dimension, unsigned short>();
94   }
95
96   else if (PixelType == "unsigned_char") {
97     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl;
98     UpdateWithDimAndPixelType<Dimension, unsigned char>();
99   }
100
101   //     else if (PixelType == "char"){
102   //       if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl;
103   //       UpdateWithDimAndPixelType<Dimension, signed char>();
104   //     }
105   else if (PixelType == "double") {
106     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and double..." << std::endl;
107     UpdateWithDimAndPixelType<Dimension, double>();
108   }
109   else {
110     if (m_Verbose) std::cout  << "Launching filter in "<< Dimension <<"D and float..." << std::endl;
111     UpdateWithDimAndPixelType<Dimension, float>();
112   }
113 }
114
115 //-------------------------------------------------------------------
116 // Update with the number of dimensions and the pixeltype read from
117 // the dicom files. The MHD files may be resampled to match the
118 // dicom spacing (and number of slices). Rounding errors in resampling
119 // are handled by removing files when generating the output dicom
120 // series.
121 //-------------------------------------------------------------------
122 template<class args_info_type>
123 template <unsigned int Dimension, class  PixelType>
124 void
125 WriteDicomSeriesGenericFilter<args_info_type>::UpdateWithDimAndPixelType()
126 {
127
128   // ImageTypes
129   typedef itk::Image<PixelType, Dimension> InputImageType;
130   typedef itk::Image<PixelType, 2> OutputImageType;
131
132   // Read the dicom directory
133   typedef itk::ImageSeriesReader< InputImageType >     ReaderType;
134   typedef itk::GDCMImageIO ImageIOType;
135   typedef itk::GDCMSeriesFileNames NamesGeneratorType;
136
137   ImageIOType::Pointer gdcmIO = ImageIOType::New();
138   NamesGeneratorType::Pointer namesGenerator = NamesGeneratorType::New();
139   namesGenerator->SetInputDirectory( m_ArgsInfo.inputDir_arg );
140   namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg  );
141   typename   ReaderType::FileNamesContainer filenames_in = namesGenerator->GetInputFileNames();
142   typename   ReaderType::FileNamesContainer filenames_out;
143
144   // Output the dicom files
145   unsigned int numberOfFilenames =  filenames_in.size();
146   if (m_Verbose) {
147     std::cout << numberOfFilenames <<" were read in the directory "<<m_ArgsInfo.inputDir_arg<<"..."<<std::endl<<std::endl;
148     for(unsigned int fni = 0; fni<numberOfFilenames; fni++) {
149       std::cout << "filename # " << fni << " = ";
150       std::cout << filenames_in[fni] << std::endl;
151     }
152   }
153
154   // Read the series
155   typename ReaderType::Pointer reader = ReaderType::New();
156   reader->SetImageIO( gdcmIO );
157   reader->SetFileNames( filenames_in );
158   try {
159     reader->Update();
160   } catch (itk::ExceptionObject &excp) {
161     std::cerr << "Error: Exception thrown while reading the DICOM series!!" << std::endl;
162     std::cerr << excp << std::endl;
163   }
164
165   // Read the input (MHD file)
166   typedef typename InputImageType::RegionType RegionType;
167   typedef typename RegionType::SizeType SizeType;
168   typedef itk::ImageFileReader<InputImageType> InputReaderType;
169   typename InputReaderType::Pointer volumeReader = InputReaderType::New();
170   volumeReader->SetFileName( m_InputFileName);
171   volumeReader->Update();
172   
173   typename InputImageType::Pointer input = volumeReader->GetOutput();
174   if ((!m_ArgsInfo.useSizeAsReference_flag && (input->GetSpacing() != reader->GetOutput()->GetSpacing())) || 
175       (m_ArgsInfo.useSizeAsReference_flag && (input->GetLargestPossibleRegion().GetSize() != reader->GetOutput()->GetLargestPossibleRegion().GetSize()))) {
176         
177     // resampling is carried out on the fly if resolution or size between 
178     // the input mhd and input dicom series is different
179     
180     // Filter
181     typedef clitk::ResampleImageWithOptionsFilter<InputImageType, InputImageType> ResampleImageFilterType;
182     typename ResampleImageFilterType::Pointer filter = ResampleImageFilterType::New();
183     filter->SetInput(input);
184     filter->SetVerboseOptions(m_Verbose);
185     filter->SetGaussianFilteringEnabled(false);
186     filter->SetDefaultPixelValue(0);
187     
188     if (!m_ArgsInfo.useSizeAsReference_flag) {
189       filter->SetOutputSpacing(reader->GetOutput()->GetSpacing());
190       if (m_Verbose) {
191         std::cout << "Warning: The image spacing differs between the MHD file and the input dicom series. Performing resampling with default options using spacing as reference (for advanced options, use clitkResampleImage)." << std::endl;
192         std::cout << "MHD -> " << input->GetSpacing() << std::endl;
193         std::cout << "dicom -> " << reader->GetOutput()->GetSpacing() << std::endl;
194       }
195     }
196     else {
197       const SizeType& dicom_size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
198       SizeType output_size;
199       for (unsigned int i = 0; i < Dimension; i++)
200         output_size[i] = dicom_size[i];
201       filter->SetOutputSize(output_size);
202       if (m_Verbose) {
203           std::cout << "Warning: The image size differs between the MHD file and the input dicom series. Performing resampling with default options using size as reference (for advanced options, use clitkResampleImage)." << std::endl;
204           std::cout << "MHD -> " << input->GetLargestPossibleRegion().GetSize() << std::endl;
205           std::cout << "dicom -> " << reader->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl;
206       }
207     }
208
209     try {
210       filter->Update();
211       input = filter->GetOutput();
212     } catch( itk::ExceptionObject & excp ) {
213     std::cerr << "Error: Exception thrown while resampling!!" << std::endl;
214     std::cerr << excp << std::endl;
215     }
216   }
217   
218   //    In some cases, due to resampling approximation issues, 
219   //    the number of slices in the MHD file may be different (smaller)
220   //    from the number of files in the template dicom directory. 
221   //    To avoid ITK generating an exception, we reduce the number 
222   //    of DCM files to be considered, and a warning is printed
223   //    in verbose mode
224   const RegionType volumeRegion = input->GetLargestPossibleRegion();
225   const SizeType& volumeSize = volumeRegion.GetSize();
226   if (m_Verbose) {
227     std::cout << volumeRegion << volumeSize << std::endl;
228   }
229   if (Dimension == 3 && volumeSize[2] < numberOfFilenames) {
230     if (m_Verbose)
231       std::cout << "Warning: The number of files in " << m_ArgsInfo.inputDir_arg << " (" << filenames_in.size() << " files) is greater than the number of slices in MHD (" << volumeSize[2] << " slices). Using only " << volumeSize[2] << " files." << std::endl;
232     
233     filenames_in.resize(volumeSize[2]);
234     filenames_out.resize(filenames_in.size());
235     numberOfFilenames =  filenames_in.size();
236   }
237
238   // Modify the meta dictionary
239   typedef itk::MetaDataDictionary   DictionaryType;
240   const std::vector<DictionaryType*>* dictionary = reader->GetMetaDataDictionaryArray();
241
242   // Get keys
243   unsigned int numberOfKeysGiven=m_ArgsInfo.key_given;
244     if (m_ArgsInfo.verbose_flag) 
245       DD(numberOfKeysGiven);
246
247   std::string seriesUID;
248   std::string frameOfReferenceUID;
249   std::string studyUID;
250   
251   // one pass through the keys given on the cmd-line, to check what will be recreated
252   std::string seriesUIDkey = "0020|000e";
253   std::string frameOfReferenceUIDKey = "0020|0052";
254   std::string studyUIDKey = "0020|000d";
255   bool seriesUIDGiven = false;
256   bool studyUIDGiven = false;
257   for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
258     std::string entryId( m_ArgsInfo.key_arg[i] );
259     if (m_ArgsInfo.verbose_flag) 
260       DD(entryId);
261     
262     seriesUIDGiven = (entryId ==  seriesUIDkey || entryId ==  frameOfReferenceUIDKey);
263     studyUIDGiven = (entryId == studyUIDKey);
264   }
265
266   // force the creation of a new series if a new study was specified
267   if (!studyUIDGiven && m_ArgsInfo.newStudyUID_flag) {
268     m_ArgsInfo.newSeriesUID_flag = true;
269 #if GDCM_MAJOR_VERSION >= 2
270     gdcm::UIDGenerator suid;
271     studyUID = suid.Generate();
272 #else
273     studyUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
274 #endif
275   }
276     
277   if (!seriesUIDGiven && m_ArgsInfo.newSeriesUID_flag) {
278 #if GDCM_MAJOR_VERSION >= 2
279     gdcm::UIDGenerator suid;
280     seriesUID = suid.Generate();
281     gdcm::UIDGenerator fuid;
282     frameOfReferenceUID = fuid.Generate();
283 #else
284     seriesUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
285     frameOfReferenceUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
286 #endif
287   }
288
289   if (m_ArgsInfo.verbose_flag) {
290     DD(seriesUID);
291     DD(frameOfReferenceUID);
292     DD(studyUID);
293   }
294
295   // check if file UIDs will be be preserved
296   bool useInputFileUID = true;
297   if (m_ArgsInfo.newSeriesUID_flag || m_ArgsInfo.newStudyUID_flag || seriesUIDGiven || studyUIDGiven) {
298     useInputFileUID = false;
299 #if GDCM_MAJOR_VERSION < 2
300     gdcmIO->SetKeepOriginalUID(true);
301 #endif
302   }
303   else {
304     namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg  );
305     filenames_out = namesGenerator->GetOutputFileNames();
306   }
307   
308   filenames_out.resize(numberOfFilenames);
309   
310   // update output dicom keys/tags
311   for(unsigned int fni = 0; fni<numberOfFilenames; fni++) {
312     for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
313       std::string entryId(m_ArgsInfo.key_arg[i]  );
314       std::string value( m_ArgsInfo.tag_arg[i] );
315
316       itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), entryId, value );
317     }
318
319     // 
320     if (!seriesUIDGiven) {
321       if (m_ArgsInfo.newSeriesUID_flag) {
322         itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), seriesUIDkey, seriesUID );
323         itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), frameOfReferenceUIDKey, frameOfReferenceUID );
324       }
325     }
326     
327     if (!studyUIDGiven) {
328       if (m_ArgsInfo.newStudyUID_flag) 
329         itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), studyUIDKey, studyUID );
330     }
331
332     // file UIDs are recreated for new studies or series
333     if (!useInputFileUID)
334     {
335       std::string fileUID;
336 #if GDCM_MAJOR_VERSION >= 2
337       gdcm::UIDGenerator fid;
338       fileUID = fid.Generate();
339 #else
340       fileUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
341 #endif
342       itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0018", fileUID );
343       itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0002|0003", fileUID );
344       filenames_out[fni] = itksys::SystemTools::CollapseFullPath(fileUID.c_str(), m_ArgsInfo.outputDir_arg) + std::string(".dcm"); 
345     }
346   }
347   
348   // Output directory and filenames
349   itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist
350   typedef itk::ImageSeriesWriter<InputImageType, OutputImageType >  SeriesWriterType;
351   typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New();
352
353   seriesWriter->SetInput( input );
354   seriesWriter->SetImageIO( gdcmIO );
355   
356   seriesWriter->SetFileNames( filenames_out );
357   seriesWriter->SetMetaDataDictionaryArray( dictionary );
358
359   // Write
360   try {
361     seriesWriter->Update();
362   } catch( itk::ExceptionObject & excp ) {
363     std::cerr << "Error: Exception thrown while writing the series!!" << std::endl;
364     std::cerr << excp << std::endl;
365   }
366
367 }
368
369 /*
370 //-------------------------------------------------------------------
371 // Update with the number of dimensions and the pixeltype
372 //-------------------------------------------------------------------
373 template<class args_info_type>
374 template <unsigned int Dimension, class  PixelType>
375 void
376 WriteDicomSeriesGenericFilter<args_info_type>::UpdateWithDimAndPixelType()
377 {
378
379   // ImageTypes
380   typedef itk::Image<PixelType, Dimension> InputImageType;
381   typedef itk::Image<PixelType, 2> OutputImageType;
382
383   // Read the input (volumetric)
384   typedef itk::ImageFileReader<InputImageType> InputReaderType;
385   typename InputReaderType::Pointer volumeReader = InputReaderType::New();
386   volumeReader->SetFileName( m_InputFileName);
387   volumeReader->Update();
388   typename InputImageType::Pointer input= volumeReader->GetOutput();
389
390   // Read the dicom directory
391   typedef itk::ImageSeriesReader< InputImageType >     ReaderType;
392   typedef itk::GDCMImageIO ImageIOType;
393   typedef itk::GDCMSeriesFileNames NamesGeneratorType;
394
395   ImageIOType::Pointer gdcmIO = ImageIOType::New();
396   NamesGeneratorType::Pointer namesGenerator = NamesGeneratorType::New();
397   namesGenerator->SetInputDirectory( m_ArgsInfo.inputDir_arg );
398   namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg  );
399   typename   ReaderType::FileNamesContainer filenames_in = namesGenerator->GetInputFileNames();
400   typename   ReaderType::FileNamesContainer filenames_out = namesGenerator->GetOutputFileNames();
401
402   // Output the dicom files
403   unsigned int numberOfFilenames =  filenames_in.size();
404   if (m_Verbose) {
405     std::cout << numberOfFilenames <<" were read in the directory "<<m_ArgsInfo.inputDir_arg<<"..."<<std::endl<<std::endl;
406     for(unsigned int fni = 0; fni<numberOfFilenames; fni++) {
407       std::cout << "filename # " << fni << " = ";
408       std::cout << filenames_in[fni] << std::endl;
409     }
410   }
411   
412   // RP: 16/03/2011
413   //    In some cases, due to resampling approximation issues, 
414   //    the number of slices in the MHD file may be different 
415   //    from the number of slices in the template DCM directory. 
416   //    To avoid ITK generating an exception, we reduce the number 
417   //    of DCM files to be considered, provided the --force
418   //    option is set.
419   typedef typename InputImageType::RegionType RegionType;
420   typedef typename RegionType::SizeType SizeType;
421   const RegionType volumeRegion = input->GetLargestPossibleRegion();
422   const SizeType& volumeSize = volumeRegion.GetSize();
423   if (m_ArgsInfo.force_given && Dimension == 3 && volumeSize[2] < numberOfFilenames)
424   {
425     std::cout << "Warning: Number of files in " << m_ArgsInfo.inputDir_arg << " is greater than the number of slices in MHD. Using only " << volumeSize[2] << " files." << std::endl;
426     filenames_in.resize(volumeSize[2]);
427     filenames_out.resize(filenames_in.size());
428     numberOfFilenames =  filenames_in.size();
429   }
430
431   // Read the series
432   typename ReaderType::Pointer reader = ReaderType::New();
433   reader->SetImageIO( gdcmIO );
434   reader->SetFileNames( filenames_in );
435   try {
436     reader->Update();
437   } catch (itk::ExceptionObject &excp) {
438     std::cerr << "Error: Exception thrown while reading the DICOM series!!" << std::endl;
439     std::cerr << excp << std::endl;
440   }
441
442
443   // Modify the meta dictionary
444   typedef itk::MetaDataDictionary   DictionaryType;
445   const std::vector<DictionaryType*>* dictionary = reader->GetMetaDataDictionaryArray();
446
447   // Get keys
448   unsigned int numberOfKeysGiven=0;
449   if(m_ArgsInfo.midP_flag && m_ArgsInfo.key_given)
450     std::cerr<<"Error: both keys and midP option are given"<<std::endl;
451   else if (m_ArgsInfo.midP_flag)
452     numberOfKeysGiven=1;
453   else
454     numberOfKeysGiven=m_ArgsInfo.key_given;
455
456   for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
457     std::string entryId(m_ArgsInfo.key_arg[i]  );
458     std::string value( m_ArgsInfo.tag_arg[i] );
459     for(unsigned int fni = 0; fni<numberOfFilenames; fni++)
460       itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), entryId, value );
461   }
462
463   // Output directory and filenames
464   itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist
465   typedef itk::ImageSeriesWriter<InputImageType, OutputImageType >  SeriesWriterType;
466   typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New();
467
468   seriesWriter->SetInput( volumeReader->GetOutput() );
469   seriesWriter->SetImageIO( gdcmIO );
470   
471   seriesWriter->SetFileNames( filenames_out );
472   seriesWriter->SetMetaDataDictionaryArray( dictionary );
473
474   // Write
475   try {
476     seriesWriter->Update();
477   } catch( itk::ExceptionObject & excp ) {
478     std::cerr << "Error: Exception thrown while writing the series!!" << std::endl;
479     std::cerr << excp << std::endl;
480   }
481
482 }
483 */
484
485 }//end clitk
486
487 #endif //#define clitkWriteDicomSeriesGenericFilter_txx