]> Creatis software - clitk.git/blob - tools/clitkDicom2Image.cxx
Add instanceNumber sorting for clitkDicom2Image
[clitk.git] / tools / clitkDicom2Image.cxx
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
19 // clitk includes
20 #include "clitkIO.h"
21 #include "clitkDicom2Image_ggo.h"
22 #include "clitkCommon.h"
23 #include "clitkImageCommon.h"
24 #include "vvImageReader.h"
25 #include "vvImageWriter.h"
26 #include <itkGDCMImageIO.h>
27 #include <itkGDCMSeriesFileNames.h>
28 #include <gdcmFile.h>
29 #include <vtkVersion.h>
30 #include <vtkImageChangeInformation.h>
31 #if GDCM_MAJOR_VERSION >= 2
32   #include <gdcmImageHelper.h>
33   #include <gdcmAttribute.h>
34   #include <gdcmReader.h>
35 #endif
36
37 #include <set>
38
39 //====================================================================
40 int main(int argc, char * argv[])
41 {
42   // init command line
43   GGO(clitkDicom2Image, args_info);
44   CLITK_INIT;
45
46   std::vector<std::string> input_files;
47   ///if std_input is given, read the input files from stdin
48   if (args_info.std_input_given) {
49     while (true) {
50       std::string tmp;
51       std::cin >> tmp;
52       if(std::cin.good())
53         input_files.push_back(tmp);
54       else break;
55     }
56     args_info.inputs_num=input_files.size();
57   } else for (unsigned int i=0; i<args_info.inputs_num; i++)
58       input_files.push_back(args_info.inputs[i]);
59
60   //Get GDCMSeriesFileNames order to sort filenames
61   typedef itk::GDCMSeriesFileNames NamesGeneratorType;
62   NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New();
63   nameGenerator->SetUseSeriesDetails(false);
64   std::string folderName=".";
65   const size_t last_slash_idx = input_files[0].rfind('/');
66   if (std::string::npos != last_slash_idx)
67     folderName = input_files[0].substr(0, last_slash_idx);
68   nameGenerator->SetInputDirectory(folderName);
69
70   //===========================================
71   /// Get slices locations ...
72   std::string series_UID = "";
73   std::set<std::string> series_UIDs;
74   std::map< std::string, std::vector<double> > theorigin;
75   std::map< std::string, std::vector<double> > theorientation;
76   std::map< std::string, std::vector<double> > sliceLocations;
77   std::map< std::string, std::vector<double> > instanceNumber;
78   std::map< std::string, std::vector<std::string> > seriesFiles;
79 #if GDCM_MAJOR_VERSION >= 2
80   if (args_info.verbose_flag)
81     std::cout << "Using GDCM-2.x" << std::endl;
82 #else
83   if (args_info.verbose_flag) {
84     std::cout << "Not using GDCM-2.x" << std::endl;
85     std::cout<< "The image orientation is not supported with this version of GDCM" <<std::endl;
86   }
87 #endif
88   for(unsigned int i=0; i<args_info.inputs_num; i++) {
89     if (args_info.verbose_flag)
90         std::cout << "Reading <" << input_files[i] << std::endl;
91 #if GDCM_MAJOR_VERSION >= 2
92     gdcm::Reader hreader;
93     hreader.SetFileName(input_files[i].c_str());
94     hreader.Read();
95     gdcm::DataSet& ds = hreader.GetFile().GetDataSet();
96
97     gdcm::Attribute<0x20,0x000e> series_UID_att;
98     series_UID_att.SetFromDataSet(ds);
99     series_UID = series_UID_att.GetValue().c_str();
100
101     series_UIDs.insert(series_UID);
102     theorigin[series_UID] = gdcm::ImageHelper::GetOriginValue(hreader.GetFile());
103     theorientation[series_UID] = gdcm::ImageHelper::GetDirectionCosinesValue(hreader.GetFile());
104     if (args_info.patientSystem_flag) {
105       double n1 = theorientation[series_UID][1]*theorientation[series_UID][5]-
106                   theorientation[series_UID][2]*theorientation[series_UID][4];
107       double n2 = theorientation[series_UID][3]*theorientation[series_UID][2]-
108                   theorientation[series_UID][5]*theorientation[series_UID][0];
109       double n3 = theorientation[series_UID][0]*theorientation[series_UID][4]-
110                   theorientation[series_UID][1]*theorientation[series_UID][3];
111       double sloc = theorigin[series_UID][0]*n1+
112                     theorigin[series_UID][1]*n2+
113                     theorigin[series_UID][2]*n3;
114       sliceLocations[series_UID].push_back(sloc);
115     } else
116       sliceLocations[series_UID].push_back(theorigin[series_UID][2]);
117     seriesFiles[series_UID].push_back(input_files[i]);
118
119     gdcm::Attribute<0x20,0x0013> instanceNumber_att;
120     instanceNumber_att.SetFromDataSet(ds);
121     instanceNumber[series_UID].push_back(instanceNumber_att.GetValue());
122
123     gdcm::Attribute<0x28, 0x100> pixel_size;
124     pixel_size.SetFromDataSet(ds);
125     /* if (pixel_size.GetValue() != 16)
126        {
127        std::cerr << "Pixel type not 2 bytes ! " << std::endl;
128        std::cerr << "In file " << input_files[i] << std::endl;
129        exit(0);
130        }
131     */
132 #else
133   gdcm::File *header = new gdcm::File();
134   header->SetFileName(input_files[i]);
135   header->SetMaxSizeLoadEntry(16384); // required ?
136   header->Load();
137
138   series_UID = header->GetEntryValue(0x20,0x000e).c_str();
139
140   series_UIDs.insert(series_UID);
141   theorigin[series_UID].resize(3);
142   theorigin[series_UID][0] = header->GetXOrigin();
143   theorigin[series_UID][1] = header->GetYOrigin();
144   theorigin[series_UID][2] = header->GetZOrigin();
145   sliceLocations[series_UID].push_back(theorigin[series_UID][2]);
146   seriesFiles[series_UID].push_back(input_files[i]);
147   /*if (header->GetPixelSize() != 2) {
148     std::cerr << "Pixel type 2 bytes ! " << std::endl;
149     std::cerr << "In file " << input_files[i] << std::endl;
150     exit(0);
151   }
152   */
153 #endif
154   }
155
156   //===========================================
157   // Sort slices locations ...
158   std::set<std::string>::iterator sn = series_UIDs.begin();
159   while ( sn != series_UIDs.end() ) {
160     std::vector<double> locs = sliceLocations[*sn];
161     std::vector<double> origin = theorigin[*sn];
162     std::vector<double> instanceNumberSerie = instanceNumber[*sn];
163     std::vector<std::string> files = seriesFiles[*sn];
164     std::vector<int> sliceIndex(files.size());
165     //clitk::GetSortedIndex(locs, sliceIndex);
166     //Look for files into GDCMSeriesFileNames, because it sorts files correctly and take the order
167     const std::vector<std::string> & temp = nameGenerator->GetFileNames(*sn);
168     for(unsigned int i=0; i<files.size(); i++) {
169       int j(0);
170       bool found(false);
171       while (!found && j<temp.size()) {
172         const size_t last_slash_idx2 = temp[j].rfind('/');
173         std::string tempFilename(temp[j]);
174         if (temp[j][0] == '.' && temp[j][1] == '/')
175           tempFilename = temp[j].substr(2, temp[j].size()-1);
176         if (tempFilename == files[i]) {
177           sliceIndex[j] = i;
178           found = true;
179         }
180         ++j;
181       }
182     }
183     if (sliceIndex.size() == 0) { //ie. sn is not a serie present in files
184       sn++;
185       continue;
186     }
187
188     if (args_info.verbose_flag) {
189       std::cout << locs[sliceIndex[0]] << " -> "
190                 << sliceIndex[0] << " / " << 0 << " => "
191                 << "0 mm "
192                 << files[sliceIndex[0]]
193                 << std::endl;
194       for(unsigned int i=1; i<sliceIndex.size(); i++) {
195         std::cout << locs[sliceIndex[i]] << " -> "
196                   << sliceIndex[i] << " / " << i << " => "
197                   << locs[sliceIndex[i]] - locs[sliceIndex[i-1]]
198                   << "mm "
199                   << files[sliceIndex[i]]
200                   << std::endl;
201       }
202     }
203
204     //===========================================
205     // Analyze slices locations ...
206     double currentDist;
207     double dist=0;
208     double tolerance = args_info.tolerance_arg;
209     double previous = locs[sliceIndex[0]];
210     for(unsigned int i=1; i<sliceIndex.size(); i++) {
211       currentDist = locs[sliceIndex[i]]-previous;
212       if (i!=1) {
213         if (fabs(dist-currentDist) > tolerance) {
214           std::cout << "ERROR : " << std::endl
215                     << "Current slice pos is  = " << locs[sliceIndex[i]] << std::endl
216                     << "Previous slice pos is = " << previous << std::endl
217                     << "Current file is       = " << files[sliceIndex[i]] << std::endl
218                     << "Current index is      = " << i << std::endl
219                     << "Current sortindex is  = " << sliceIndex[i] << std::endl
220                     << "Current slice diff    = " << dist << std::endl
221                     << "Current error         = " << fabs(dist-currentDist) << std::endl;
222           exit(1);
223         }
224       } else dist = currentDist;
225       previous = locs[sliceIndex[i]];
226     }
227
228     //===========================================
229     // Create ordered vector of filenames
230     std::vector<std::string> sorted_files;
231     sorted_files.resize(sliceIndex.size());
232     if (!args_info.instanceNumber_flag) {
233       for(unsigned int i=0; i<sliceIndex.size(); i++)
234         sorted_files[i] = files[ sliceIndex[i] ];
235     } else {
236       std::vector<double>::iterator maxInstanceNumber = std::max_element(instanceNumberSerie.begin(), instanceNumberSerie.end());
237       std::vector<std::string> instanceNumberTemp(*maxInstanceNumber, "");
238       for(unsigned int i=0; i<instanceNumberSerie.size(); i++)
239         instanceNumberTemp[instanceNumberSerie[i]-1] = files[i];
240       unsigned int fillFiles(0);
241       for(unsigned int i=0; i<instanceNumberTemp.size(); i++) {
242           if (instanceNumberTemp[i] != "") {
243             sorted_files[fillFiles] = instanceNumberTemp[i];
244             ++fillFiles;
245           }
246        }
247     }
248
249     //===========================================
250     // Read write serie
251     vvImageReader::Pointer reader = vvImageReader::New();
252     reader->SetInputFilenames(sorted_files);
253     reader->SetPatientCoordinateSystem(args_info.patientSystem_flag);
254     reader->Update(vvImageReader::DICOM);
255     if (reader->GetLastError().size() != 0) {
256       std::cerr << reader->GetLastError() << std::endl;
257       return 1;
258     }
259
260     vvImage::Pointer image = reader->GetOutput();
261     vtkImageData* vtk_image = image->GetFirstVTKImageData();
262     vtkImageChangeInformation* modifier = vtkImageChangeInformation::New();
263     if  (args_info.focal_origin_given) {
264       std::vector<double> spacing = image->GetSpacing();
265       std::vector<int> size = image->GetSize();
266       origin[0] = -spacing[0]*size[0]/2.0;
267       origin[1] = -spacing[1]*size[1]/2.0;
268 #if VTK_MAJOR_VERSION <= 5
269       modifier->SetInput(vtk_image);
270 #else
271       modifier->SetInputData(vtk_image);
272 #endif
273       modifier->SetOutputOrigin(origin[0], origin[1], locs[sliceIndex[0]]);
274       modifier->Update();
275       vvImage::Pointer focal_image = vvImage::New();
276       focal_image->AddVtkImage(modifier->GetOutput());
277       image = focal_image;
278     }
279
280     std::string outfile;
281     if (series_UIDs.size() == 1)
282       outfile = args_info.output_arg;
283     else {
284       std::ostringstream name;
285       std::vector<std::string> directory = clitk::SplitFilename(args_info.output_arg);
286       if (directory.size() == 2)
287         name << directory[0] << "/" << *sn << "_" << directory[1];
288       else
289         name << *sn << "_" << args_info.output_arg;
290       outfile = name.str();
291     }
292     vvImageWriter::Pointer writer = vvImageWriter::New();
293     writer->SetInput(image);
294     if (args_info.patientSystem_flag && !image->GetTransform().empty())
295       writer->SetSaveTransform(true);
296     writer->SetOutputFileName(outfile);
297     writer->Update();
298
299     modifier->Delete();
300
301     sn++;
302   }
303
304   return 0;
305 }