1 /*=========================================================================
2 Program: vv http://www.creatis.insa-lyon.fr/rio/vv
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
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.
13 It is distributed under dual licence
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
21 /* =================================================
22 * @file clitkWriteDicomSeriesGenericFilter.txx
28 ===================================================*/
31 #include "clitkResampleImageWithOptionsFilter.h"
32 #if GDCM_MAJOR_VERSION >= 2
33 #include "gdcmUIDGenerator.h"
44 //-----------------------------------------------------------
46 //-----------------------------------------------------------
47 template<class args_info_type>
48 WriteDicomSeriesGenericFilter<args_info_type>::WriteDicomSeriesGenericFilter()
55 //-----------------------------------------------------------
57 //-----------------------------------------------------------
58 template<class args_info_type>
59 void WriteDicomSeriesGenericFilter<args_info_type>::Update()
61 // Read the Dimension and PixelType
63 std::string PixelType;
64 ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType);
68 if(Dimension==2) UpdateWithDim<2>(PixelType);
69 else if(Dimension==3) UpdateWithDim<3>(PixelType);
70 // else if (Dimension==4)UpdateWithDim<4>(PixelType);
72 std::cout<<"Error, Only for 2 or 3 Dimensions!!!"<<std::endl ;
77 //-------------------------------------------------------------------
78 // Update with the number of dimensions
79 //-------------------------------------------------------------------
80 template<class args_info_type>
81 template<unsigned int Dimension>
83 WriteDicomSeriesGenericFilter<args_info_type>::UpdateWithDim(std::string PixelType)
85 if (m_Verbose) std::cout << "Image was detected to be "<<Dimension<<"D and "<< PixelType<<"..."<<std::endl;
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>();
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>();
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>();
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>();
105 else if (PixelType == "double") {
106 if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and double..." << std::endl;
107 UpdateWithDimAndPixelType<Dimension, double>();
110 if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl;
111 UpdateWithDimAndPixelType<Dimension, float>();
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
121 //-------------------------------------------------------------------
122 template<class args_info_type>
123 template <unsigned int Dimension, class PixelType>
125 WriteDicomSeriesGenericFilter<args_info_type>::UpdateWithDimAndPixelType()
129 typedef itk::Image<PixelType, Dimension> InputImageType;
130 typedef itk::Image<PixelType, 2> OutputImageType;
132 // Read the dicom directory
133 typedef itk::ImageSeriesReader< InputImageType > ReaderType;
134 typedef itk::GDCMImageIO ImageIOType;
135 typedef itk::GDCMSeriesFileNames NamesGeneratorType;
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 = namesGenerator->GetOutputFileNames();
144 // Output the dicom files
145 unsigned int numberOfFilenames = filenames_in.size();
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;
155 typename ReaderType::Pointer reader = ReaderType::New();
156 reader->SetImageIO( gdcmIO );
157 reader->SetFileNames( filenames_in );
160 } catch (itk::ExceptionObject &excp) {
161 std::cerr << "Error: Exception thrown while reading the DICOM series!!" << std::endl;
162 std::cerr << excp << std::endl;
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();
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()))) {
177 // resampling is carried out on the fly if resolution or size between
178 // the input mhd and input dicom series is different
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);
188 if (!m_ArgsInfo.useSizeAsReference_flag) {
189 filter->SetOutputSpacing(reader->GetOutput()->GetSpacing());
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;
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);
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;
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;
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
224 const RegionType volumeRegion = input->GetLargestPossibleRegion();
225 const SizeType& volumeSize = volumeRegion.GetSize();
227 std::cout << volumeRegion << volumeSize << std::endl;
229 if (Dimension == 3 && volumeSize[2] < numberOfFilenames) {
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;
233 filenames_in.resize(volumeSize[2]);
234 filenames_out.resize(filenames_in.size());
235 numberOfFilenames = filenames_in.size();
238 // Modify the meta dictionary
239 typedef itk::MetaDataDictionary DictionaryType;
240 const std::vector<DictionaryType*>* dictionary = reader->GetMetaDataDictionaryArray();
243 unsigned int numberOfKeysGiven=m_ArgsInfo.key_given;
245 std::string seriesUID;
246 std::string frameOfReferenceUID;
247 std::string studyUID;
249 // one pass through the keys given on the cmd-line, to check what will be recreated
250 std::string seriesUIDkey = "0020|000e";
251 std::string frameOfReferenceUIDKey = "0020|0052";
252 std::string studyUIDKey = "0020|000d";
253 bool seriesUIDGiven = false;
254 bool studyUIDGiven = false;
255 for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
256 std::string entryId( m_ArgsInfo.key_arg[i] );
258 seriesUIDGiven = (entryId == seriesUIDkey || entryId == frameOfReferenceUIDKey);
261 if (entryId == seriesUIDkey)
262 seriesUID = m_ArgsInfo.tag_arg[i];
264 frameOfReferenceUID = m_ArgsInfo.tag_arg[i];
266 else if (m_ArgsInfo.newSeriesUID_flag) {
267 #if GDCM_MAJOR_VERSION >= 2
268 gdcm::UIDGenerator suid;
269 seriesUID = suid.Generate();
270 gdcm::UIDGenerator fuid;
271 frameOfReferenceUID = fuid.Generate();
273 seriesUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
274 frameOfReferenceUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
276 if (m_ArgsInfo.verbose_flag)
279 DD(frameOfReferenceUID);
283 studyUIDGiven = (entryId == studyUIDKey);
285 studyUID = m_ArgsInfo.tag_arg[i];
286 else if (m_ArgsInfo.newStudyUID_flag) {
287 #if GDCM_MAJOR_VERSION >= 2
288 gdcm::UIDGenerator suid;
289 studyUID = suid.Generate();
291 studyUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
293 if (m_ArgsInfo.verbose_flag)
296 #if GDCM_MAJOR_VERSION < 2
297 <<<<<<< Updated upstream
299 gdcmIO->KeepOriginalUID();
302 gdcmIO->SetKeepOriginalUID(true);
303 >>>>>>> Stashed changes
307 // check if file UIDs will be be preserved
308 bool useInputFileUID = true;
309 if (m_ArgsInfo.newSeriesUID_flag || m_ArgsInfo.newStudyUID_flag || seriesUIDGiven || studyUIDGiven)
310 useInputFileUID = false;
312 namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg );
313 filenames_out = namesGenerator->GetOutputFileNames();
316 filenames_out.resize(numberOfFilenames);
318 // update output dicom keys/tags
319 for(unsigned int fni = 0; fni<numberOfFilenames; fni++) {
320 for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
321 std::string entryId(m_ArgsInfo.key_arg[i] );
322 std::string value( m_ArgsInfo.tag_arg[i] );
324 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), entryId, value );
328 if (!seriesUIDGiven) {
329 if (m_ArgsInfo.newSeriesUID_flag) {
330 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), seriesUIDkey, seriesUID );
331 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), frameOfReferenceUIDKey, frameOfReferenceUID );
335 if (!studyUIDGiven) {
336 if (m_ArgsInfo.newStudyUID_flag)
337 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), studyUIDKey, studyUID );
340 // file UIDs are recreated for new studies or series
341 if (!useInputFileUID)
344 #if GDCM_MAJOR_VERSION >= 2
345 gdcm::UIDGenerator fid;
346 fileUID = fid.Generate();
348 fileUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
350 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0018", fileUID );
351 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0002|0003", fileUID );
352 filenames_out[fni] = itksys::SystemTools::CollapseFullPath(fileUID.c_str(), m_ArgsInfo.outputDir_arg) + std::string(".dcm");
356 // Output directory and filenames
357 itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist
358 typedef itk::ImageSeriesWriter<InputImageType, OutputImageType > SeriesWriterType;
359 typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New();
361 seriesWriter->SetInput( input );
362 seriesWriter->SetImageIO( gdcmIO );
364 seriesWriter->SetFileNames( filenames_out );
365 seriesWriter->SetMetaDataDictionaryArray( dictionary );
369 seriesWriter->Update();
370 } catch( itk::ExceptionObject & excp ) {
371 std::cerr << "Error: Exception thrown while writing the series!!" << std::endl;
372 std::cerr << excp << std::endl;
378 //-------------------------------------------------------------------
379 // Update with the number of dimensions and the pixeltype
380 //-------------------------------------------------------------------
381 template<class args_info_type>
382 template <unsigned int Dimension, class PixelType>
384 WriteDicomSeriesGenericFilter<args_info_type>::UpdateWithDimAndPixelType()
388 typedef itk::Image<PixelType, Dimension> InputImageType;
389 typedef itk::Image<PixelType, 2> OutputImageType;
391 // Read the input (volumetric)
392 typedef itk::ImageFileReader<InputImageType> InputReaderType;
393 typename InputReaderType::Pointer volumeReader = InputReaderType::New();
394 volumeReader->SetFileName( m_InputFileName);
395 volumeReader->Update();
396 typename InputImageType::Pointer input= volumeReader->GetOutput();
398 // Read the dicom directory
399 typedef itk::ImageSeriesReader< InputImageType > ReaderType;
400 typedef itk::GDCMImageIO ImageIOType;
401 typedef itk::GDCMSeriesFileNames NamesGeneratorType;
403 ImageIOType::Pointer gdcmIO = ImageIOType::New();
404 NamesGeneratorType::Pointer namesGenerator = NamesGeneratorType::New();
405 namesGenerator->SetInputDirectory( m_ArgsInfo.inputDir_arg );
406 namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg );
407 typename ReaderType::FileNamesContainer filenames_in = namesGenerator->GetInputFileNames();
408 typename ReaderType::FileNamesContainer filenames_out = namesGenerator->GetOutputFileNames();
410 // Output the dicom files
411 unsigned int numberOfFilenames = filenames_in.size();
413 std::cout << numberOfFilenames <<" were read in the directory "<<m_ArgsInfo.inputDir_arg<<"..."<<std::endl<<std::endl;
414 for(unsigned int fni = 0; fni<numberOfFilenames; fni++) {
415 std::cout << "filename # " << fni << " = ";
416 std::cout << filenames_in[fni] << std::endl;
421 // In some cases, due to resampling approximation issues,
422 // the number of slices in the MHD file may be different
423 // from the number of slices in the template DCM directory.
424 // To avoid ITK generating an exception, we reduce the number
425 // of DCM files to be considered, provided the --force
427 typedef typename InputImageType::RegionType RegionType;
428 typedef typename RegionType::SizeType SizeType;
429 const RegionType volumeRegion = input->GetLargestPossibleRegion();
430 const SizeType& volumeSize = volumeRegion.GetSize();
431 if (m_ArgsInfo.force_given && Dimension == 3 && volumeSize[2] < numberOfFilenames)
433 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;
434 filenames_in.resize(volumeSize[2]);
435 filenames_out.resize(filenames_in.size());
436 numberOfFilenames = filenames_in.size();
440 typename ReaderType::Pointer reader = ReaderType::New();
441 reader->SetImageIO( gdcmIO );
442 reader->SetFileNames( filenames_in );
445 } catch (itk::ExceptionObject &excp) {
446 std::cerr << "Error: Exception thrown while reading the DICOM series!!" << std::endl;
447 std::cerr << excp << std::endl;
451 // Modify the meta dictionary
452 typedef itk::MetaDataDictionary DictionaryType;
453 const std::vector<DictionaryType*>* dictionary = reader->GetMetaDataDictionaryArray();
456 unsigned int numberOfKeysGiven=0;
457 if(m_ArgsInfo.midP_flag && m_ArgsInfo.key_given)
458 std::cerr<<"Error: both keys and midP option are given"<<std::endl;
459 else if (m_ArgsInfo.midP_flag)
462 numberOfKeysGiven=m_ArgsInfo.key_given;
464 for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
465 std::string entryId(m_ArgsInfo.key_arg[i] );
466 std::string value( m_ArgsInfo.tag_arg[i] );
467 for(unsigned int fni = 0; fni<numberOfFilenames; fni++)
468 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), entryId, value );
471 // Output directory and filenames
472 itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist
473 typedef itk::ImageSeriesWriter<InputImageType, OutputImageType > SeriesWriterType;
474 typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New();
476 seriesWriter->SetInput( volumeReader->GetOutput() );
477 seriesWriter->SetImageIO( gdcmIO );
479 seriesWriter->SetFileNames( filenames_out );
480 seriesWriter->SetMetaDataDictionaryArray( dictionary );
484 seriesWriter->Update();
485 } catch( itk::ExceptionObject & excp ) {
486 std::cerr << "Error: Exception thrown while writing the series!!" << std::endl;
487 std::cerr << excp << std::endl;
495 #endif //#define clitkWriteDicomSeriesGenericFilter_txx