1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2005/10/17 09:52:41 $
7 Version: $Revision: 1.21 $
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 //-----------------------------------------------------------------------------
35 //-----------------------------------------------------------------------------
36 // Constructor / Destructor
38 * \brief Constructor from a given SerieHelper
40 SerieHelper::SerieHelper()
43 UserLessThanFunction = 0;
48 * \brief Canonical destructor.
50 SerieHelper::~SerieHelper()
56 * \brief - Preventively, clear everything at constructor time.
57 * - use it at destructor time.
59 void SerieHelper::ClearAll()
61 // For all the 'Single SerieUID' Filesets that may already exist
62 FileList *l = GetFirstSingleSerieUIDFileSet();
65 // For all the gdcm::File of a File set
66 for (gdcm::FileList::iterator it = l->begin();
70 delete *it; // remove each entry
73 delete l; // remove the container
74 l = GetNextSingleSerieUIDFileSet();
78 //-----------------------------------------------------------------------------
80 //-----------------------------------------------------------------------------
84 * \brief add a gdcm::File to the Fileset corresponding to its Serie UID
85 * @param filename Name of the file to deal with
87 void SerieHelper::AddFileName(std::string const &filename)
89 // Create a DICOM file
90 File *header = new File ();
91 header->SetLoadMode(LoadMode);
92 header->SetFileName( filename );
95 if ( header->IsReadable() )
98 // First step : the user defined a set of rules for the DICOM file
100 // Make sure the file corresponds to his set of rules:
103 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
104 it2 != ExRestrictions.end();
107 const ExRule &r = *it2;
108 s = header->GetEntryValue( r.group, r.elem );
109 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
111 // Argh ! This rule is unmatched; let's just quit
117 if ( allrules ) // all rules are respected:
119 // Allright! we have a found a DICOM that matches the user expectation.
122 // 0020 000e UI REL Series Instance UID
123 const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
124 // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
125 // no need here to do anything special
127 if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
129 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
130 // create a std::list in 'uid' position
131 SingleSerieUIDFileSetHT[uid] = new FileList;
133 // Current Serie UID and DICOM header seems to match; add the file:
134 SingleSerieUIDFileSetHT[uid]->push_back( header );
138 // at least one rule was unmatched we need to deallocate the file:
144 gdcmWarningMacro("Could not read file: " << filename );
150 * \brief add a gdcm::File to the first (and supposed to be unique) file set
151 * of the gdcm::SerieHelper.
152 * \warning : this method should be used by aware users only!
153 * Passing a gdcm::File* has the same effect than passing a file name!
154 * \TODO : decide which one is wrong (the method, or the commentary)!
155 * the following comment doesn't match the method :-(
156 * User is supposed to know the files he want to deal with
157 * and consider them they belong to the same Serie
158 * (even if their Serie UID is different)
159 * user will probabely OrderFileList() this list (actually, ordering
160 * user choosen gdm::File is the sole interest of this method)
161 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
162 * vtkGdcmReader parsing twice the same files.
163 * *no* coherence check is performed, but those specified
164 * by SerieHelper::AddRestriction()
165 * @param header gdcm::File* of the file to deal with
167 void SerieHelper::AddGdcmFile(File *header)
170 // First step the user has defined a set of rules for the DICOM
171 // he is looking for.
172 // make sure the file correspond to his set of rules:
173 for(SerieRestrictions::iterator it = Restrictions.begin();
174 it != Restrictions.end();
178 const std::string s;// = header->GetEntryValue( r.first );
179 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
181 // Argh ! This rule is unmatch let's just quit
186 if ( allrules ) // all rules are respected:
188 // Allright ! we have a found a DICOM that match the user expectation.
191 const std::string &uid = "0";
192 // Serie UID of the gdcm::File* may be different.
193 // User is supposed to know what he wants
195 if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
197 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
198 // create a std::list in 'uid' position
199 SingleSerieUIDFileSetHT[uid] = new FileList;
201 // Current Serie UID and DICOM header seems to match; add the file:
202 SingleSerieUIDFileSetHT[uid]->push_back( header );
204 // Even if a rule was unmatch we don't deallocate the gdcm::File:
208 * \brief add a rules for restricting a DICOM file to be in the serie we are
209 * trying to find. For example you can select only the DICOM file from a
210 * directory which would have a particular EchoTime==4.0.
211 * This method is a user level, value is not required to be formatted as a DICOM
213 * @param group Group number of the target tag.
214 * @param elem Element number of the target tag.
215 * @param value value to be checked to exclude File
216 * @param op operator we want to use to check
218 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
219 std::string const &value, int op)
226 ExRestrictions.push_back( r );
229 #ifndef GDCM_LEGACY_REMOVE
231 * \brief add a rules for restricting a DICOM file to be in the serie we are
232 * trying to find. For example you can select only the DICOM file from a
233 * directory which would have a particular EchoTime==4.0.
234 * This method is a user level, value is not required to be formatted as a DICOM
236 * @param group Group number of the target tag.
237 * @param elem Element number of the target tag.
238 * @param value value to be checked to exclude File
239 * @deprecated use : AddRestriction(uint16_t group, uint16_t elem,
240 * std::string const &value, int op);
242 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
247 Restrictions.push_back( r );
252 * \brief Sets the root Directory
253 * @param dir Name of the directory to deal with
254 * @param recursive whether we want explore recursively the root Directory
256 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
258 DirList dirList(dir, recursive); // OS specific
260 DirListType filenames_list = dirList.GetFilenames();
261 for( DirListType::const_iterator it = filenames_list.begin();
262 it != filenames_list.end(); ++it)
269 * \brief Sorts the given Fileset
270 * \warning This could be implemented in a 'Strategy Pattern' approach
271 * But as I don't know how to do it, I leave it this way
272 * BTW, this is also a Strategy, I don't know this is
273 * the best approach :)
275 void SerieHelper::OrderFileList(FileList *fileSet)
278 if ( SerieHelper::UserLessThanFunction )
280 UserOrdering( fileSet );
283 else if ( ImagePositionPatientOrdering( fileSet ) )
287 else if ( ImageNumberOrdering(fileSet ) )
293 FileNameOrdering(fileSet );
298 * \brief Elementary coherence checking of the files with the same Serie UID
299 * Only sizes and pixel type are checked right now ...
301 bool SerieHelper::IsCoherent(FileList *fileSet)
303 if(fileSet->size() == 1)
306 FileList::const_iterator it = fileSet->begin();
308 int nX = (*it)->GetXSize();
309 int nY = (*it)->GetYSize();
310 int pixelSize = (*it)->GetPixelSize();
314 it != fileSet->end();
317 if ( (*it)->GetXSize() != nX )
319 if ( (*it)->GetYSize() != nY )
321 if ( (*it)->GetPixelSize() != pixelSize )
323 // probabely more is to be checked (?)
328 #ifndef GDCM_LEGACY_REMOVE
330 * \brief accessor (DEPRECATED : use GetFirstSingleSerieUIDFileSet )
331 * Warning : 'coherent' means here they have the same Serie UID
332 * @return The first FileList if found, otherwhise NULL
334 FileList *SerieHelper::GetFirstCoherentFileList()
336 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
337 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
338 return ItFileSetHt->second;
343 * \brief accessor (DEPRECATED : use GetNextSingleSerieUIDFileSet )
344 * Warning : 'coherent' means here they have the same Serie UID
345 * \note : meaningfull only if GetFirstCoherentFileList() already called
346 * @return The next FileList if found, otherwhise NULL
348 FileList *SerieHelper::GetNextCoherentFileList()
350 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
353 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
354 return ItFileSetHt->second;
359 * \brief accessor (DEPRECATED : use GetSingleSerieUIDFileSet )
360 * Warning : 'coherent' means here they have the same Serie UID
361 * @param SerieUID SerieUID
362 * \return pointer to the FileList if found, otherwhise NULL
364 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
366 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
368 return SingleSerieUIDFileSetHT[SerieUID];
374 * \brief Get the first Fileset while visiting the SingleSerieUIDFileSetmap
375 * @return The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
377 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
379 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
380 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
381 return ItFileSetHt->second;
386 * \brief Get the next Fileset while visiting the SingleSerieUIDFileSetmap
387 * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called
388 * @return The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
390 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
392 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
395 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
396 return ItFileSetHt->second;
401 * \brief Get the SingleSerieUIDFileSet according to its Serie UID
402 * @param SerieUID SerieUID to retrieve
403 * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
405 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
407 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
409 return SingleSerieUIDFileSetHT[SerieUID];
413 * \brief Splits a Single SerieUID Fileset according to the Orientations
414 * @param fileSet File Set to be splitted
415 * \return std::map of 'Xcoherent' File sets
418 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
420 XCoherentFileSetmap CoherentFileSet;
422 int nb = fileSet->size();
424 return CoherentFileSet;
426 std::ostringstream ossOrient;
427 std::string strOrient;
429 FileList::const_iterator it = fileSet->begin();
432 it != fileSet->end();
435 // Information is in :
436 // 0020 0037 : Image Orientation (Patient) or
437 // 0020 0035 : Image Orientation (RET)
439 // Let's build again the 'cosines' string, to be sure of it's format
440 (*it)->GetImageOrientationPatient(iop);
442 for (int i = 1; i < 6; i++)
447 strOrient = ossOrient.str();
449 if ( CoherentFileSet.count(strOrient) == 0 )
451 gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
452 // create a File set in 'orientation' position
453 CoherentFileSet[strOrient] = new FileList;
455 // Current Orientation and DICOM header match; add the file:
456 CoherentFileSet[strOrient]->push_back( (*it) );
458 return CoherentFileSet;
462 * \brief Splits a Single SerieUID Fileset according to the Positions
463 * @param fileSet File Set to be splitted
464 * \return std::map of 'Xcoherent' File sets
467 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
469 XCoherentFileSetmap CoherentFileSet;
471 int nb = fileSet->size();
473 return CoherentFileSet;
475 std::string strImPos; // read on disc
476 std::ostringstream ossPosition;
477 std::string strPosition; // re computed
478 FileList::const_iterator it = fileSet->begin();
481 it != fileSet->end();
484 // Information is in :
485 // 0020,0032 : Image Position Patient
486 // 0020,0030 : Image Position (RET)
488 std::string strImPos = (*it)->GetEntryValue(0x0020,0x0032);
489 if ( strImPos == GDCM_UNFOUND)
491 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
492 strImPos = (*it)->GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
493 if ( strImPos == GDCM_UNFOUND )
495 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
496 // User wants to split on the 'Position'
497 // No 'Position' info found.
498 // We return an empty Htable !
499 return CoherentFileSet;
503 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ",
504 &pos[0], &pos[1], &pos[2]) != 3 )
506 gdcmWarningMacro( "Wrong number for Position : ["
507 << strImPos << "]" );
508 return CoherentFileSet;
511 // Let's build again the 'position' string, to be sure of it's format
513 ossPosition << pos[0];
514 for (int i = 1; i < 3; i++)
517 ossPosition << pos[i];
519 strPosition = ossPosition.str();
521 if ( CoherentFileSet.count(strPosition) == 0 )
523 gdcmDebugMacro(" New Position :[" << strPosition << "]");
524 // create a File set in 'position' position
525 CoherentFileSet[strPosition] = new FileList;
527 // Current Position and DICOM header match; add the file:
528 CoherentFileSet[strPosition]->push_back( (*it) );
530 return CoherentFileSet;
534 * \brief Splits a SingleSerieUID File set Coherent according to the
535 * value of a given Tag
536 * @param fileSet File Set to be splitted
537 * \return std::map of 'Xcoherent' File sets
540 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet,
541 uint16_t group, uint16_t element)
543 XCoherentFileSetmap CoherentFileSet;
545 int nb = fileSet->size();
547 return CoherentFileSet;
549 std::string strTagValue; // read on disc
551 FileList::const_iterator it = fileSet->begin();
554 it != fileSet->end();
557 // Information is in :
558 // 0020,0032 : Image Position Patient
559 // 0020,0030 : Image Position (RET)
561 std::string strTagValue = (*it)->GetEntryValue(group,element);
563 if ( CoherentFileSet.count(strTagValue) == 0 )
565 gdcmDebugMacro(" New Tag Value :[" << strTagValue << "]");
566 // create a File set in 'position' position
567 CoherentFileSet[strTagValue] = new FileList;
569 // Current Tag value and DICOM header match; add the file:
570 CoherentFileSet[strTagValue]->push_back( (*it) );
572 return CoherentFileSet;
575 //-----------------------------------------------------------------------------
578 //-----------------------------------------------------------------------------
581 * \brief sorts the images, according to their Patient Position
582 * We may order, considering :
583 * -# Image Position Patient
585 * -# More to come :-)
586 * WARNING : FileList = std::vector<File* >
587 * @param fileList Coherent File list (same Serie UID) to sort
588 * @return false only if the header is bugged !
590 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
591 //based on Jolinda Smith's algorithm
593 //iop is calculated based on the file file
598 float min = 0, max = 0;
601 std::vector<float> distlist;
603 //!\todo rewrite this for loop.
604 for ( FileList::const_iterator
605 it = fileList->begin();
606 it != fileList->end(); ++it )
610 (*it)->GetImageOrientationPatient( cosines );
612 // You only have to do this once for all slices in the volume. Next,
613 // for each slice, calculate the distance along the slice normal
614 // using the IPP ("Image Position Patient") tag.
615 // ("dist" is initialized to zero before reading the first slice) :
616 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
617 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
618 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
620 ipp[0] = (*it)->GetXOrigin();
621 ipp[1] = (*it)->GetYOrigin();
622 ipp[2] = (*it)->GetZOrigin();
625 for ( int i = 0; i < 3; ++i )
627 dist += normal[i]*ipp[i];
630 distlist.push_back( dist );
637 ipp[0] = (*it)->GetXOrigin();
638 ipp[1] = (*it)->GetYOrigin();
639 ipp[2] = (*it)->GetZOrigin();
642 for ( int i = 0; i < 3; ++i )
644 dist += normal[i]*ipp[i];
647 distlist.push_back( dist );
649 min = (min < dist) ? min : dist;
650 max = (max > dist) ? max : dist;
655 // Then I order the slices according to the value "dist". Finally, once
656 // I've read in all the slices, I calculate the z-spacing as the difference
657 // between the "dist" values for the first two slices.
658 FileVector CoherentFileVector(n);
659 // CoherentFileVector.reserve( n );
660 CoherentFileVector.resize( n );
661 // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
663 // Find out if min/max are coherent
666 gdcmWarningMacro("Looks like all images have the exact same image position"
667 << ". No PositionPatientOrdering sort performed" );
671 float step = (max - min)/(n - 1);
675 //VC++ don't understand what scope is !! it -> it2
676 for (FileList::const_iterator it2 = fileList->begin();
677 it2 != fileList->end(); ++it2, ++n)
680 //Assumption: all files are present (no one missing)
681 pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
683 // a Dicom 'Serie' may contain scout views
684 // and images may have differents directions
685 // -> More than one may have the same 'pos'
686 // Sorting has then NO meaning !
687 if (CoherentFileVector[pos]==NULL)
688 CoherentFileVector[pos] = *it2;
691 gdcmWarningMacro( "At least 2 files with same position."
692 << " No PositionPatientOrdering sort performed");
697 fileList->clear(); // doesn't delete list elements, only nodes
701 //VC++ don't understand what scope is !! it -> it3
702 for (FileVector::const_iterator it3 = CoherentFileVector.begin();
703 it3 != CoherentFileVector.end(); ++it3)
705 fileList->push_back( *it3 );
708 else // user asked for reverse order
710 FileVector::const_iterator it4;
711 it4 = CoherentFileVector.end();
715 fileList->push_back( *it4 );
716 } while (it4 != CoherentFileVector.begin() );
720 CoherentFileVector.clear();
725 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
727 return file1->GetImageNumber() < file2->GetImageNumber();
730 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
732 return file1->GetImageNumber() > file2->GetImageNumber();
736 * \brief sorts the images, according to their Image Number
737 * \note Works only on bona fide files (i.e image number is a character string
738 * corresponding to an integer)
739 * within a bona fide serie (i.e image numbers are consecutive)
740 * @param fileList Coherent File list (same Serie UID) to sort
741 * @return false if non bona fide stuff encountered
743 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
746 int n = fileList->size();
748 FileList::const_iterator it = fileList->begin();
749 min = max = (*it)->GetImageNumber();
751 for (; it != fileList->end(); ++it, ++n)
753 pos = (*it)->GetImageNumber();
754 min = (min < pos) ? min : pos;
755 max = (max > pos) ? max : pos;
758 // Find out if image numbers are coherent (consecutive)
759 if ( min == max || max == 0 || max >= (n+min) )
761 gdcmWarningMacro( " 'Image numbers' not coherent. "
762 << " No ImageNumberOrdering sort performed.");
766 std::sort(fileList->begin(), fileList->end(),
767 SerieHelper::ImageNumberLessThan );
769 std::sort(fileList->begin(), fileList->end(),
770 SerieHelper::ImageNumberGreaterThan );
775 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
777 return file1->GetFileName() < file2->GetFileName();
780 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
782 return file1->GetFileName() > file2->GetFileName();
785 * \brief sorts the images, according to their File Name
786 * @param fileList Coherent File list (same Serie UID) to sort
787 * @return false only if the header is bugged !
789 bool SerieHelper::FileNameOrdering(FileList *fileList)
792 std::sort(fileList->begin(), fileList->end(),
793 SerieHelper::FileNameLessThan);
795 std::sort(fileList->begin(), fileList->end(),
796 SerieHelper::FileNameGreaterThan);
802 * \brief sorts the images, according to user supplied function
803 * @param fileList Coherent File list (same Serie UID) to sort
804 * @return false only if the header is bugged !
806 bool SerieHelper::UserOrdering(FileList *fileList)
808 std::sort(fileList->begin(), fileList->end(),
809 SerieHelper::UserLessThanFunction);
812 std::reverse(fileList->begin(), fileList->end());
817 //-----------------------------------------------------------------------------
820 * \brief Canonical printer.
822 void SerieHelper::Print(std::ostream &os, std::string const &indent)
824 // For all the Coherent File lists of the gdcm::Serie
825 SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
826 if ( itl == SingleSerieUIDFileSetHT.end() )
828 gdcmWarningMacro( "No SingleSerieUID File set found" );
831 while (itl != SingleSerieUIDFileSetHT.end())
833 os << "Serie UID :[" << itl->first << "]" << std::endl;
835 // For all the files of a SingleSerieUID File set
836 for (FileList::iterator it = (itl->second)->begin();
837 it != (itl->second)->end();
840 os << indent << " --- " << (*it)->GetFileName() << std::endl;
846 //-----------------------------------------------------------------------------
847 } // end namespace gdcm