1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2005/08/30 14:15:34 $
7 Version: $Revision: 1.19 $
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"
32 //-----------------------------------------------------------------------------
34 //-----------------------------------------------------------------------------
35 // Constructor / Destructor
37 * \brief Constructor from a given SerieHelper
39 SerieHelper::SerieHelper()
41 UserLessThanFunction = 0;
43 // For all the File lists that may already exist within the gdcm::Serie
44 FileList *l = GetFirstCoherentFileList();
47 // For all the files of a File list
48 for (gdcm::FileList::iterator it = l->begin();
52 delete *it; // remove entry
55 delete l; // remove the list
56 l = GetNextCoherentFileList();
62 * \brief Canonical destructor.
64 SerieHelper::~SerieHelper()
66 // For all the Coherent File lists of the gdcm::Serie
67 FileList *l = GetFirstCoherentFileList();
70 // For all the files of a Coherent File list
71 for (FileList::iterator it = l->begin();
75 delete *it; // remove entry
78 delete l; // remove the list
79 l = GetNextCoherentFileList();
83 //-----------------------------------------------------------------------------
85 //-----------------------------------------------------------------------------
89 * \brief add a gdcm::File to the list corresponding to its Serie UID
90 * @param filename Name of the file to deal with
92 void SerieHelper::AddFileName(std::string const &filename)
94 // Create a DICOM file
95 File *header = new File ();
96 header->SetLoadMode(LoadMode);
97 header->SetFileName( filename );
100 if ( header->IsReadable() )
103 // First step the user has defined a set of rules for the DICOM file
104 // he is looking for.
105 // make sure the file correspond to his set of rules:
108 for(SerieRestrictions::iterator it = Restrictions.begin();
109 it != Restrictions.end();
113 // doesn't compile (no matching function...).
114 const std::string s;// = header->GetEntryValue( r.first );
115 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
117 // Argh ! This rule is unmatch let's just quit
123 // Just keep 'new style' for Rules
125 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
126 it2 != ExRestrictions.end();
129 const ExRule &r = *it2;
130 s = header->GetEntryValue( r.group, r.elem );
131 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
133 // Argh ! This rule is unmatch let's just quit
139 if ( allrules ) // all rules are respected:
141 // Allright ! we have a found a DICOM that match the user expectation.
144 // 0020 000e UI REL Series Instance UID
145 const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
146 // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
147 // no need here to do anything special
149 if ( CoherentFileListHT.count(uid) == 0 )
151 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
152 // create a std::list in 'uid' position
153 CoherentFileListHT[uid] = new FileList;
155 // Current Serie UID and DICOM header seems to match; add the file:
156 CoherentFileListHT[uid]->push_back( header );
160 // at least one rule was unmatch we need to deallocate the file:
166 gdcmWarningMacro("Could not read file: " << filename );
172 * \brief add a gdcm::File to the first (and supposed to be unique) list
173 * of the gdcm::SerieHelper.
174 * \warning : this method should be used by aware users only!
175 * User is supposed to know the files he want to deal with
176 * and consider them they belong to the same Serie
177 * (even if their Serie UID is different)
178 * user will probabely OrderFileList() this list (actually, ordering
179 * user choosen gdm::File is the sole interest of this method)
180 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
181 * vtkGdcmReader parsing twice the same files.
182 * *no* coherence check is performed, but those specified
183 * by SerieHelper::AddRestriction()
184 * @param header gdcm::File* of the file to deal with
186 void SerieHelper::AddGdcmFile(File *header)
189 // First step the user has defined a set of rules for the DICOM
190 // he is looking for.
191 // make sure the file correspond to his set of rules:
192 for(SerieRestrictions::iterator it = Restrictions.begin();
193 it != Restrictions.end();
197 const std::string s;// = header->GetEntryValue( r.first );
198 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
200 // Argh ! This rule is unmatch let's just quit
205 if ( allrules ) // all rules are respected:
207 // Allright ! we have a found a DICOM that match the user expectation.
210 const std::string &uid = "0";
211 // Serie UID of the gdcm::File* may be different.
212 // User is supposed to know what he wants
214 if ( CoherentFileListHT.count(uid) == 0 )
216 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
217 // create a std::list in 'uid' position
218 CoherentFileListHT[uid] = new FileList;
220 // Current Serie UID and DICOM header seems to match; add the file:
221 CoherentFileListHT[uid]->push_back( header );
223 // Even if a rule was unmatch we don't deallocate the gdcm::File:
227 * \brief add a rules for restricting a DICOM file to be in the serie we are
228 * trying to find. For example you can select only the DICOM file from a
229 * directory which would have a particular EchoTime==4.0.
230 * This method is a user level, value is not required to be formatted as a DICOM
233 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
234 std::string const &value, int op)
241 ExRestrictions.push_back( r );
244 #ifndef GDCM_LEGACY_REMOVE
246 * \brief add a rules for restricting a DICOM file to be in the serie we are
247 * trying to find. For example you can select only the DICOM file from a
248 * directory which would have a particular EchoTime==4.0.
249 * This method is a user level, value is not required to be formatted as a DICOM
251 * @deprecated use : AddRestriction(uint16_t group, uint16_t elem,
252 * std::string const &value, int op);
254 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
259 Restrictions.push_back( r );
264 * \brief Sets the root Directory
265 * @param dir Name of the directory to deal with
266 * @param recursive whether we want explore recursively the Directory
268 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
270 DirList dirList(dir, recursive); // OS specific
272 DirListType filenames_list = dirList.GetFilenames();
273 for( DirListType::const_iterator it = filenames_list.begin();
274 it != filenames_list.end(); ++it)
281 * \brief Sorts the given File List
282 * \warning This could be implemented in a 'Strategy Pattern' approach
283 * But as I don't know how to do it, I leave it this way
284 * BTW, this is also a Strategy, I don't know this is the best approach :)
286 void SerieHelper::OrderFileList(FileList *coherentFileList)
289 if ( SerieHelper::UserLessThanFunction )
291 UserOrdering( coherentFileList );
294 else if ( ImagePositionPatientOrdering( coherentFileList ) )
298 else if ( ImageNumberOrdering(coherentFileList ) )
304 FileNameOrdering(coherentFileList );
309 * \brief Elementary coherence checking of the files with the same Serie UID
310 * Only sizes and pixel type are checked right now ...
312 bool SerieHelper::IsCoherent(FileList *coherentFileList)
314 if(coherentFileList->size() == 1)
317 FileList::const_iterator it = coherentFileList->begin();
319 int nX = (*it)->GetXSize();
320 int nY = (*it)->GetYSize();
321 int pixelSize = (*it)->GetPixelSize();
325 it != coherentFileList->end();
328 if ( (*it)->GetXSize() != nX )
330 if ( (*it)->GetYSize() != nY )
332 if ( (*it)->GetPixelSize() != pixelSize )
334 // probabely more is to be checked (?)
339 * \brief Get the first List while visiting the CoherentFileListHT
340 * @return The first FileList if found, otherwhise NULL
342 FileList *SerieHelper::GetFirstCoherentFileList()
344 ItListHt = CoherentFileListHT.begin();
345 if ( ItListHt != CoherentFileListHT.end() )
346 return ItListHt->second;
351 * \brief Get the next List while visiting the CoherentFileListHT
352 * \note : meaningfull only if GetFirstCoherentFileList() already called
353 * @return The next FileList if found, otherwhise NULL
355 FileList *SerieHelper::GetNextCoherentFileList()
357 gdcmAssertMacro (ItListHt != CoherentFileListHT.end());
360 if ( ItListHt != CoherentFileListHT.end() )
361 return ItListHt->second;
366 * \brief Get the Coherent Files list according to its Serie UID
367 * @param SerieUID SerieUID
368 * \return pointer to the Coherent Files list if found, otherwhise NULL
370 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
372 if ( CoherentFileListHT.count(SerieUID) == 0 )
374 return CoherentFileListHT[SerieUID];
377 //-----------------------------------------------------------------------------
380 //-----------------------------------------------------------------------------
383 * \brief sorts the images, according to their Patient Position
384 * We may order, considering :
385 * -# Image Position Patient
387 * -# More to come :-)
388 * WARNING : FileList = std::vector<File* >
389 * @param fileList Coherent File list (same Serie UID) to sort
390 * @return false only if the header is bugged !
392 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
393 //based on Jolinda Smith's algorithm
395 //iop is calculated based on the file file
400 float min = 0, max = 0;
403 std::vector<float> distlist;
405 //!\todo rewrite this for loop.
406 for ( FileList::const_iterator
407 it = fileList->begin();
408 it != fileList->end(); ++it )
412 (*it)->GetImageOrientationPatient( cosines );
414 // You only have to do this once for all slices in the volume. Next,
415 // for each slice, calculate the distance along the slice normal
416 // using the IPP tag ("dist" is initialized to zero before reading
417 // the first slice) :
418 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
419 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
420 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
422 ipp[0] = (*it)->GetXOrigin();
423 ipp[1] = (*it)->GetYOrigin();
424 ipp[2] = (*it)->GetZOrigin();
427 for ( int i = 0; i < 3; ++i )
429 dist += normal[i]*ipp[i];
432 distlist.push_back( dist );
439 ipp[0] = (*it)->GetXOrigin();
440 ipp[1] = (*it)->GetYOrigin();
441 ipp[2] = (*it)->GetZOrigin();
444 for ( int i = 0; i < 3; ++i )
446 dist += normal[i]*ipp[i];
449 distlist.push_back( dist );
451 min = (min < dist) ? min : dist;
452 max = (max > dist) ? max : dist;
457 // Then I order the slices according to the value "dist". Finally, once
458 // I've read in all the slices, I calculate the z-spacing as the difference
459 // between the "dist" values for the first two slices.
460 FileVector CoherentFileVector(n);
461 // CoherentFileVector.reserve( n );
462 CoherentFileVector.resize( n );
463 // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
465 // Find out if min/max are coherent
468 gdcmWarningMacro( "Looks like all images have the exact same image position."
469 << "No PositionPatientOrdering sort performed" );
473 float step = (max - min)/(n - 1);
477 //VC++ don't understand what scope is !! it -> it2
478 for (FileList::const_iterator it2 = fileList->begin();
479 it2 != fileList->end(); ++it2, ++n)
482 //Assumption: all files are present (no one missing)
483 pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
485 // a Dicom 'Serie' may contain scout views
486 // and images may have differents directions
487 // -> More than one may have the same 'pos'
488 // Sorting has then NO meaning !
489 if (CoherentFileVector[pos]==NULL)
490 CoherentFileVector[pos] = *it2;
493 gdcmWarningMacro( "At least 2 files with same position. No PositionPatientOrdering sort performed");
498 fileList->clear(); // doesn't delete list elements, only nodes
502 //VC++ don't understand what scope is !! it -> it3
503 for (FileVector::const_iterator it3 = CoherentFileVector.begin();
504 it3 != CoherentFileVector.end(); ++it3)
506 fileList->push_back( *it3 );
509 else // user asked for reverse order
511 FileVector::const_iterator it4;
512 it4 = CoherentFileVector.end();
516 fileList->push_back( *it4 );
517 } while (it4 != CoherentFileVector.begin() );
521 CoherentFileVector.clear();
526 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
528 return file1->GetImageNumber() < file2->GetImageNumber();
531 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
533 return file1->GetImageNumber() > file2->GetImageNumber();
536 * \brief sorts the images, according to their Image Number
537 * \note Works only on bona fide files (i.e image number is a character string
538 * corresponding to an integer)
539 * within a bona fide serie (i.e image numbers are consecutive)
540 * @param fileList Coherent File list (same Serie UID) to sort
541 * @return false if non bona fide stuff encountered
543 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
546 int n = fileList->size();
548 FileList::const_iterator it = fileList->begin();
549 min = max = (*it)->GetImageNumber();
551 for (; it != fileList->end(); ++it, ++n)
553 pos = (*it)->GetImageNumber();
554 min = (min < pos) ? min : pos;
555 max = (max > pos) ? max : pos;
558 // Find out if image numbers are coherent (consecutive)
559 if ( min == max || max == 0 || max >= (n+min) )
561 gdcmWarningMacro( " 'Image numbers' not coherent. No ImageNumberOrdering sort performed.");
565 std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
567 std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberGreaterThan );
572 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
574 return file1->GetFileName() < file2->GetFileName();
577 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
579 return file1->GetFileName() > file2->GetFileName();
582 * \brief sorts the images, according to their File Name
583 * @param fileList Coherent File list (same Serie UID) to sort
584 * @return false only if the header is bugged !
586 bool SerieHelper::FileNameOrdering(FileList *fileList)
589 std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
591 std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameGreaterThan);
597 * \brief sorts the images, according to user supplied function
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)
603 std::sort(fileList->begin(), fileList->end(), SerieHelper::UserLessThanFunction);
606 std::reverse(fileList->begin(), fileList->end());
611 //-----------------------------------------------------------------------------
614 * \brief Canonical printer.
616 void SerieHelper::Print(std::ostream &os, std::string const &indent)
618 // For all the Coherent File lists of the gdcm::Serie
619 CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
620 if ( itl == CoherentFileListHT.end() )
622 gdcmWarningMacro( "No Coherent File list found" );
625 while (itl != CoherentFileListHT.end())
627 os << "Serie UID :[" << itl->first << "]" << std::endl;
629 // For all the files of a Coherent File list
630 for (FileList::iterator it = (itl->second)->begin();
631 it != (itl->second)->end();
634 os << indent << " --- " << (*it)->GetFileName() << std::endl;
640 //-----------------------------------------------------------------------------
641 } // end namespace gdcm