]> Creatis software - gdcm.git/blob - src/gdcmSerieHeader.cxx
29f475701aa5f61ed2f7ca672b97816ae6cfe6c2
[gdcm.git] / src / gdcmSerieHeader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHeader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/01 10:40:46 $
7   Version:   $Revision: 1.19 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmSerieHeader.h"
20 #include "gdcmDirList.h"
21 #include "gdcmFile.h"
22 #include "gdcmDebug.h"
23
24 #include <math.h>
25 #include <algorithm>
26 #include <vector>
27
28 namespace gdcm 
29 {
30 typedef std::list<File* > GdcmFileList;
31 typedef std::vector<File* > GdcmFileVector;
32
33 //-----------------------------------------------------------------------------
34 // Constructor / Destructor
35 /**
36  * \brief   Constructor from a given SerieHeader
37  */
38 SerieHeader::SerieHeader()
39 {
40    // For all the File lists of the gdcm::Serie
41    GdcmFileList *l = GetFirstCoherentFileList();
42    while (l)
43    { 
44       // For all the files of a File list
45       for (GdcmFileList::iterator it  = l->begin();
46                                   it != l->end(); 
47                                 ++it)
48       {
49          delete *it;
50       }
51       l->clear();
52       delete l;;
53       l = GetNextCoherentFileList();
54    }
55 }
56
57 /**
58  * \brief   Canonical destructor.
59  */
60 SerieHeader::~SerieHeader()
61 {
62    // For all the Coherent File lists of the gdcm::Serie
63    GdcmFileList *l = GetFirstCoherentFileList();
64    while (l)
65    { 
66       // For all the files of a Coherent File list
67       for (GdcmFileList::iterator it  = l->begin();
68                                   it != l->end(); 
69                                 ++it)
70       {
71          delete *it;
72       }
73       l->clear();
74       delete l;
75       l = GetNextCoherentFileList();
76    }
77 }
78
79 //-----------------------------------------------------------------------------
80 <<<<<<< gdcmSerieHeader.cxx
81 // Print
82
83 /**
84  * \brief   Canonical printer.
85  */
86 void SerieHeader::Print()
87 {
88    // For all the Coherent File lists of the gdcm::Serie
89    CoherentFileListmap::iterator itl = CoherentGdcmFileListHT.begin();
90    if ( itl == CoherentGdcmFileListHT.end() )
91    {
92       gdcmVerboseMacro( "No Coherent File list found" );
93       return;
94    }
95    while (itl != CoherentGdcmFileListHT.end())
96    { 
97       std::cout << "Serie UID :[" << itl->first << "]" << std::endl;
98       // For all the files of a Coherent File list
99       for (GdcmFileList::iterator it =  (itl->second)->begin();
100                                   it != (itl->second)->end(); 
101                                 ++it)
102       {
103          std::cout << " --- " << (*it)->GetFileName() << std::endl;
104       }
105       ++itl;
106    }
107 }
108
109 //-----------------------------------------------------------------------------
110 =======
111 >>>>>>> 1.18
112 // Public
113 /**
114  * \brief add a gdcm::File to the list corresponding to its Serie UID
115  * @param   filename Name of the file to deal with
116  */
117 void SerieHeader::AddFileName(std::string const &filename)
118 {
119    //directly use string and not const char*:
120    File *header = new File( filename ); 
121    if( header->IsReadable() )
122    {
123       // 0020 000e UI REL Series Instance UID
124       std::string uid =  header->GetEntryValue (0x0020, 0x000e);
125       // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
126       // no need here to do anything special
127
128       if ( CoherentGdcmFileListHT.count(uid) == 0 )
129       {
130          gdcmVerboseMacro(" New Serie UID :[" << uid << "]");
131          // create a std::list in 'uid' position
132          CoherentGdcmFileListHT[uid] = new GdcmFileList;
133       }
134       // Current Serie UID and DICOM header seems to match add the file:
135       CoherentGdcmFileListHT[uid]->push_back( header );
136    }
137    else
138    {
139       gdcmVerboseMacro("Could not read file: " << filename );
140       delete header;
141    }
142 }
143
144 /**
145  * \brief Sets the root Directory
146  * @param   dir Name of the directory to deal with
147  * @param recursive whether we want explore recursively the Directory
148  */
149 void SerieHeader::SetDirectory(std::string const &dir, bool recursive)
150 {
151    DirList dirList(dir, recursive); // OS specific
152   
153    DirListType filenames_list = dirList.GetFilenames();
154    for( DirListType::const_iterator it = filenames_list.begin(); 
155         it != filenames_list.end(); ++it)
156    {
157       AddFileName( *it );
158    }
159 }
160
161 /**
162  * \brief Sorts the given File List
163  * \warning This could be implemented in a 'Strategy Pattern' approach
164  *          But as I don't know how to do it, I leave it this way
165  *          BTW, this is also a Strategy, I don't know this is the best approach :)
166  */
167 void SerieHeader::OrderGdcmFileList(GdcmFileList *CoherentGdcmFileList)
168 {
169    if( ImagePositionPatientOrdering( CoherentGdcmFileList ) )
170    {
171       return ;
172    }
173    else if( ImageNumberOrdering(CoherentGdcmFileList ) )
174    {
175       return ;
176    }
177    else  
178    {
179       FileNameOrdering(CoherentGdcmFileList );
180    }
181 }
182
183 /**
184  * \brief   Get the first List while visiting the CoherentFileListHT
185  * @return  The first GdcmFileList if found, otherwhise NULL
186  */
187  std::list<File* > *SerieHeader::GetFirstCoherentFileList()
188 // Why doesn't it compile ?!?
189 //GdcmFileList *SerieHeader::GetFirstCoherentFileList()
190 {
191    ItListHt = CoherentGdcmFileListHT.begin();
192    if( ItListHt != CoherentGdcmFileListHT.end() )
193       return ItListHt->second;
194    return NULL;
195 }
196
197 /**
198  * \brief   Get the next List while visiting the CoherentFileListHT
199  * \note : meaningfull only if GetFirstCoherentFileList already called
200  * @return  The next GdcmFileList if found, otherwhise NULL
201  */
202 std::list<File* > *SerieHeader::GetNextCoherentFileList()
203 {
204    gdcmAssertMacro (ItListHt != CoherentGdcmFileListHT.end());
205   
206    ++ItListHt;
207    if ( ItListHt != CoherentGdcmFileListHT.end() )
208       return ItListHt->second;
209    return NULL;
210 }
211
212 /**
213  * \brief   Get the Coherent Files list according to its Serie UID
214  * @param SerieUID SerieUID
215  * \return  pointer to the Coherent Filseslist if found, otherwhise NULL
216  */
217 GdcmFileList *SerieHeader::GetCoherentFileList(std::string SerieUID)
218 {
219    if ( CoherentGdcmFileListHT.count(SerieUID) == 0 )
220       return 0;     
221    return CoherentGdcmFileListHT[SerieUID];
222 }
223
224 //-----------------------------------------------------------------------------
225 // Protected
226
227 //-----------------------------------------------------------------------------
228 // Private
229 /**
230  * \brief sorts the images, according to their Patient Position
231  *  We may order, considering :
232  *   -# Image Position Patient
233  *   -# Image Number
234  *   -# More to come :-)
235  * @param CoherentGdcmFileList Coherent File list (same Serie UID) to sort
236  * @return false only if the header is bugged !
237  */
238 bool SerieHeader::ImagePositionPatientOrdering( 
239                                        GdcmFileList *CoherentGdcmFileList )
240 //based on Jolinda's algorithm
241 {
242    //iop is calculated based on the file file
243    float cosines[6];
244    float normal[3];
245    float ipp[3];
246    float dist;
247    float min = 0, max = 0;
248    bool first = true;
249    int n=0;
250    std::vector<float> distlist;
251
252    //!\todo rewrite this for loop.
253    for ( GdcmFileList::const_iterator 
254          it = CoherentGdcmFileList->begin();
255          it != CoherentGdcmFileList->end(); ++it )
256    {
257       if( first ) 
258       {
259          (*it)->GetImageOrientationPatient( cosines );
260       
261          // You only have to do this once for all slices in the volume. Next, 
262          // for each slice, calculate the distance along the slice normal 
263          // using the IPP tag ("dist" is initialized to zero before reading 
264          // the first slice) :
265          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
266          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
267          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
268   
269          ipp[0] = (*it)->GetXOrigin();
270          ipp[1] = (*it)->GetYOrigin();
271          ipp[2] = (*it)->GetZOrigin();
272
273          dist = 0;
274          for ( int i = 0; i < 3; ++i )
275          {
276             dist += normal[i]*ipp[i];
277          }
278     
279          if( dist == 0 )
280          {
281             return false;
282          }
283
284          distlist.push_back( dist );
285
286          max = min = dist;
287          first = false;
288       }
289       else 
290       {
291          ipp[0] = (*it)->GetXOrigin();
292          ipp[1] = (*it)->GetYOrigin();
293          ipp[2] = (*it)->GetZOrigin();
294   
295          dist = 0;
296          for ( int i = 0; i < 3; ++i )
297          {
298             dist += normal[i]*ipp[i];
299          }
300
301          if( dist == 0 )
302          {
303             return false;
304          }
305       
306          distlist.push_back( dist );
307
308          min = (min < dist) ? min : dist;
309          max = (max > dist) ? max : dist;
310       }
311       ++n;
312    }
313
314    // Then I order the slices according to the value "dist". Finally, once
315    // I've read in all the slices, I calculate the z-spacing as the difference
316    // between the "dist" values for the first two slices.
317    GdcmFileVector CoherentGdcmFileVector(n);
318    // CoherentGdcmFileVector.reserve( n );
319    CoherentGdcmFileVector.resize( n );
320    // gdcmAssertMacro( CoherentGdcmFileVector.capacity() >= n );
321
322    float step = (max - min)/(n - 1);
323    int pos;
324    n = 0;
325     
326    //VC++ don't understand what scope is !! it -> it2
327    for (GdcmFileList::const_iterator it2  = CoherentGdcmFileList->begin();
328         it2 != CoherentGdcmFileList->end(); ++it2, ++n)
329    {
330       //2*n sort algo !!
331       //Assumption: all files are present (no one missing)
332       pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
333
334       // a Dicom 'Serie' may contain scout views
335       // and images may have differents directions
336       // -> More than one may have the same 'pos'
337       // Sorting has then NO meaning !
338       if (CoherentGdcmFileVector[pos]==NULL)
339          CoherentGdcmFileVector[pos] = *it2;
340       else
341       {
342          gdcmVerboseMacro( "2 files same position");
343          return false;
344       }
345    }
346
347    CoherentGdcmFileList->clear();  // doesn't delete list elements, only node
348   
349    //VC++ don't understand what scope is !! it -> it3
350    for (GdcmFileVector::const_iterator it3  = CoherentGdcmFileVector.begin();
351         it3 != CoherentGdcmFileVector.end(); ++it3)
352    {
353       CoherentGdcmFileList->push_back( *it3 );
354    }
355
356    distlist.clear();
357    CoherentGdcmFileVector.clear();
358
359    return true;
360 }
361
362 /**
363  * \brief sorts the images, according to their Image Number
364  * \note Works only on bona fide files  (i.e image number is a character string
365  *                                      corresponding to an integer)
366  *             within a bona fide serie (i.e image numbers are consecutive)
367  * @param CoherentGdcmFileList Coherent File list (same Serie UID) to sort 
368  * @return false if non nona fide stuff encountered
369  */
370 bool SerieHeader::ImageNumberOrdering(GdcmFileList *CoherentGdcmFileList) 
371 {
372    int min, max, pos;
373    int n = 0;//CoherentGdcmFileList.size() is a O(N) operation
374    unsigned char *partition;
375   
376    GdcmFileList::const_iterator it = CoherentGdcmFileList->begin();
377    min = max = (*it)->GetImageNumber();
378
379    for (; it != CoherentGdcmFileList->end(); ++it, ++n)
380    {
381       pos = (*it)->GetImageNumber();
382       min = (min < pos) ? min : pos;
383       max = (max > pos) ? max : pos;
384    }
385
386    // Find out if image numbers are coherent (consecutive)
387    if( min == max || max == 0 || max >= (n+min))
388       return false;
389
390    partition = new unsigned char[n];
391    memset(partition, 0, n); 
392
393    GdcmFileVector CoherentGdcmFileVector(n);
394
395    //VC++ doesn't understand what scope is !! it -> it2
396    for (GdcmFileList::const_iterator it2 = CoherentGdcmFileList->begin();
397         it2 != CoherentGdcmFileList->end(); ++it2)
398    {
399       pos = (*it2)->GetImageNumber();
400       CoherentGdcmFileVector[pos - min] = *it2;
401       partition[pos - min]++;
402    }
403   
404    unsigned char mult = 1;
405    for( int i=0; i<n ; i++ )
406    {
407       mult *= partition[i];
408    }
409
410    //VC++ doesn't understand what scope is !! it -> it3
411    CoherentGdcmFileList->clear();  // doesn't delete list elements, only nodes
412    for ( GdcmFileVector::const_iterator it3 = CoherentGdcmFileVector.begin();
413          it3 != CoherentGdcmFileVector.end(); ++it3 )
414    {
415       CoherentGdcmFileList->push_back( *it3 );
416    }
417    CoherentGdcmFileVector.clear();  
418    delete[] partition;
419
420    return mult != 0;
421 }
422
423 /**
424  * \brief sorts the images, according to their File Name
425  * @param CoherentGdcmFileList Coherent File list (same Serie UID) to sort
426  * @return false only if the header is bugged !
427  */
428 bool SerieHeader::FileNameOrdering(GdcmFileList *)
429 {
430    //TODO using the sort
431    //sort(CoherentGdcmFileList.begin(), CoherentGdcmFileList.end());
432    return true;
433 }
434
435 //-----------------------------------------------------------------------------
436 // Print
437 /**
438  * \brief   Canonical printer.
439  */
440 void SerieHeader::Print()
441 {
442    // For all the Coherent File lists of the gdcm::Serie
443    CoherentFileListmap::iterator itl = CoherentGdcmFileListHT.begin();
444    if ( itl == CoherentGdcmFileListHT.end() )
445    {
446       gdcmVerboseMacro( "No Coherent File list found" );
447       return;
448    }
449    while (itl != CoherentGdcmFileListHT.end())
450    { 
451       std::cout << "Serie UID :[" << itl->first << "]" << std::endl;
452
453       // For all the files of a Coherent File list
454       for (GdcmFileList::iterator it =  (itl->second)->begin();
455                                   it != (itl->second)->end(); 
456                                 ++it)
457       {
458          std::cout << " --- " << (*it)->GetFileName() << std::endl;
459       }
460       ++itl;
461    }
462 }
463
464 //-----------------------------------------------------------------------------
465 } // end namespace gdcm