1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2008/02/13 18:53:33 $
7 Version: $Revision: 1.65 $
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;
46 DropDuplicatePositions = false;
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)
266 // std::cout << "--------------------------------filename [" << *it << "]"
268 gdcmDebugMacro("filename [" << *it << "]" );
274 * \brief Sets the DicomDirSerie
275 * @param se DicomDirSerie to deal with
277 void SerieHelper::SetDicomDirSerie(DicomDirSerie *se)
281 DirListType filenames_list = dirList.GetFilenames();
282 for( DirListType::const_iterator it = filenames_list.begin();
283 it != filenames_list.end(); ++it)
290 * \brief Sorts the given Fileset
291 * \warning This could be implemented in a 'Strategy Pattern' approach
292 * But as I don't know how to do it, I leave it this way
293 * BTW, this is also a Strategy, I don't know this is
294 * the best approach :)
296 void SerieHelper::OrderFileList(FileList *fileSet)
298 // Only computed during ImagePositionPatientOrdering
299 // (need to sort the FileList using IPP and IOP !)
302 if ( SerieHelper::UserLessThanFunction )
304 gdcmDebugMacro("Use UserLessThanFunction");
305 UserOrdering( fileSet );
308 else if ( ImagePositionPatientOrdering( fileSet ) )
310 gdcmDebugMacro("ImagePositionPatientOrdering succeeded");
313 else if ( ImageNumberOrdering(fileSet ) )
315 gdcmDebugMacro("ImageNumberOrdering succeeded");
320 gdcmDebugMacro("Use FileNameOrdering");
321 FileNameOrdering(fileSet );
326 * \brief Elementary coherence checking of the files with the same Serie UID
327 * Only sizes and pixel type are checked right now ...
329 bool SerieHelper::IsCoherent(FileList *fileSet)
331 if(fileSet->size() == 1)
334 FileList::const_iterator it = fileSet->begin();
336 int nX = (*it)->GetXSize();
337 int nY = (*it)->GetYSize();
338 int pixelSize = (*it)->GetPixelSize();
339 bool signedPixelData = (*it)->IsSignedPixelData();
342 it != fileSet->end();
345 if ( (*it)->GetXSize() != nX )
347 if ( (*it)->GetYSize() != nY )
349 if ( (*it)->GetPixelSize() != pixelSize )
351 if ( (*it)->IsSignedPixelData() != signedPixelData )
353 // probabely more is to be checked (?)
358 //#ifndef GDCM_LEGACY_REMOVE
360 * \brief accessor (DEPRECATED : use GetFirstSingleSerieUIDFileSet )
361 * Warning : 'coherent' means here they have the same Serie UID
362 * @return The first FileList if found, otherwhise NULL
365 FileList *SerieHelper::GetFirstCoherentFileList()
367 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
368 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
369 return ItFileSetHt->second;
374 * \brief accessor (DEPRECATED : use GetNextSingleSerieUIDFileSet )
375 * Warning : 'coherent' means here they have the same Serie UID
376 * \note : meaningfull only if GetFirstCoherentFileList() already called
377 * @return The next FileList if found, otherwhise NULL
380 FileList *SerieHelper::GetNextCoherentFileList()
382 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
385 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
386 return ItFileSetHt->second;
392 * \brief accessor (DEPRECATED : use GetSingleSerieUIDFileSet )
393 * Warning : 'coherent' means here they have the same Serie UID
394 * @param SerieUID SerieUID
395 * \return pointer to the FileList if found, otherwhise NULL
398 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
400 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
402 return SingleSerieUIDFileSetHT[SerieUID];
409 * \brief Get the first Fileset while visiting the SingleSerieUIDFileSetmap
410 * @return The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
412 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
414 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
415 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
416 return ItFileSetHt->second;
421 * \brief Get the next Fileset while visiting the SingleSerieUIDFileSetmap
422 * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called
423 * @return The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
425 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
427 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
430 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
431 return ItFileSetHt->second;
436 * \brief Get the SingleSerieUIDFileSet according to its Serie UID
437 * @param SerieUID SerieUID to retrieve
438 * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
440 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
442 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
444 return SingleSerieUIDFileSetHT[SerieUID];
448 * \brief Splits a Single SerieUID Fileset according to the Orientations
449 * @param fileSet File Set to be splitted
450 * \return std::map of 'Xcoherent' File sets
453 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
455 XCoherentFileSetmap CoherentFileSet;
457 int nb = fileSet->size();
459 gdcmWarningMacro("Empty FileList passed to SplitOnOrientation");
460 return CoherentFileSet;
464 std::string strOrient;
465 std::ostringstream ossOrient;
467 FileList::const_iterator it = fileSet->begin();
469 it != fileSet->end();
472 // Information is in :
473 // 0020 0037 : Image Orientation (Patient) or
474 // 0020 0035 : Image Orientation (RET)
476 // Let's build again the 'cosines' string, to be sure of its format
477 (*it)->GetImageOrientationPatient(iop);
480 for (int i = 1; i < 6; i++)
485 strOrient = ossOrient.str();
487 if ( CoherentFileSet.count(strOrient) == 0 )
489 gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
490 // create a File set in 'orientation' position
491 CoherentFileSet[strOrient] = new FileList;
492 gdcmDebugMacro(" CoherentFileSet[strOrient]" << strOrient << "created");
494 // Current Orientation and DICOM header match; add the file:
495 CoherentFileSet[strOrient]->push_back( (*it) );
496 gdcmDebugMacro(" CoherentFileSet[strOrient]" << "pushed back")
498 return CoherentFileSet;
502 * \brief Splits a 'Single SerieUID' Fileset according to the Positions
503 * @param fileSet File Set to be splitted
504 * \return std::map of 'Xcoherent' File sets
507 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
509 XCoherentFileSetmap CoherentFileSet;
511 int nb = fileSet->size();
513 gdcmWarningMacro("Empty FileList passed to SplitOnPosition");
514 return CoherentFileSet;
517 std::string strImPos; // read on disc
518 std::ostringstream ossPosition;
519 std::string strPosition; // re computed
520 FileList::const_iterator it = fileSet->begin();
522 it != fileSet->end();
525 // Information is in :
526 // 0020,0032 : Image Position Patient
527 // 0020,0030 : Image Position (RET)
529 strImPos = (*it)->GetEntryString(0x0020,0x0032);
530 if ( strImPos == GDCM_UNFOUND)
532 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
533 strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
534 if ( strImPos == GDCM_UNFOUND )
536 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
537 // User wants to split on the 'Position'
538 // No 'Position' info found.
539 // We return an empty Htable !
540 return CoherentFileSet;
544 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ",
545 &pos[0], &pos[1], &pos[2]) != 3 )
547 gdcmWarningMacro( "Wrong number for Position : ["
548 << strImPos << "]" );
549 return CoherentFileSet;
552 // Let's build again the 'position' string, to be sure of it's format
554 ossPosition << pos[0];
555 for (int i = 1; i < 3; i++)
558 ossPosition << pos[i];
560 strPosition = ossPosition.str();
563 if ( CoherentFileSet.count(strPosition) == 0 )
565 gdcmDebugMacro(" New Position :[" << strPosition << "]");
566 // create a File set in 'position' position
567 CoherentFileSet[strPosition] = new FileList;
569 // Current Position and DICOM header match; add the file:
570 CoherentFileSet[strPosition]->push_back( (*it) );
572 return CoherentFileSet;
576 * \brief Splits a 'Single SerieUID' File set Coherent according to the
577 * value of a given Tag
578 * @param fileSet File Set to be splitted
579 * @param group group number of the target Element
580 * @param element element number of the target Element
581 * \return std::map of 'Xcoherent' File sets
584 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet,
585 uint16_t group, uint16_t element)
587 XCoherentFileSetmap CoherentFileSet;
589 int nb = fileSet->size();
591 gdcmWarningMacro("Empty FileList passed to SplitOnPosition");
592 return CoherentFileSet;
595 std::string strTagValue; // read on disc
597 FileList::const_iterator it = fileSet->begin();
600 it != fileSet->end();
603 // Information is in :
604 // 0020,0032 : Image Position Patient
605 // 0020,0030 : Image Position (RET)
607 strTagValue = (*it)->GetEntryString(group,element);
609 if ( CoherentFileSet.count(strTagValue) == 0 )
611 gdcmDebugMacro(" :[" << strTagValue << "]");
612 // create a File set in 'position' position
613 CoherentFileSet[strTagValue] = new FileList;
615 // Current Tag value and DICOM header match; add the file:
616 CoherentFileSet[strTagValue]->push_back( (*it) );
618 return CoherentFileSet;
621 //-----------------------------------------------------------------------------
624 //-----------------------------------------------------------------------------
627 * \brief sorts the images, according to their Patient Position.
628 * As a side effect, it computes the ZSpacing, according to Jolinda Smith's
629 * algorithm. (get it with double GetZSpacing() !)
630 * We may order, considering :
631 * -# Image Position Patient
634 * -# More to come :-)
635 * \note : FileList = std::vector<File* >
636 * @param fileList Coherent File list (same Serie UID) to sort
637 * @return false only if the header is bugged !
639 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
640 //based on Jolinda Smith's algorithm
642 //Tags always use the same coordinate system, where "x" is left
643 //to right, "y" is posterior to anterior, and "z" is foot to head (RAH).
645 //iop is calculated based on the file file
650 double min = 0, max = 0;
652 ZSpacing = -1.0; // will be updated if process doesn't fail
654 gdcmDebugMacro("============================================DropDuplicatePositions : " << DropDuplicatePositions );
656 std::multimap<double,File *> distmultimap;
657 // Use a multimap to sort the distances from 0,0,0
658 for ( FileList::const_iterator
659 it = fileList->begin();
660 it != fileList->end(); ++it )
662 gdcmDebugMacro("deal with " << (*it)->GetFileName() );
665 (*it)->GetImageOrientationPatient( cosines );
667 // The "Image Orientation Patient" tag gives the direction cosines
668 // for the rows and columns for the three axes defined above.
669 // Typical axial slices will have a value 1/0/0/0/1/0:
670 // rows increase from left to right,
671 // columns increase from posterior to anterior. This is your everyday
672 // "looking up from the bottom of the head with the eyeballs up" image.
674 // The "Image Position Patient" tag gives the coordinates of the first
675 // voxel in the image in the "RAH" coordinate system, relative to some
678 // First, calculate the slice normal from IOP :
680 // You only have to do this once for all slices in the volume. Next,
681 // for each slice, calculate the distance along the slice normal
682 // using the IPP ("Image Position Patient") tag.
683 // ("dist" is initialized to zero before reading the first slice) :
684 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
685 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
686 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
688 // For each slice (here : the first), calculate the distance along
689 // the slice normal using the IPP tag
691 ipp[0] = (*it)->GetXOrigin();
692 ipp[1] = (*it)->GetYOrigin();
693 ipp[2] = (*it)->GetZOrigin();
696 for ( int i = 0; i < 3; ++i )
698 dist += normal[i]*ipp[i];
701 gdcmDebugMacro("dist : " << dist);
702 distmultimap.insert(std::pair<const double,File *>(dist, *it));
709 // Next, for each slice, calculate the distance along the slice normal
711 ipp[0] = (*it)->GetXOrigin();
712 ipp[1] = (*it)->GetYOrigin();
713 ipp[2] = (*it)->GetZOrigin();
716 for ( int i = 0; i < 3; ++i )
718 dist += normal[i]*ipp[i];
721 distmultimap.insert(std::pair<const double,File *>(dist, *it));
722 gdcmDebugMacro("dist : " << dist);
723 min = (min < dist) ? min : dist;
724 max = (max > dist) ? max : dist;
728 gdcmDebugMacro("After parsing vector, nb of elements : " << fileList->size() );
730 // Find out if min/max are coherent
733 gdcmWarningMacro("Looks like all images have the exact same image position. "
734 << "No PositionPatientOrdering sort performed. "
735 << "No 'ZSpacing' calculated! ");
739 // Check to see if image shares a common position
741 for (std::multimap<double, File *>::iterator it2 = distmultimap.begin();
742 it2 != distmultimap.end();
746 gdcmDebugMacro("Check if image shares a common position : " << (*it2).second->GetFileName() );
748 if (distmultimap.count((*it2).first) != 1)
750 gdcmWarningMacro("File: ["
751 << ((*it2).second->GetFileName())
752 << "] : more than ONE file at distance: '"
754 << " (position is not unique!) "
755 << "No PositionPatientOrdering sort performed. "
756 << "No 'ZSpacing' calculated! ");
763 if (! DropDuplicatePositions)
767 // Now, we can calculate Z Spacing as the difference
768 // between the "dist" values for the first two slices.
770 // The following (un)-commented out code is let here
771 // to be re-used by whomsoever is interested...
773 std::multimap<double, File *>::iterator it5 = distmultimap.begin();
774 double d1 = (*it5).first;
776 double d2 = (*it5).first;
779 ZSpacing = - ZSpacing;
781 fileList->clear(); // doesn't delete list elements, only nodes
783 // Acording to user requierement, we sort direct order or reverse order.
786 for (std::multimap<double, File *>::iterator it3 = distmultimap.begin();
787 it3 != distmultimap.end();
790 fileList->push_back( (*it3).second );
791 if (DropDuplicatePositions)
793 /// \todo ImagePositionPatientOrdering wrong duplicates are found ???
795 it3 = distmultimap.upper_bound((*it3).first); // skip all duplicates
796 if (it3 == distmultimap.end() ) // if last image, stop iterate
801 else // user asked for reverse order
803 std::multimap<double, File *>::const_iterator it4;
804 it4 = distmultimap.end();
808 fileList->push_back( (*it4).second );
809 if (DropDuplicatePositions) // skip all duplicates
811 it4 = distmultimap.upper_bound((*it4).first);
812 if (it4 == distmultimap.begin() ) // if first image, stop iterate
815 } while (it4 != distmultimap.begin() );
818 distmultimap.clear();
823 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
825 return file1->GetImageNumber() < file2->GetImageNumber();
828 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
830 return file1->GetImageNumber() > file2->GetImageNumber();
834 * \brief sorts the images, according to their Image Number
835 * \note Works only on bona fide files (i.e image number is a character string
836 * corresponding to an integer)
837 * within a bona fide serie (i.e image numbers are consecutive)
838 * @param fileList File set (same Serie UID) to sort
839 * @return false if non bona fide stuff encountered
841 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
844 int n = fileList->size();
846 FileList::const_iterator it = fileList->begin();
847 min = max = (*it)->GetImageNumber();
849 for (; it != fileList->end(); ++it, ++n)
851 pos = (*it)->GetImageNumber();
852 min = (min < pos) ? min : pos;
853 max = (max > pos) ? max : pos;
856 // Find out if image numbers are coherent (consecutive)
857 if ( min == max || max == 0 || max >= (n+min) )
859 gdcmWarningMacro( " 'Image numbers' not coherent. "
860 << " No ImageNumberOrdering sort performed.");
864 Sort(fileList,SerieHelper::ImageNumberLessThan);
866 Sort(fileList,SerieHelper::ImageNumberGreaterThan);
871 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
873 return file1->GetFileName() < file2->GetFileName();
876 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
878 return file1->GetFileName() > file2->GetFileName();
881 * \brief sorts the images, according to their File Name
882 * @param fileList Coherent File list (same Serie UID) to sort
883 * @return false only if the header is bugged !
885 bool SerieHelper::FileNameOrdering(FileList *fileList)
888 Sort(fileList,SerieHelper::FileNameLessThan);
890 Sort(fileList,SerieHelper::FileNameGreaterThan);
896 * \brief sorts the images, according to user supplied function
897 * @param fileList Coherent File list (same Serie UID) to sort
898 * @return false only if the header is bugged !
900 bool SerieHelper::UserOrdering(FileList *fileList)
902 Sort(fileList,SerieHelper::UserLessThanFunction);
905 std::reverse(fileList->begin(), fileList->end());
910 //-----------------------------------------------------------------------------
913 * \brief Canonical printer.
915 void SerieHelper::Print(std::ostream &os, std::string const &indent)
917 // For all the Coherent File lists of the GDCM_NAME_SPACE::Serie
918 SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
919 if ( itl == SingleSerieUIDFileSetHT.end() )
921 gdcmWarningMacro( "No SingleSerieUID File set found" );
924 while (itl != SingleSerieUIDFileSetHT.end())
926 os << "Serie UID :[" << itl->first << "]" << std::endl;
928 // For all the files of a SingleSerieUID File set
929 for (FileList::iterator it = (itl->second)->begin();
930 it != (itl->second)->end();
933 os << indent << " --- " << (*it)->GetFileName() << std::endl;
939 void SerieHelper::CreateDefaultUniqueSeriesIdentifier()
941 // If the user requests, additional information can be appended
942 // to the SeriesUID to further differentiate volumes in the DICOM
943 // objects being processed.
945 // 0020 0011 Series Number
946 // A scout scan prior to a CT volume scan can share the same
947 // SeriesUID, but they will sometimes have a different Series Number
948 AddRestriction( TagKey(0x0020, 0x0011) );
950 // 0018 0024 Sequence Name
951 // For T1-map and phase-contrast MRA, the different flip angles and
952 // directions are only distinguished by the Sequence Name
953 AddRestriction( TagKey(0x0018, 0x0024) );
955 // 0018 0050 Slice Thickness
956 // On some CT systems, scout scans and subsequence volume scans will
957 // have the same SeriesUID and Series Number - YET the slice
958 // thickness will differ from the scout slice and the volume slices.
959 AddRestriction( TagKey(0x0018, 0x0050));
962 // If the 2D images in a sequence don't have the same number of rows,
963 // then it is difficult to reconstruct them into a 3D volume.
964 AddRestriction( TagKey(0x0028, 0x0010));
967 // If the 2D images in a sequence don't have the same number of columns,
968 // then it is difficult to reconstruct them into a 3D volume.
969 AddRestriction( TagKey(0x0028, 0x0011));
973 * \brief Heuristics to *try* to build a Serie Identifier that would ensure
974 * all the images are coherent.
976 * By default, uses the SeriesUID. If UseSeriesDetails(true) has been called,
977 * then additional identifying information is used.
978 * We allow user to add his own critierions, using AddSeriesDetail
979 * (he knows more than we do about his images!)
980 * ex : in tagging series, the only pertinent tag is
981 * 0018|1312 [In-plane Phase Encoding Direction] value : ROW/COLUMN
982 * @param inFile GDCM_NAME_SPACE::File we want to build a Serie Identifier for.
983 * @return the SeriesIdentifier
985 std::string SerieHelper::CreateUniqueSeriesIdentifier( File *inFile )
987 if( inFile->IsReadable() )
989 // 0020 000e UI REL Series Instance UID
990 std::string uid = inFile->GetEntryString (0x0020, 0x000e);
991 std::string id = uid.c_str();
992 if(m_UseSeriesDetails)
994 for(SerieExRestrictions::iterator it2 = ExRefine.begin();
995 it2 != ExRefine.end();
998 const ExRule &r = *it2;
999 std::string s = inFile->GetEntryString( r.group, r.elem );
1000 if( s == GDCM_UNFOUND )
1004 if( id == uid && !s.empty() )
1006 id += "."; // add separator
1011 // Eliminate non-alnum characters, including whitespace...
1012 // that may have been introduced by concats.
1013 unsigned int s_size = id.size();
1014 for(unsigned int i=0; i<s_size; i++)
1017 && !( id[i] == '.' || id[i] == '%' || id[i] == '_'
1018 || (id[i] >= '+' && id[i] <= '-')
1019 || (id[i] >= 'a' && id[i] <= 'z')
1020 || (id[i] >= '0' && id[i] <= '9')
1021 || (id[i] >= 'A' && id[i] <= 'Z')))
1023 id.replace(i, 1, "_"); // ImagePositionPatient related stuff will be more human readable
1026 // deal with Dicom strings trailing '\0'
1027 if(id[s_size-1] == '_')
1028 id.erase(s_size-1, 1);
1031 else // Could not open inFile
1033 gdcmWarningMacro("Could not parse series info.");
1034 std::string id = GDCM_UNFOUND;
1040 * \brief Allow user to build is own File Identifier (to be able to sort
1041 * temporal series just as he wants)
1042 * Criterions will be set with AddSeriesDetail.
1043 * (Maybe the method should be moved elsewhere
1044 * -File class? FileHelper class?-
1045 * @return FileIdentifier (Tokenizable on '%%%'. Hope it's enough !)
1047 std::string SerieHelper::CreateUserDefinedFileIdentifier( File *inFile )
1049 // Deal with all user supplied tags.
1050 // (user knows more than we do about his images!)
1055 char charConverted[17];
1057 for(SeriesExDetails::iterator it2 = ExDetails.begin();
1058 it2 != ExDetails.end();
1061 const ExDetail &r = *it2;
1062 s = inFile->GetEntryString( r.group, r.elem );
1063 if (s == "") // avoid troubles when empty string is found
1066 // User is allowed to ask for 'convertion', to allow further ordering
1067 // e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK
1070 if ( s != GDCM_UNFOUND) // Don't convert unfound fields !
1072 converted = atof(s.c_str());
1073 // probabely something much more complicated is possible,
1074 // using C++ features
1075 /// \todo check the behaviour when there are >0 and <0 numbers
1076 sprintf(charConverted, "%016.6f",converted);
1080 // Eliminate non-alphanum characters, including whitespace.
1081 unsigned int s_size = s.size();
1082 for(unsigned int i=0; i<s_size; i++)
1085 && !( s[i] == '.' || s[i] == '%' || s[i] == '_'
1086 || (s[i] >= '+' && s[i] <= '-')
1087 || (s[i] >= 'a' && s[i] <= 'z')
1088 || (s[i] >= '0' && s[i] <= '9')
1089 || (s[i] >= 'A' && s[i] <= 'Z')))
1091 s.replace(i, 1, "_"); // ImagePositionPatient related stuff will be more human readable
1094 // deal with Dicom strings trailing '\0'
1095 if(s[s_size-1] == '_')
1096 s.erase(s_size-1, 1);
1099 id += "%%%"; // make the FileIdentifier Tokenizable
1101 id += inFile->GetFileName();
1106 //-----------------------------------------------------------------------------
1109 * \brief Sort FileList.
1111 void SerieHelper::Sort(FileList *fileList, bool (*pt2Func)( File *file1, File *file2) )
1113 std::sort(fileList->begin(), fileList->end(), pt2Func );
1117 #ifndef GDCM_LEGACY_REMOVE
1118 bool SerieHelper::AddGdcmFile(File* header)
1120 return AddFile(header);
1125 //-----------------------------------------------------------------------------
1126 } // end namespace gdcm