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 clitkGateSimulation2DicomGenericFilter_txx
19 #define clitkGateSimulation2DicomGenericFilter_txx
21 /* =================================================
22 * @file clitkGateSimulation2DicomGenericFilter.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 GateSimulation2DicomGenericFilter<args_info_type>::GateSimulation2DicomGenericFilter()
55 //-----------------------------------------------------------
57 //-----------------------------------------------------------
58 template<class args_info_type>
59 void GateSimulation2DicomGenericFilter<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 GateSimulation2DicomGenericFilter<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 GateSimulation2DicomGenericFilter<args_info_type>::UpdateWithDimAndPixelType()
129 typedef itk::Image<PixelType, Dimension> InputImageType;
130 typedef itk::Image<PixelType, Dimension> 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 if (m_ArgsInfo.preserve_flag) {
157 #if GDCM_MAJOR_VERSION >= 2
158 gdcmIO->LoadPrivateTagsOn();
159 gdcmIO->KeepOriginalUIDOn();
162 reader->SetImageIO( gdcmIO );
163 reader->SetFileNames( filenames_in );
166 } catch (itk::ExceptionObject &excp) {
167 std::cerr << "Error: Exception thrown while reading the DICOM series!!" << std::endl;
168 std::cerr << excp << std::endl;
171 // Read the input (MHD file)
172 typedef typename InputImageType::RegionType RegionType;
173 typedef typename RegionType::SizeType SizeType;
174 typedef itk::ImageFileReader<InputImageType> InputReaderType;
175 typename InputReaderType::Pointer volumeReader = InputReaderType::New();
176 volumeReader->SetFileName( m_InputFileName);
177 volumeReader->Update();
179 typename InputImageType::Pointer input = volumeReader->GetOutput();
180 if ((!m_ArgsInfo.useSizeAsReference_flag && (input->GetSpacing() != reader->GetOutput()->GetSpacing())) ||
181 (m_ArgsInfo.useSizeAsReference_flag && (input->GetLargestPossibleRegion().GetSize() != reader->GetOutput()->GetLargestPossibleRegion().GetSize()))) {
183 // resampling is carried out on the fly if resolution or size between
184 // the input mhd and input dicom series is different
187 typedef clitk::ResampleImageWithOptionsFilter<InputImageType, InputImageType> ResampleImageFilterType;
188 typename ResampleImageFilterType::Pointer filter = ResampleImageFilterType::New();
189 filter->SetInput(input);
190 filter->SetVerboseOptions(m_Verbose);
191 filter->SetGaussianFilteringEnabled(false);
192 filter->SetDefaultPixelValue(0);
194 if (!m_ArgsInfo.useSizeAsReference_flag) {
195 filter->SetOutputSpacing(input->GetSpacing());
197 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;
198 std::cout << "MHD -> " << input->GetSpacing() << std::endl;
199 std::cout << "dicom -> " << reader->GetOutput()->GetSpacing() << std::endl;
203 const SizeType& dicom_size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
204 SizeType output_size;
205 for (unsigned int i = 0; i < Dimension; i++)
206 output_size[i] = dicom_size[i];
207 filter->SetOutputSize(output_size);
209 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;
210 std::cout << "MHD -> " << input->GetLargestPossibleRegion().GetSize() << std::endl;
211 std::cout << "dicom -> " << reader->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl;
217 input = filter->GetOutput();
218 } catch( itk::ExceptionObject & excp ) {
219 std::cerr << "Error: Exception thrown while resampling!!" << std::endl;
220 std::cerr << excp << std::endl;
223 std::cout << "RESAMPING FILTER DONE" << std::endl;
225 // In some cases, due to resampling approximation issues,
226 // the number of slices in the MHD file may be different (smaller)
227 // from the number of files in the template dicom directory.
228 // To avoid ITK generating an exception, we reduce the number
229 // of DCM files to be considered, and a warning is printed
231 const RegionType volumeRegion = input->GetLargestPossibleRegion();
232 const SizeType& volumeSize = volumeRegion.GetSize();
234 std::cout << volumeRegion << volumeSize << std::endl;
236 std::cout << Dimension << volumeSize[2] << numberOfFilenames << std::endl;
237 if (Dimension == 3 && volumeSize[2] < numberOfFilenames) {
239 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;
241 filenames_in.resize(volumeSize[2]);
242 filenames_out.resize(filenames_in.size());
243 numberOfFilenames = filenames_in.size();
246 // Modify the meta dictionary
247 typedef itk::MetaDataDictionary DictionaryType;
248 const std::vector<DictionaryType*>* dictionary = reader->GetMetaDataDictionaryArray();
251 unsigned int numberOfKeysGiven=m_ArgsInfo.key_given;
252 if (m_ArgsInfo.verbose_flag)
253 DD(numberOfKeysGiven);
255 std::string seriesUID;
256 std::string frameOfReferenceUID;
257 std::string studyUID;
259 // one pass through the keys given on the cmd-line, to check what will be recreated
260 std::string seriesUIDkey = "0020|000e";
261 std::string seriesNumberKey = "0020|0011";
262 std::string seriesDescriptionKey = "0008|103e";
263 std::string frameOfReferenceUIDKey = "0020|0052";
264 std::string studyUIDKey = "0020|000d";
265 std::string studyIDKey = "0020|0010";
266 std::string studyDescriptionKey = "0008|1030";
267 bool seriesUIDGiven = false;
268 bool seriesNumberGiven = false;
269 bool seriesDescriptionGiven = false;
270 bool studyUIDGiven = false;
271 bool studyIDGiven = false;
272 bool studyDescriptionGiven = false;
273 for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
274 std::string entryId( m_ArgsInfo.key_arg[i] );
275 if (m_ArgsInfo.verbose_flag)
278 seriesUIDGiven |= (entryId == seriesUIDkey || entryId == frameOfReferenceUIDKey);
279 seriesNumberGiven |= (entryId == seriesNumberKey);
280 seriesDescriptionGiven |= (entryId == seriesDescriptionKey);
281 studyUIDGiven |= (entryId == studyUIDKey);
282 studyIDGiven |= (entryId == studyIDKey);
283 studyDescriptionGiven |= (entryId == studyDescriptionKey);
286 // force the creation of a new series if a new study was specified
287 if (!studyUIDGiven && m_ArgsInfo.newStudyUID_flag) {
288 m_ArgsInfo.newSeriesUID_flag = true;
289 #if GDCM_MAJOR_VERSION >= 2
290 gdcm::UIDGenerator suid;
291 studyUID = suid.Generate();
293 studyUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
297 if (!seriesUIDGiven && m_ArgsInfo.newSeriesUID_flag) {
298 #if GDCM_MAJOR_VERSION >= 2
299 gdcm::UIDGenerator suid;
300 seriesUID = suid.Generate();
301 gdcm::UIDGenerator fuid;
302 frameOfReferenceUID = fuid.Generate();
304 seriesUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
305 frameOfReferenceUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
309 if (m_ArgsInfo.verbose_flag) {
311 DD(frameOfReferenceUID);
315 // check if file UIDs will be be preserved
316 bool useInputFileUID = true;
317 if (m_ArgsInfo.newSeriesUID_flag || m_ArgsInfo.newStudyUID_flag || seriesUIDGiven || studyUIDGiven) {
318 useInputFileUID = false;
321 #if GDCM_MAJOR_VERSION < 2
322 gdcmIO->SetKeepOriginalUID(true);
324 namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg );
327 filenames_out.resize(numberOfFilenames);
331 struct tm* instanceDateTimeTm = localtime(&t);
333 strftime(datetime, 16, "%Y%m%d", instanceDateTimeTm);
334 std::ostringstream instanceDate;
335 instanceDate << datetime;
336 std::ostringstream instanceTime;
337 strftime(datetime, 16, "%H%M%S", instanceDateTimeTm);
338 instanceTime << datetime;
340 // update output dicom keys/tags
341 for(unsigned int fni = 0; fni<numberOfFilenames; fni++) {
342 for (unsigned int i = 0; i < numberOfKeysGiven; i++) {
343 std::string entryId(m_ArgsInfo.key_arg[i] );
344 std::string value( m_ArgsInfo.tag_arg[i] );
346 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), entryId, value );
350 if (!seriesUIDGiven) {
351 if (m_ArgsInfo.newSeriesUID_flag) {
352 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), seriesUIDkey, seriesUID );
353 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), frameOfReferenceUIDKey, frameOfReferenceUID );
358 if (!studyUIDGiven) {
359 if (m_ArgsInfo.newStudyUID_flag)
360 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), studyUIDKey, studyUID );
364 if (studyUIDGiven || m_ArgsInfo.newStudyUID_flag) {
366 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), studyIDKey,itksys::SystemTools::GetFilenameName( m_ArgsInfo.outputDir_arg ));
367 if (!studyDescriptionGiven)
368 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), studyDescriptionKey,itksys::SystemTools::GetFilenameName( m_ArgsInfo.outputDir_arg ));
370 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0020", instanceDate.str() );
371 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0030", instanceTime.str() );
374 // series description/number
375 if (seriesUIDGiven || m_ArgsInfo.newSeriesUID_flag) {
376 if (!seriesDescriptionGiven)
377 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), seriesDescriptionKey, itksys::SystemTools::GetFilenameName(m_ArgsInfo.outputDir_arg) );
378 if (!seriesNumberGiven)
379 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), seriesNumberKey, itksys::SystemTools::GetFilenameName(m_ArgsInfo.outputDir_arg) );
381 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0012", instanceDate.str() );
382 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0013", instanceTime.str() );
385 // file UIDs are recreated for new studies or series
386 if (!useInputFileUID)
388 if (m_ArgsInfo.verbose_flag)
389 std::cout << "Recreating file UIDs" << std::endl;
392 #if GDCM_MAJOR_VERSION >= 2
393 gdcm::UIDGenerator fid;
394 fileUID = fid.Generate();
396 fileUID = gdcm::Util::CreateUniqueUID( gdcmIO->GetUIDPrefix());
398 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0008|0018", fileUID );
399 itk::EncapsulateMetaData<std::string>( *((*dictionary)[fni]), "0002|0003", fileUID );
401 filenames_out[fni] = itksys::SystemTools::CollapseFullPath(fileUID.c_str(), m_ArgsInfo.outputDir_arg) + std::string(".dcm");
405 // Output directory and filenames
406 itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist
407 typedef itk::ImageFileWriter<OutputImageType> SeriesWriterType;
408 typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New();
410 seriesWriter->SetInput( input );
411 seriesWriter->SetImageIO( gdcmIO );
413 seriesWriter->SetFileName( filenames_out[0] );
414 seriesWriter->SetMetaDataDictionary( *((*dictionary)[0]) );
418 if (m_ArgsInfo.verbose_flag)
419 std::cout << seriesWriter << std::endl;
420 seriesWriter->Update();
421 } catch( itk::ExceptionObject & excp ) {
422 std::cerr << "Error: Exception thrown while writing the series!!" << std::endl;
423 std::cerr << excp << std::endl;
430 #endif //#define clitkGateSimulation2DicomGenericFilter_txx