1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2007/10/01 09:28:57 $
7 Version: $Revision: 1.62 $
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 : no more !
23 #include "gdcmDebug.h"
30 #include <stdio.h> //for sscanf
32 namespace GDCM_NAME_SPACE
35 //-----------------------------------------------------------------------------
36 // Constructor / Destructor
38 * \brief Constructor from a given SerieHelper
40 SerieHelper::SerieHelper()
42 m_UseSeriesDetails = false;
44 UserLessThanFunction = 0;
50 * \brief Canonical destructor.
52 SerieHelper::~SerieHelper()
58 * \brief Preventively, clear everything at constructor time.
59 * ( use it at destructor time.)
61 void SerieHelper::ClearAll()
63 // For all the 'Single SerieUID' Filesets that may already exist
64 FileList *l = GetFirstSingleSerieUIDFileSet();
67 // For all the GDCM_NAME_SPACE::File of a File set
68 for (GDCM_NAME_SPACE::FileList::iterator it = l->begin();
72 (*it)->Delete(); // remove each entry
75 delete l; // remove the container
76 l = GetNextSingleSerieUIDFileSet();
78 // Need to clear that too:
79 SingleSerieUIDFileSetHT.clear();
82 //-----------------------------------------------------------------------------
84 //-----------------------------------------------------------------------------
88 * \brief add a GDCM_NAME_SPACE::File to the Fileset 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 = File::New();
95 header->SetLoadMode(LoadMode);
96 header->SetFileName( filename );
99 if ( header->IsReadable() )
101 if ( !AddFile( header ) )
103 // at least one rule was unmatched we need to deallocate the file:
109 gdcmWarningMacro("Could not read file: " << filename );
115 * \brief add a GDCM_NAME_SPACE::File to the first (and supposed to be unique) file set
116 * of the GDCM_NAME_SPACE::SerieHelper.
117 * \warning : this method should be used by aware users only!
118 * Passing a GDCM_NAME_SPACE::File* has the same effect than passing a file name!
119 * \todo : decide which one is wrong (the method, or the commentary)!
120 * the following comment doesn't match the method :-(
121 * User is supposed to know the files he want to deal with
122 * and consider them they belong to the same Serie
123 * (even if their Serie UID is different)
124 * user will probabely OrderFileList() this list (actually, ordering
125 * user choosen gdm::File is the sole interest of this method)
126 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
127 * vtkGdcmReader parsing twice the same files.
128 * *no* coherence check is performed, but those specified
129 * by SerieHelper::AddRestriction()
130 * @param header GDCM_NAME_SPACE::File* of the file to deal with
131 * @return true if file was added, false if file was rejected
133 bool SerieHelper::AddFile(File *header)
136 // First step the user has defined a set of rules for the DICOM
137 // he is looking for.
138 // make sure the file correspond to his set of rules:
141 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
142 it2 != ExRestrictions.end();
145 const ExRule &r = *it2;
146 s = header->GetEntryString( r.group, r.elem );
147 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
149 // Argh ! This rule is unmatched; let's just quit
155 if ( allrules ) // all rules are respected:
157 // Allright! we have a found a DICOM that matches the user expectation.
158 // Let's add it to the specific 'id' which by default is uid (Serie UID)
159 // but can be `refined` by user with more paramater (see AddRestriction(g,e))
161 std::string id = CreateUniqueSeriesIdentifier( header );
162 // if id == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
163 // no need here to do anything special
165 if ( SingleSerieUIDFileSetHT.count(id) == 0 )
167 gdcmDebugMacro(" New/gdcmSerieHelper.cxx Serie UID :[" << id << "]");
168 // create a std::list in 'id' position
169 SingleSerieUIDFileSetHT[id] = new FileList;
171 // Current Serie UID and DICOM header seems to match add the file:
172 SingleSerieUIDFileSetHT[id]->push_back( header );
176 // one rule not matched, tell user:
183 * \brief add a rule for restricting a DICOM file to be in the serie we are
184 * trying to find. For example you can select only the DICOM files from a
185 * directory which would have a particular EchoTime==4.0.
186 * This method is a user level, value is not required to be formatted as a DICOM
188 * \todo find a trick to allow user to say if he wants the Rectrictions
189 * to be *ored* (and not only *anded*)
190 * @param key Target tag we want restrict on a given value
191 * @param value value to be checked to exclude File
192 * @param op operator we want to use to check
194 void SerieHelper::AddRestriction(TagKey const &key,
195 std::string const &value, int op)
202 ExRestrictions.push_back( r );
205 void SerieHelper::AddRestriction(TagKey const &key)
210 ExRefine.push_back( r );
213 //#ifndef GDCM_LEGACY_REMOVE
215 * \brief add a rule for restricting a DICOM file to be in the serie we are
216 * trying to find. For example you can select only the DICOM files from a
217 * directory which would have a particular EchoTime==4.0.
218 * This method is a user level, value is not required to be formatted as a DICOM
220 * @param group tag group number we want restrict on a given value
221 * @param elem tag element number we want restrict on a given value
222 * @param value value to be checked to exclude File
223 * @param op operator we want to use to check
224 * @deprecated use : AddRestriction(TagKey const &key,
225 * std::string const &value, int op);
228 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
229 std::string const &value, int op)
231 TagKey t(group, elem);
232 AddRestriction(t, value, op);
238 * \brief add an extra 'SerieDetail' for building a 'Serie Identifier'
239 * that ensures (hope so) File consistency (Series Instance UID doesn't)
240 * @param group tag group number we want restrict on a given value
241 * @param elem tag element number we want restrict on a given value
242 * @param convert wether we want 'convertion', to allow further ordering
243 * e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK
245 void SerieHelper::AddSeriesDetail(uint16_t group, uint16_t elem, bool convert)
251 ExDetails.push_back( d );
254 * \brief Sets the root Directory
255 * @param dir Name of the directory to deal with
256 * @param recursive whether we want explore recursively the root Directory
258 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
260 DirList dirList(dir, recursive); // OS specific
262 DirListType filenames_list = dirList.GetFilenames();
263 for( DirListType::const_iterator it = filenames_list.begin();
264 it != filenames_list.end(); ++it)
271 * \brief Sets the DicomDirSerie
272 * @param se DicomDirSerie to deal with
274 void SerieHelper::SetDicomDirSerie(DicomDirSerie *se)
278 DirListType filenames_list = dirList.GetFilenames();
279 for( DirListType::const_iterator it = filenames_list.begin();
280 it != filenames_list.end(); ++it)
287 * \brief Sorts the given Fileset
288 * \warning This could be implemented in a 'Strategy Pattern' approach
289 * But as I don't know how to do it, I leave it this way
290 * BTW, this is also a Strategy, I don't know this is
291 * the best approach :)
293 void SerieHelper::OrderFileList(FileList *fileSet)
295 // Only computed during ImagePositionPatientOrdering
296 // (need to sort the FileList using IPP and IOP !)
299 if ( SerieHelper::UserLessThanFunction )
301 gdcmDebugMacro("Use UserLessThanFunction");
302 UserOrdering( fileSet );
305 else if ( ImagePositionPatientOrdering( fileSet ) )
307 gdcmDebugMacro("ImagePositionPatientOrdering succeeded");
310 else if ( ImageNumberOrdering(fileSet ) )
312 gdcmDebugMacro("ImageNumberOrdering succeeded");
317 gdcmDebugMacro("Use FileNameOrdering");
318 FileNameOrdering(fileSet );
323 * \brief Elementary coherence checking of the files with the same Serie UID
324 * Only sizes and pixel type are checked right now ...
326 bool SerieHelper::IsCoherent(FileList *fileSet)
328 if(fileSet->size() == 1)
331 FileList::const_iterator it = fileSet->begin();
333 int nX = (*it)->GetXSize();
334 int nY = (*it)->GetYSize();
335 int pixelSize = (*it)->GetPixelSize();
336 bool signedPixelData = (*it)->IsSignedPixelData();
339 it != fileSet->end();
342 if ( (*it)->GetXSize() != nX )
344 if ( (*it)->GetYSize() != nY )
346 if ( (*it)->GetPixelSize() != pixelSize )
348 if ( (*it)->IsSignedPixelData() != signedPixelData )
350 // probabely more is to be checked (?)
355 //#ifndef GDCM_LEGACY_REMOVE
357 * \brief accessor (DEPRECATED : use GetFirstSingleSerieUIDFileSet )
358 * Warning : 'coherent' means here they have the same Serie UID
359 * @return The first FileList if found, otherwhise NULL
362 FileList *SerieHelper::GetFirstCoherentFileList()
364 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
365 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
366 return ItFileSetHt->second;
371 * \brief accessor (DEPRECATED : use GetNextSingleSerieUIDFileSet )
372 * Warning : 'coherent' means here they have the same Serie UID
373 * \note : meaningfull only if GetFirstCoherentFileList() already called
374 * @return The next FileList if found, otherwhise NULL
377 FileList *SerieHelper::GetNextCoherentFileList()
379 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
382 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
383 return ItFileSetHt->second;
389 * \brief accessor (DEPRECATED : use GetSingleSerieUIDFileSet )
390 * Warning : 'coherent' means here they have the same Serie UID
391 * @param SerieUID SerieUID
392 * \return pointer to the FileList if found, otherwhise NULL
395 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
397 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
399 return SingleSerieUIDFileSetHT[SerieUID];
406 * \brief Get the first Fileset while visiting the SingleSerieUIDFileSetmap
407 * @return The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
409 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
411 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
412 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
413 return ItFileSetHt->second;
418 * \brief Get the next Fileset while visiting the SingleSerieUIDFileSetmap
419 * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called
420 * @return The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
422 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
424 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
427 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
428 return ItFileSetHt->second;
433 * \brief Get the SingleSerieUIDFileSet according to its Serie UID
434 * @param SerieUID SerieUID to retrieve
435 * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
437 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
439 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
441 return SingleSerieUIDFileSetHT[SerieUID];
445 * \brief Splits a Single SerieUID Fileset according to the Orientations
446 * @param fileSet File Set to be splitted
447 * \return std::map of 'Xcoherent' File sets
450 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
452 XCoherentFileSetmap CoherentFileSet;
454 int nb = fileSet->size();
456 gdcmWarningMacro("Empty FileList passed to SplitOnOrientation");
457 return CoherentFileSet;
461 std::string strOrient;
462 std::ostringstream ossOrient;
464 FileList::const_iterator it = fileSet->begin();
466 it != fileSet->end();
469 // Information is in :
470 // 0020 0037 : Image Orientation (Patient) or
471 // 0020 0035 : Image Orientation (RET)
473 // Let's build again the 'cosines' string, to be sure of its format
474 (*it)->GetImageOrientationPatient(iop);
477 for (int i = 1; i < 6; i++)
482 strOrient = ossOrient.str();
484 if ( CoherentFileSet.count(strOrient) == 0 )
486 gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
487 // create a File set in 'orientation' position
488 CoherentFileSet[strOrient] = new FileList;
489 gdcmDebugMacro(" CoherentFileSet[strOrient]" << strOrient << "created");
491 // Current Orientation and DICOM header match; add the file:
492 CoherentFileSet[strOrient]->push_back( (*it) );
493 gdcmDebugMacro(" CoherentFileSet[strOrient]" << "pushed back")
495 return CoherentFileSet;
499 * \brief Splits a 'Single SerieUID' Fileset according to the Positions
500 * @param fileSet File Set to be splitted
501 * \return std::map of 'Xcoherent' File sets
504 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
506 XCoherentFileSetmap CoherentFileSet;
508 int nb = fileSet->size();
510 gdcmWarningMacro("Empty FileList passed to SplitOnPosition");
511 return CoherentFileSet;
514 std::string strImPos; // read on disc
515 std::ostringstream ossPosition;
516 std::string strPosition; // re computed
517 FileList::const_iterator it = fileSet->begin();
519 it != fileSet->end();
522 // Information is in :
523 // 0020,0032 : Image Position Patient
524 // 0020,0030 : Image Position (RET)
526 strImPos = (*it)->GetEntryString(0x0020,0x0032);
527 if ( strImPos == GDCM_UNFOUND)
529 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
530 strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
531 if ( strImPos == GDCM_UNFOUND )
533 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
534 // User wants to split on the 'Position'
535 // No 'Position' info found.
536 // We return an empty Htable !
537 return CoherentFileSet;
541 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ",
542 &pos[0], &pos[1], &pos[2]) != 3 )
544 gdcmWarningMacro( "Wrong number for Position : ["
545 << strImPos << "]" );
546 return CoherentFileSet;
549 // Let's build again the 'position' string, to be sure of it's format
551 ossPosition << pos[0];
552 for (int i = 1; i < 3; i++)
555 ossPosition << pos[i];
557 strPosition = ossPosition.str();
560 if ( CoherentFileSet.count(strPosition) == 0 )
562 gdcmDebugMacro(" New Position :[" << strPosition << "]");
563 // create a File set in 'position' position
564 CoherentFileSet[strPosition] = new FileList;
566 // Current Position and DICOM header match; add the file:
567 CoherentFileSet[strPosition]->push_back( (*it) );
569 return CoherentFileSet;
573 * \brief Splits a 'Single SerieUID' File set Coherent according to the
574 * value of a given Tag
575 * @param fileSet File Set to be splitted
576 * @param group group number of the target Element
577 * @param element element number of the target Element
578 * \return std::map of 'Xcoherent' File sets
581 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet,
582 uint16_t group, uint16_t element)
584 XCoherentFileSetmap CoherentFileSet;
586 int nb = fileSet->size();
588 gdcmWarningMacro("Empty FileList passed to SplitOnPosition");
589 return CoherentFileSet;
592 std::string strTagValue; // read on disc
594 FileList::const_iterator it = fileSet->begin();
597 it != fileSet->end();
600 // Information is in :
601 // 0020,0032 : Image Position Patient
602 // 0020,0030 : Image Position (RET)
604 strTagValue = (*it)->GetEntryString(group,element);
606 if ( CoherentFileSet.count(strTagValue) == 0 )
608 gdcmDebugMacro(" :[" << strTagValue << "]");
609 // create a File set in 'position' position
610 CoherentFileSet[strTagValue] = new FileList;
612 // Current Tag value and DICOM header match; add the file:
613 CoherentFileSet[strTagValue]->push_back( (*it) );
615 return CoherentFileSet;
618 //-----------------------------------------------------------------------------
621 //-----------------------------------------------------------------------------
624 * \brief sorts the images, according to their Patient Position.
625 * As a side effect, it computes the ZSpacing, according to Jolinda Smith's
626 * algorithm. (get it with double GetZSpacing() !)
627 * We may order, considering :
628 * -# Image Position Patient
631 * -# More to come :-)
632 * \note : FileList = std::vector<File* >
633 * @param fileList Coherent File list (same Serie UID) to sort
634 * @return false only if the header is bugged !
636 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
637 //based on Jolinda Smith's algorithm
639 //Tags always use the same coordinate system, where "x" is left
640 //to right, "y" is posterior to anterior, and "z" is foot to head (RAH).
642 //iop is calculated based on the file file
647 double min = 0, max = 0;
649 ZSpacing = -1.0; // will be updated if process doesn't fail
651 std::multimap<double,File *> distmultimap;
652 // Use a multimap to sort the distances from 0,0,0
653 for ( FileList::const_iterator
654 it = fileList->begin();
655 it != fileList->end(); ++it )
657 gdcmDebugMacro("deal with " << (*it)->GetFileName() );
660 (*it)->GetImageOrientationPatient( cosines );
662 // The "Image Orientation Patient" tag gives the direction cosines
663 // for the rows and columns for the three axes defined above.
664 // Typical axial slices will have a value 1/0/0/0/1/0:
665 // rows increase from left to right,
666 // columns increase from posterior to anterior. This is your everyday
667 // "looking up from the bottom of the head with the eyeballs up" image.
669 // The "Image Position Patient" tag gives the coordinates of the first
670 // voxel in the image in the "RAH" coordinate system, relative to some
673 // First, calculate the slice normal from IOP :
675 // You only have to do this once for all slices in the volume. Next,
676 // for each slice, calculate the distance along the slice normal
677 // using the IPP ("Image Position Patient") tag.
678 // ("dist" is initialized to zero before reading the first slice) :
679 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
680 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
681 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
683 // For each slice (here : the first), calculate the distance along
684 // the slice normal using the IPP tag
686 ipp[0] = (*it)->GetXOrigin();
687 ipp[1] = (*it)->GetYOrigin();
688 ipp[2] = (*it)->GetZOrigin();
691 for ( int i = 0; i < 3; ++i )
693 dist += normal[i]*ipp[i];
696 gdcmDebugMacro("dist : " << dist);
697 distmultimap.insert(std::pair<const double,File *>(dist, *it));
704 // Next, for each slice, calculate the distance along the slice normal
706 ipp[0] = (*it)->GetXOrigin();
707 ipp[1] = (*it)->GetYOrigin();
708 ipp[2] = (*it)->GetZOrigin();
711 for ( int i = 0; i < 3; ++i )
713 dist += normal[i]*ipp[i];
716 distmultimap.insert(std::pair<const double,File *>(dist, *it));
717 gdcmDebugMacro("dist : " << dist);
718 min = (min < dist) ? min : dist;
719 max = (max > dist) ? max : dist;
723 // Find out if min/max are coherent
726 gdcmWarningMacro("Looks like all images have the exact same image position. "
727 << "No PositionPatientOrdering sort performed. "
728 << "No 'ZSpacing' calculated! ");
732 // Check to see if image shares a common position
734 for (std::multimap<double, File *>::iterator it2 = distmultimap.begin();
735 it2 != distmultimap.end();
738 if (distmultimap.count((*it2).first) != 1)
740 gdcmWarningMacro("File: ["
741 << ((*it2).second->GetFileName())
742 << "] : more than ONE file at distance: '"
744 << " (position is not unique!) "
745 << "No PositionPatientOrdering sort performed. "
746 << "No 'ZSpacing' calculated! ");
753 if (! DropDuplicatePositions)
757 // Now, we can calculate Z Spacing as the difference
758 // between the "dist" values for the first two slices.
760 // The following (un)-commented out code is let here
761 // to be re-used by whomsoever is interested...
763 std::multimap<double, File *>::iterator it5 = distmultimap.begin();
764 double d1 = (*it5).first;
766 double d2 = (*it5).first;
769 ZSpacing = - ZSpacing;
771 fileList->clear(); // doesn't delete list elements, only nodes
773 // Acording to user requierement, we sort direct order or reverse order.
776 for (std::multimap<double, File *>::iterator it3 = distmultimap.begin();
777 it3 != distmultimap.end();
780 fileList->push_back( (*it3).second );
781 if (DropDuplicatePositions)
783 /// \todo ImagePositionPatientOrdering wrong duplicates are found ???
785 it3 = distmultimap.upper_bound((*it3).first); // skip all duplicates
786 if (it3 == distmultimap.end() ) // if last image, stop iterate
791 else // user asked for reverse order
793 std::multimap<double, File *>::const_iterator it4;
794 it4 = distmultimap.end();
798 fileList->push_back( (*it4).second );
799 if (DropDuplicatePositions) // skip all duplicates
801 it4 = distmultimap.upper_bound((*it4).first);
802 if (it4 == distmultimap.begin() ) // if first image, stop iterate
805 } while (it4 != distmultimap.begin() );
808 distmultimap.clear();
813 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
815 return file1->GetImageNumber() < file2->GetImageNumber();
818 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
820 return file1->GetImageNumber() > file2->GetImageNumber();
824 * \brief sorts the images, according to their Image Number
825 * \note Works only on bona fide files (i.e image number is a character string
826 * corresponding to an integer)
827 * within a bona fide serie (i.e image numbers are consecutive)
828 * @param fileList File set (same Serie UID) to sort
829 * @return false if non bona fide stuff encountered
831 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
834 int n = fileList->size();
836 FileList::const_iterator it = fileList->begin();
837 min = max = (*it)->GetImageNumber();
839 for (; it != fileList->end(); ++it, ++n)
841 pos = (*it)->GetImageNumber();
842 min = (min < pos) ? min : pos;
843 max = (max > pos) ? max : pos;
846 // Find out if image numbers are coherent (consecutive)
847 if ( min == max || max == 0 || max >= (n+min) )
849 gdcmWarningMacro( " 'Image numbers' not coherent. "
850 << " No ImageNumberOrdering sort performed.");
854 Sort(fileList,SerieHelper::ImageNumberLessThan);
856 Sort(fileList,SerieHelper::ImageNumberGreaterThan);
861 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
863 return file1->GetFileName() < file2->GetFileName();
866 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
868 return file1->GetFileName() > file2->GetFileName();
871 * \brief sorts the images, according to their File Name
872 * @param fileList Coherent File list (same Serie UID) to sort
873 * @return false only if the header is bugged !
875 bool SerieHelper::FileNameOrdering(FileList *fileList)
878 Sort(fileList,SerieHelper::FileNameLessThan);
880 Sort(fileList,SerieHelper::FileNameGreaterThan);
886 * \brief sorts the images, according to user supplied function
887 * @param fileList Coherent File list (same Serie UID) to sort
888 * @return false only if the header is bugged !
890 bool SerieHelper::UserOrdering(FileList *fileList)
892 Sort(fileList,SerieHelper::UserLessThanFunction);
895 std::reverse(fileList->begin(), fileList->end());
900 //-----------------------------------------------------------------------------
903 * \brief Canonical printer.
905 void SerieHelper::Print(std::ostream &os, std::string const &indent)
907 // For all the Coherent File lists of the GDCM_NAME_SPACE::Serie
908 SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
909 if ( itl == SingleSerieUIDFileSetHT.end() )
911 gdcmWarningMacro( "No SingleSerieUID File set found" );
914 while (itl != SingleSerieUIDFileSetHT.end())
916 os << "Serie UID :[" << itl->first << "]" << std::endl;
918 // For all the files of a SingleSerieUID File set
919 for (FileList::iterator it = (itl->second)->begin();
920 it != (itl->second)->end();
923 os << indent << " --- " << (*it)->GetFileName() << std::endl;
929 void SerieHelper::CreateDefaultUniqueSeriesIdentifier()
931 // If the user requests, additional information can be appended
932 // to the SeriesUID to further differentiate volumes in the DICOM
933 // objects being processed.
935 // 0020 0011 Series Number
936 // A scout scan prior to a CT volume scan can share the same
937 // SeriesUID, but they will sometimes have a different Series Number
938 AddRestriction( TagKey(0x0020, 0x0011) );
940 // 0018 0024 Sequence Name
941 // For T1-map and phase-contrast MRA, the different flip angles and
942 // directions are only distinguished by the Sequence Name
943 AddRestriction( TagKey(0x0018, 0x0024) );
945 // 0018 0050 Slice Thickness
946 // On some CT systems, scout scans and subsequence volume scans will
947 // have the same SeriesUID and Series Number - YET the slice
948 // thickness will differ from the scout slice and the volume slices.
949 AddRestriction( TagKey(0x0018, 0x0050));
952 // If the 2D images in a sequence don't have the same number of rows,
953 // then it is difficult to reconstruct them into a 3D volume.
954 AddRestriction( TagKey(0x0028, 0x0010));
957 // If the 2D images in a sequence don't have the same number of columns,
958 // then it is difficult to reconstruct them into a 3D volume.
959 AddRestriction( TagKey(0x0028, 0x0011));
963 * \brief Heuristics to *try* to build a Serie Identifier that would ensure
964 * all the images are coherent.
966 * By default, uses the SeriesUID. If UseSeriesDetails(true) has been called,
967 * then additional identifying information is used.
968 * We allow user to add his own critierions, using AddSeriesDetail
969 * (he knows more than we do about his images!)
970 * ex : in tagging series, the only pertinent tag is
971 * 0018|1312 [In-plane Phase Encoding Direction] value : ROW/COLUMN
972 * @param inFile GDCM_NAME_SPACE::File we want to build a Serie Identifier for.
973 * @return the SeriesIdentifier
975 std::string SerieHelper::CreateUniqueSeriesIdentifier( File *inFile )
977 if( inFile->IsReadable() )
979 // 0020 000e UI REL Series Instance UID
980 std::string uid = inFile->GetEntryString (0x0020, 0x000e);
981 std::string id = uid.c_str();
982 if(m_UseSeriesDetails)
984 for(SerieExRestrictions::iterator it2 = ExRefine.begin();
985 it2 != ExRefine.end();
988 const ExRule &r = *it2;
989 std::string s = inFile->GetEntryString( r.group, r.elem );
990 if( s == GDCM_UNFOUND )
994 if( id == uid && !s.empty() )
996 id += "."; // add separator
1001 // Eliminate non-alnum characters, including whitespace...
1002 // that may have been introduced by concats.
1003 unsigned int s_size = id.size();
1004 for(unsigned int i=0; i<s_size; i++)
1007 && !( id[i] == '.' || id[i] == '%' || id[i] == '_'
1008 || (id[i] >= '+' && id[i] <= '-')
1009 || (id[i] >= 'a' && id[i] <= 'z')
1010 || (id[i] >= '0' && id[i] <= '9')
1011 || (id[i] >= 'A' && id[i] <= 'Z')))
1013 id.replace(i, 1, "_"); // ImagePositionPatient related stuff will be more human readable
1016 // deal with Dicom strings trailing '\0'
1017 if(id[s_size-1] == '_')
1018 id.erase(s_size-1, 1);
1021 else // Could not open inFile
1023 gdcmWarningMacro("Could not parse series info.");
1024 std::string id = GDCM_UNFOUND;
1030 * \brief Allow user to build is own File Identifier (to be able to sort
1031 * temporal series just as he wants)
1032 * Criterions will be set with AddSeriesDetail.
1033 * (Maybe the method should be moved elsewhere
1034 * -File class? FileHelper class?-
1035 * @return FileIdentifier (Tokenizable on '%%%'. Hope it's enough !)
1037 std::string SerieHelper::CreateUserDefinedFileIdentifier( File *inFile )
1039 // Deal with all user supplied tags.
1040 // (user knows more than we do about his images!)
1045 char charConverted[17];
1047 for(SeriesExDetails::iterator it2 = ExDetails.begin();
1048 it2 != ExDetails.end();
1051 const ExDetail &r = *it2;
1052 s = inFile->GetEntryString( r.group, r.elem );
1054 // User is allowed to ask for 'convertion', to allow further ordering
1055 // e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK
1058 if ( s != GDCM_UNFOUND) // Don't convert unfound fields !
1060 converted = atof(s.c_str());
1061 // probabely something much more complicated is possible,
1062 // using C++ features
1063 /// \todo check the behaviour when there are >0 and <0 numbers
1064 sprintf(charConverted, "%016.6f",converted);
1068 // Eliminate non-alphanum characters, including whitespace.
1069 unsigned int s_size = s.size();
1070 for(unsigned int i=0; i<s_size; i++)
1073 && !( s[i] == '.' || s[i] == '%' || s[i] == '_'
1074 || (s[i] >= '+' && s[i] <= '-')
1075 || (s[i] >= 'a' && s[i] <= 'z')
1076 || (s[i] >= '0' && s[i] <= '9')
1077 || (s[i] >= 'A' && s[i] <= 'Z')))
1079 s.replace(i, 1, "_"); // ImagePositionPatient related stuff will be more human readable
1082 // deal with Dicom strings trailing '\0'
1083 if(s[s_size-1] == '_')
1084 s.erase(s_size-1, 1);
1087 id += "%%%"; // make the FileIdentifier Tokenizable
1089 id += inFile->GetFileName();
1094 //-----------------------------------------------------------------------------
1097 * \brief Sort FileList.
1099 void SerieHelper::Sort(FileList *fileList, bool (*pt2Func)( File *file1, File *file2) )
1101 std::sort(fileList->begin(), fileList->end(), pt2Func );
1105 #ifndef GDCM_LEGACY_REMOVE
1106 bool SerieHelper::AddGdcmFile(File* header)
1108 return AddFile(header);
1113 //-----------------------------------------------------------------------------
1114 } // end namespace gdcm