1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2005/08/30 08:12:40 $
7 Version: $Revision: 1.18 $
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.
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.
17 =========================================================================*/
19 #include "gdcmSerieHelper.h"
20 #include "gdcmDirList.h"
22 #include "gdcmDictEntry.h" // for TranslateToKey
23 #include "gdcmDebug.h"
33 //-----------------------------------------------------------------------------
34 // Constructor / Destructor
36 * \brief Constructor from a given SerieHelper
38 SerieHelper::SerieHelper()
40 UserLessThanFunction = 0;
42 // For all the File lists that may already exist within the gdcm::Serie
43 FileList *l = GetFirstCoherentFileList();
46 // For all the files of a File list
47 for (gdcm::FileList::iterator it = l->begin();
51 delete *it; // remove entry
54 delete l; // remove the list
55 l = GetNextCoherentFileList();
61 * \brief Canonical destructor.
63 SerieHelper::~SerieHelper()
65 // For all the Coherent File lists of the gdcm::Serie
66 FileList *l = GetFirstCoherentFileList();
69 // For all the files of a Coherent File list
70 for (FileList::iterator it = l->begin();
74 delete *it; // remove entry
77 delete l; // remove the list
78 l = GetNextCoherentFileList();
82 //-----------------------------------------------------------------------------
84 //-----------------------------------------------------------------------------
88 * \brief add a gdcm::File to the list corresponding to its Serie UID
89 * @param filename Name of the file to deal with
91 void SerieHelper::AddFileName(std::string const &filename)
93 // Create a DICOM file
94 File *header = new File ();
95 header->SetLoadMode(LoadMode);
96 header->SetFileName( filename );
99 if ( header->IsReadable() )
102 // First step the user has defined a set of rules for the DICOM file
103 // he is looking for.
104 // make sure the file correspond to his set of rules:
107 for(SerieRestrictions::iterator it = Restrictions.begin();
108 it != Restrictions.end();
112 // doesn't compile (no matching function...).
113 const std::string s;// = header->GetEntryValue( r.first );
114 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
116 // Argh ! This rule is unmatch let's just quit
122 // Just keep 'new style' for Rules
124 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
125 it2 != ExRestrictions.end();
128 const ExRule &r = *it2;
129 s = header->GetEntryValue( r.group, r.elem );
130 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
132 // Argh ! This rule is unmatch let's just quit
138 if ( allrules ) // all rules are respected:
140 // Allright ! we have a found a DICOM that match the user expectation.
143 // 0020 000e UI REL Series Instance UID
144 const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
145 // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
146 // no need here to do anything special
148 if ( CoherentFileListHT.count(uid) == 0 )
150 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
151 // create a std::list in 'uid' position
152 CoherentFileListHT[uid] = new FileList;
154 // Current Serie UID and DICOM header seems to match; add the file:
155 CoherentFileListHT[uid]->push_back( header );
159 // at least one rule was unmatch we need to deallocate the file:
165 gdcmWarningMacro("Could not read file: " << filename );
171 * \brief add a gdcm::File to the first (and supposed to be unique) list
172 * of the gdcm::SerieHelper.
173 * \warning : this method should be used by aware users only!
174 * User is supposed to know the files he want to deal with
175 * and consider them they belong to the same Serie
176 * (even if their Serie UID is different)
177 * user will probabely OrderFileList() this list (actually, ordering
178 * user choosen gdm::File is the sole interest of this method)
179 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
180 * vtkGdcmReader parsing twice the same files.
181 * *no* coherence check is performed, but those specified
182 * by SerieHelper::AddRestriction()
183 * @param header gdcm::File* of the file to deal with
185 void SerieHelper::AddGdcmFile(File *header)
188 // First step the user has defined a set of rules for the DICOM
189 // he is looking for.
190 // make sure the file correspond to his set of rules:
191 for(SerieRestrictions::iterator it = Restrictions.begin();
192 it != Restrictions.end();
196 const std::string s;// = header->GetEntryValue( r.first );
197 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
199 // Argh ! This rule is unmatch let's just quit
204 if ( allrules ) // all rules are respected:
206 // Allright ! we have a found a DICOM that match the user expectation.
209 const std::string &uid = "0";
210 // Serie UID of the gdcm::File* may be different.
211 // User is supposed to know what he wants
213 if ( CoherentFileListHT.count(uid) == 0 )
215 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
216 // create a std::list in 'uid' position
217 CoherentFileListHT[uid] = new FileList;
219 // Current Serie UID and DICOM header seems to match; add the file:
220 CoherentFileListHT[uid]->push_back( header );
222 // Even if a rule was unmatch we don't deallocate the gdcm::File:
226 * \brief add a rules for restricting a DICOM file to be in the serie we are
227 * trying to find. For example you can select only the DICOM file from a
228 * directory which would have a particular EchoTime==4.0.
229 * This method is a user level, value is not required to be formatted as a DICOM
232 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
233 std::string const &value, int op)
240 ExRestrictions.push_back( r );
243 #ifndef GDCM_LEGACY_REMOVE
245 * \brief add a rules for restricting a DICOM file to be in the serie we are
246 * trying to find. For example you can select only the DICOM file from a
247 * directory which would have a particular EchoTime==4.0.
248 * This method is a user level, value is not required to be formatted as a DICOM
250 * @deprecated use : AddRestriction(uint16_t group, uint16_t elem,
251 * std::string const &value, int op);
253 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
258 Restrictions.push_back( r );
263 * \brief Sets the root Directory
264 * @param dir Name of the directory to deal with
265 * @param recursive whether we want explore recursively the Directory
267 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
269 DirList dirList(dir, recursive); // OS specific
271 DirListType filenames_list = dirList.GetFilenames();
272 for( DirListType::const_iterator it = filenames_list.begin();
273 it != filenames_list.end(); ++it)
280 * \brief Sorts the given File List
281 * \warning This could be implemented in a 'Strategy Pattern' approach
282 * But as I don't know how to do it, I leave it this way
283 * BTW, this is also a Strategy, I don't know this is the best approach :)
285 void SerieHelper::OrderFileList(FileList *coherentFileList)
288 if ( SerieHelper::UserLessThanFunction )
290 UserOrdering( coherentFileList );
293 else if ( ImagePositionPatientOrdering( coherentFileList ) )
297 else if ( ImageNumberOrdering(coherentFileList ) )
303 FileNameOrdering(coherentFileList );
308 * \brief Elementary coherence checking of the files with the same Serie UID
309 * Only sizes and pixel type are checked right now ...
311 bool SerieHelper::IsCoherent(FileList *coherentFileList)
313 if(coherentFileList->size() == 1)
316 FileList::const_iterator it = coherentFileList->begin();
318 int nX = (*it)->GetXSize();
319 int nY = (*it)->GetYSize();
320 int pixelSize = (*it)->GetPixelSize();
324 it != coherentFileList->end();
327 if ( (*it)->GetXSize() != nX )
329 if ( (*it)->GetYSize() != nY )
331 if ( (*it)->GetPixelSize() != pixelSize )
333 // probabely more is to be checked (?)
338 * \brief Get the first List while visiting the CoherentFileListHT
339 * @return The first FileList if found, otherwhise NULL
341 FileList *SerieHelper::GetFirstCoherentFileList()
343 ItListHt = CoherentFileListHT.begin();
344 if ( ItListHt != CoherentFileListHT.end() )
345 return ItListHt->second;
350 * \brief Get the next List while visiting the CoherentFileListHT
351 * \note : meaningfull only if GetFirstCoherentFileList() already called
352 * @return The next FileList if found, otherwhise NULL
354 FileList *SerieHelper::GetNextCoherentFileList()
356 gdcmAssertMacro (ItListHt != CoherentFileListHT.end());
359 if ( ItListHt != CoherentFileListHT.end() )
360 return ItListHt->second;
365 * \brief Get the Coherent Files list according to its Serie UID
366 * @param SerieUID SerieUID
367 * \return pointer to the Coherent Files list if found, otherwhise NULL
369 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
371 if ( CoherentFileListHT.count(SerieUID) == 0 )
373 return CoherentFileListHT[SerieUID];
376 //-----------------------------------------------------------------------------
379 //-----------------------------------------------------------------------------
382 * \brief sorts the images, according to their Patient Position
383 * We may order, considering :
384 * -# Image Position Patient
386 * -# More to come :-)
387 * WARNING : FileList = std::vector<File* >
388 * @param fileList Coherent File list (same Serie UID) to sort
389 * @return false only if the header is bugged !
391 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
392 //based on Jolinda Smith's algorithm
394 //iop is calculated based on the file file
399 float min = 0, max = 0;
402 std::vector<float> distlist;
404 //!\todo rewrite this for loop.
405 for ( FileList::const_iterator
406 it = fileList->begin();
407 it != fileList->end(); ++it )
411 (*it)->GetImageOrientationPatient( cosines );
413 // You only have to do this once for all slices in the volume. Next,
414 // for each slice, calculate the distance along the slice normal
415 // using the IPP tag ("dist" is initialized to zero before reading
416 // the first slice) :
417 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
418 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
419 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
421 ipp[0] = (*it)->GetXOrigin();
422 ipp[1] = (*it)->GetYOrigin();
423 ipp[2] = (*it)->GetZOrigin();
426 for ( int i = 0; i < 3; ++i )
428 dist += normal[i]*ipp[i];
431 distlist.push_back( dist );
438 ipp[0] = (*it)->GetXOrigin();
439 ipp[1] = (*it)->GetYOrigin();
440 ipp[2] = (*it)->GetZOrigin();
443 for ( int i = 0; i < 3; ++i )
445 dist += normal[i]*ipp[i];
448 distlist.push_back( dist );
450 min = (min < dist) ? min : dist;
451 max = (max > dist) ? max : dist;
456 // Then I order the slices according to the value "dist". Finally, once
457 // I've read in all the slices, I calculate the z-spacing as the difference
458 // between the "dist" values for the first two slices.
459 FileVector CoherentFileVector(n);
460 // CoherentFileVector.reserve( n );
461 CoherentFileVector.resize( n );
462 // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
464 // Find out if min/max are coherent
467 gdcmWarningMacro( "Looks like all images have the exact same image position."
468 << "No PositionPatientOrdering sort performed" );
472 float step = (max - min)/(n - 1);
476 //VC++ don't understand what scope is !! it -> it2
477 for (FileList::const_iterator it2 = fileList->begin();
478 it2 != fileList->end(); ++it2, ++n)
481 //Assumption: all files are present (no one missing)
482 pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
484 // a Dicom 'Serie' may contain scout views
485 // and images may have differents directions
486 // -> More than one may have the same 'pos'
487 // Sorting has then NO meaning !
488 if (CoherentFileVector[pos]==NULL)
489 CoherentFileVector[pos] = *it2;
492 gdcmWarningMacro( "At least 2 files with same position. No PositionPatientOrdering sort performed");
497 fileList->clear(); // doesn't delete list elements, only nodes
501 //VC++ don't understand what scope is !! it -> it3
502 for (FileVector::const_iterator it3 = CoherentFileVector.begin();
503 it3 != CoherentFileVector.end(); ++it3)
505 fileList->push_back( *it3 );
508 else // user asked for reverse order
510 FileVector::const_iterator it4;
511 it4 = CoherentFileVector.end();
515 fileList->push_back( *it4 );
516 } while (it4 != CoherentFileVector.begin() );
520 CoherentFileVector.clear();
525 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
527 return file1->GetImageNumber() < file2->GetImageNumber();
530 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
532 return file1->GetImageNumber() > file2->GetImageNumber();
535 * \brief sorts the images, according to their Image Number
536 * \note Works only on bona fide files (i.e image number is a character string
537 * corresponding to an integer)
538 * within a bona fide serie (i.e image numbers are consecutive)
539 * @param fileList Coherent File list (same Serie UID) to sort
540 * @return false if non bona fide stuff encountered
542 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
545 int n = fileList->size();
547 FileList::const_iterator it = fileList->begin();
548 min = max = (*it)->GetImageNumber();
550 for (; it != fileList->end(); ++it, ++n)
552 pos = (*it)->GetImageNumber();
553 min = (min < pos) ? min : pos;
554 max = (max > pos) ? max : pos;
557 // Find out if image numbers are coherent (consecutive)
558 if ( min == max || max == 0 || max >= (n+min) )
560 gdcmWarningMacro( " 'Image numbers' not coherent. No ImageNumberOrdering sort performed.");
564 std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
566 std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberGreaterThan );
571 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
573 return file1->GetFileName() < file2->GetFileName();
576 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
578 return file1->GetFileName() > file2->GetFileName();
581 * \brief sorts the images, according to their File Name
582 * @param fileList Coherent File list (same Serie UID) to sort
583 * @return false only if the header is bugged !
585 bool SerieHelper::FileNameOrdering(FileList *fileList)
588 std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
590 std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameGreaterThan);
596 * \brief sorts the images, according to user supplied function
597 * \note Only Direct ordering is allowed
598 * @param fileList Coherent File list (same Serie UID) to sort
599 * @return false only if the header is bugged !
601 bool SerieHelper::UserOrdering(FileList *fileList)
604 std::sort(fileList->begin(), fileList->end(), SerieHelper::UserLessThanFunction);
606 gdcmWarningMacro( " Only Direct ordering allowed "
607 << "when user function is supplied");
610 //-----------------------------------------------------------------------------
613 * \brief Canonical printer.
615 void SerieHelper::Print(std::ostream &os, std::string const &indent)
617 // For all the Coherent File lists of the gdcm::Serie
618 CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
619 if ( itl == CoherentFileListHT.end() )
621 gdcmWarningMacro( "No Coherent File list found" );
624 while (itl != CoherentFileListHT.end())
626 os << "Serie UID :[" << itl->first << "]" << std::endl;
628 // For all the files of a Coherent File list
629 for (FileList::iterator it = (itl->second)->begin();
630 it != (itl->second)->end();
633 os << indent << " --- " << (*it)->GetFileName() << std::endl;
639 //-----------------------------------------------------------------------------
640 } // end namespace gdcm