]> Creatis software - clitk.git/blob - tools/clitkDicom2Image.cxx
Remove extract_series option
[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(true);
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<std::string> > seriesFiles;
78 #if GDCM_MAJOR_VERSION >= 2
79   if (args_info.verbose_flag)
80     std::cout << "Using GDCM-2.x" << std::endl;
81 #else
82   if (args_info.verbose_flag) {
83     std::cout << "Not using GDCM-2.x" << std::endl;
84     std::cout<< "The image orientation is not supported with this version of GDCM" <<std::endl;
85   }
86 #endif
87   for(unsigned int i=0; i<args_info.inputs_num; i++) {
88     if (args_info.verbose_flag)
89         std::cout << "Reading <" << input_files[i] << std::endl;
90 #if GDCM_MAJOR_VERSION >= 2
91     gdcm::Reader hreader;
92     hreader.SetFileName(input_files[i].c_str());
93     hreader.Read();
94     gdcm::DataSet& ds = hreader.GetFile().GetDataSet();
95
96     gdcm::Attribute<0x20,0x000e> series_UID_att;
97     series_UID_att.SetFromDataSet(ds);
98     series_UID = series_UID_att.GetValue().c_str();
99
100     series_UIDs.insert(series_UID);
101     theorigin[series_UID] = gdcm::ImageHelper::GetOriginValue(hreader.GetFile());
102     theorientation[series_UID] = gdcm::ImageHelper::GetDirectionCosinesValue(hreader.GetFile());
103     if (args_info.patientSystem_flag) {
104       double n1 = theorientation[series_UID][1]*theorientation[series_UID][5]-
105                   theorientation[series_UID][2]*theorientation[series_UID][4];
106       double n2 = theorientation[series_UID][3]*theorientation[series_UID][2]-
107                   theorientation[series_UID][5]*theorientation[series_UID][0];
108       double n3 = theorientation[series_UID][0]*theorientation[series_UID][4]-
109                   theorientation[series_UID][1]*theorientation[series_UID][3];
110       double sloc = theorigin[series_UID][0]*n1+
111                     theorigin[series_UID][1]*n2+
112                     theorigin[series_UID][2]*n3;
113       sliceLocations[series_UID].push_back(sloc);
114     } else
115       sliceLocations[series_UID].push_back(theorigin[series_UID][2]);
116     seriesFiles[series_UID].push_back(input_files[i]);
117
118     gdcm::Attribute<0x28, 0x100> pixel_size;
119     pixel_size.SetFromDataSet(ds);
120     /* if (pixel_size.GetValue() != 16)
121        {
122        std::cerr << "Pixel type not 2 bytes ! " << std::endl;
123        std::cerr << "In file " << input_files[i] << std::endl;
124        exit(0);
125        }
126     */
127 #else
128   gdcm::File *header = new gdcm::File();
129   header->SetFileName(input_files[i]);
130   header->SetMaxSizeLoadEntry(16384); // required ?
131   header->Load();
132
133   series_UID = header->GetEntryValue(0x20,0x000e).c_str();
134
135   series_UIDs.insert(series_UID);
136   theorigin[series_UID].resize(3);
137   theorigin[series_UID][0] = header->GetXOrigin();
138   theorigin[series_UID][1] = header->GetYOrigin();
139   theorigin[series_UID][2] = header->GetZOrigin();
140   sliceLocations[series_UID].push_back(theorigin[series_UID][2]);
141   seriesFiles[series_UID].push_back(input_files[i]);
142   /*if (header->GetPixelSize() != 2) {
143     std::cerr << "Pixel type 2 bytes ! " << std::endl;
144     std::cerr << "In file " << input_files[i] << std::endl;
145     exit(0);
146   }
147   */
148 #endif
149   }
150
151   //===========================================
152   // Sort slices locations ...
153   std::set<std::string>::iterator sn = series_UIDs.begin();
154   while ( sn != series_UIDs.end() ) {
155     std::vector<double> locs = sliceLocations[*sn];
156     std::vector<double> origin = theorigin[*sn];
157     std::vector<std::string> files = seriesFiles[*sn];
158     std::vector<int> sliceIndex;
159     //clitk::GetSortedIndex(locs, sliceIndex);
160     //Look for files into GDCMSeriesFileNames, because it sorts files correctly and take the order
161     const std::vector<std::string> & temp = nameGenerator->GetFileNames(*sn);
162     for(unsigned int i=0; i<files.size(); i++) {
163       int j(0);
164       while (sliceIndex.size()==i && j<temp.size()) {
165         const size_t last_slash_idx2 = temp[j].rfind('/');
166         std::string tempFilename(temp[j]);
167         if (temp[j][0] == '.' && std::string::npos != last_slash_idx2)
168           tempFilename = temp[j].substr(last_slash_idx2+1, temp[j].size()-1);
169         if (tempFilename == files[i])
170           sliceIndex.push_back(j);
171         ++j;
172       }
173     }
174
175     if (args_info.verbose_flag) {
176       std::cout << locs[sliceIndex[0]] << " -> "
177                 << sliceIndex[0] << " / " << 0 << " => "
178                 << "0 mm "
179                 << files[sliceIndex[0]]
180                 << std::endl;
181       for(unsigned int i=1; i<sliceIndex.size(); i++) {
182         std::cout << locs[sliceIndex[i]] << " -> "
183                   << sliceIndex[i] << " / " << i << " => "
184                   << locs[sliceIndex[i]] - locs[sliceIndex[i-1]]
185                   << "mm "
186                   << files[sliceIndex[i]]
187                   << std::endl;
188       }
189     }
190
191     //===========================================
192     // Analyze slices locations ...
193     double currentDist;
194     double dist=0;
195     double tolerance = args_info.tolerance_arg;
196     double previous = locs[sliceIndex[0]];
197     for(unsigned int i=1; i<sliceIndex.size(); i++) {
198       currentDist = locs[sliceIndex[i]]-previous;
199       if (i!=1) {
200         if (fabs(dist-currentDist) > tolerance) {
201           std::cout << "ERROR : " << std::endl
202                     << "Current slice pos is  = " << locs[sliceIndex[i]] << std::endl
203                     << "Previous slice pos is = " << previous << std::endl
204                     << "Current file is       = " << files[sliceIndex[i]] << std::endl
205                     << "Current index is      = " << i << std::endl
206                     << "Current sortindex is  = " << sliceIndex[i] << std::endl
207                     << "Current slice diff    = " << dist << std::endl
208                     << "Current error         = " << fabs(dist-currentDist) << std::endl;
209           exit(1);
210         }
211       } else dist = currentDist;
212       previous = locs[sliceIndex[i]];
213     }
214
215     //===========================================
216     // Create ordered vector of filenames
217     std::vector<std::string> sorted_files;
218     sorted_files.resize(sliceIndex.size());
219     for(unsigned int i=0; i<sliceIndex.size(); i++)
220       sorted_files[i] = files[ sliceIndex[i] ];
221
222     //===========================================
223     // Read write serie
224     vvImageReader::Pointer reader = vvImageReader::New();
225     reader->SetInputFilenames(sorted_files);
226     reader->SetPatientCoordinateSystem(args_info.patientSystem_flag);
227     reader->Update(vvImageReader::DICOM);
228     if (reader->GetLastError().size() != 0) {
229       std::cerr << reader->GetLastError() << std::endl;
230       return 1;
231     }
232
233     vvImage::Pointer image = reader->GetOutput();
234     vtkImageData* vtk_image = image->GetFirstVTKImageData();
235     vtkImageChangeInformation* modifier = vtkImageChangeInformation::New();
236     if  (args_info.focal_origin_given) {
237       std::vector<double> spacing = image->GetSpacing();
238       std::vector<int> size = image->GetSize();
239       origin[0] = -spacing[0]*size[0]/2.0;
240       origin[1] = -spacing[1]*size[1]/2.0;
241 #if VTK_MAJOR_VERSION <= 5
242       modifier->SetInput(vtk_image);
243 #else
244       modifier->SetInputData(vtk_image);
245 #endif
246       modifier->SetOutputOrigin(origin[0], origin[1], locs[sliceIndex[0]]);
247       modifier->Update();
248       vvImage::Pointer focal_image = vvImage::New();
249       focal_image->AddVtkImage(modifier->GetOutput());
250       image = focal_image;
251     }
252
253     std::string outfile;
254     if (series_UIDs.size() == 1)
255       outfile = args_info.output_arg;
256     else {
257       std::ostringstream name;
258       std::vector<std::string> directory = clitk::SplitFilename(args_info.output_arg);
259       if (directory.size() == 2)
260         name << directory[0] << "/" << *sn << "_" << directory[1];
261       else
262         name << *sn << "_" << args_info.output_arg;
263       outfile = name.str();
264     }
265     vvImageWriter::Pointer writer = vvImageWriter::New();
266     writer->SetInput(image);
267     if (args_info.patientSystem_flag && !image->GetTransform().empty())
268       writer->SetSaveTransform(true);
269     writer->SetOutputFileName(outfile);
270     writer->Update();
271
272     modifier->Delete();
273
274     sn++;
275   }
276
277   return 0;
278 }