1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2005/10/26 06:23:37 $
7 Version: $Revision: 1.31 $
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"
30 #include <stdio.h> //for sscanf
34 //-----------------------------------------------------------------------------
36 //-----------------------------------------------------------------------------
37 // Constructor / Destructor
39 * \brief Constructor from a given SerieHelper
41 SerieHelper::SerieHelper()
44 UserLessThanFunction = 0;
49 * \brief Canonical destructor.
51 SerieHelper::~SerieHelper()
57 * \brief Preventively, clear everything at constructor time.
58 * ( use it at destructor time.)
60 void SerieHelper::ClearAll()
62 // For all the 'Single SerieUID' Filesets that may already exist
63 FileList *l = GetFirstSingleSerieUIDFileSet();
66 // For all the gdcm::File of a File set
67 for (gdcm::FileList::iterator it = l->begin();
71 (*it)->Delete(); // remove each entry
74 delete l; // remove the container
75 l = GetNextSingleSerieUIDFileSet();
79 //-----------------------------------------------------------------------------
81 //-----------------------------------------------------------------------------
85 * \brief add a gdcm::File to the Fileset corresponding to its Serie UID
86 * @param filename Name of the file to deal with
88 void SerieHelper::AddFileName(std::string const &filename)
90 // Create a DICOM file
91 File *header = File::New();
92 header->SetLoadMode(LoadMode);
93 header->SetFileName( filename );
96 if ( header->IsReadable() )
99 // First step : the user defined a set of rules for the DICOM file
100 // he is looking for.
101 // Make sure the file corresponds to his set of rules:
104 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
105 it2 != ExRestrictions.end();
108 const ExRule &r = *it2;
109 s = header->GetEntryString( r.group, r.elem );
110 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
112 // Argh ! This rule is unmatched; let's just quit
119 if ( allrules ) // all rules are respected:
121 // Allright! we have a found a DICOM that matches the user expectation.
124 // 0020 000e UI REL Series Instance UID
125 const std::string &uid = header->GetEntryString(0x0020, 0x000e);
126 // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
127 // no need here to do anything special
130 if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
132 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
133 // create a std::list in 'uid' position
134 SingleSerieUIDFileSetHT[uid] = new FileList;
136 // Current Serie UID and DICOM header seems to match; add the file:
137 SingleSerieUIDFileSetHT[uid]->push_back( header );
141 // at least one rule was unmatched we need to deallocate the file:
147 gdcmWarningMacro("Could not read file: " << filename );
153 * \brief add a gdcm::File to the first (and supposed to be unique) file set
154 * of the gdcm::SerieHelper.
155 * \warning : this method should be used by aware users only!
156 * Passing a gdcm::File* has the same effect than passing a file name!
157 * \todo : decide which one is wrong (the method, or the commentary)!
158 * the following comment doesn't match the method :-(
159 * User is supposed to know the files he want to deal with
160 * and consider them they belong to the same Serie
161 * (even if their Serie UID is different)
162 * user will probabely OrderFileList() this list (actually, ordering
163 * user choosen gdm::File is the sole interest of this method)
164 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
165 * vtkGdcmReader parsing twice the same files.
166 * *no* coherence check is performed, but those specified
167 * by SerieHelper::AddRestriction()
168 * @param header gdcm::File* of the file to deal with
170 void SerieHelper::AddGdcmFile(File *header)
173 // First step the user has defined a set of rules for the DICOM
174 // he is looking for.
175 // make sure the file correspond to his set of rules:
176 for(SerieRestrictions::iterator it = Restrictions.begin();
177 it != Restrictions.end();
181 const std::string s;// = header->GetEntryValue( r.first );
182 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
184 // Argh ! This rule is unmatch let's just quit
189 if ( allrules ) // all rules are respected:
191 // Allright ! we have a found a DICOM that match the user expectation.
194 const std::string &uid = "0";
195 // Serie UID of the gdcm::File* may be different.
196 // User is supposed to know what he wants
198 if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
200 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
201 // create a std::list in 'uid' position
202 SingleSerieUIDFileSetHT[uid] = new FileList;
204 // Current Serie UID and DICOM header seems to match; add the file:
205 SingleSerieUIDFileSetHT[uid]->push_back( header );
207 // Even if a rule was unmatch we don't deallocate the gdcm::File:
211 * \brief add a rules for restricting a DICOM file to be in the serie we are
212 * trying to find. For example you can select only the DICOM file from a
213 * directory which would have a particular EchoTime==4.0.
214 * This method is a user level, value is not required to be formatted as a DICOM
216 * @param group Group number of the target tag.
217 * @param elem Element number of the target tag.
218 * @param value value to be checked to exclude File
219 * @param op operator we want to use to check
221 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
222 std::string const &value, int op)
229 ExRestrictions.push_back( r );
232 #ifndef GDCM_LEGACY_REMOVE
233 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
238 Restrictions.push_back( r );
243 * \brief Sets the root Directory
244 * @param dir Name of the directory to deal with
245 * @param recursive whether we want explore recursively the root Directory
247 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
249 DirList dirList(dir, recursive); // OS specific
251 DirListType filenames_list = dirList.GetFilenames();
252 for( DirListType::const_iterator it = filenames_list.begin();
253 it != filenames_list.end(); ++it)
260 * \brief Sorts the given Fileset
261 * \warning This could be implemented in a 'Strategy Pattern' approach
262 * But as I don't know how to do it, I leave it this way
263 * BTW, this is also a Strategy, I don't know this is
264 * the best approach :)
266 void SerieHelper::OrderFileList(FileList *fileSet)
269 if ( SerieHelper::UserLessThanFunction )
271 UserOrdering( fileSet );
274 else if ( ImagePositionPatientOrdering( fileSet ) )
278 else if ( ImageNumberOrdering(fileSet ) )
284 FileNameOrdering(fileSet );
289 * \brief Elementary coherence checking of the files with the same Serie UID
290 * Only sizes and pixel type are checked right now ...
292 bool SerieHelper::IsCoherent(FileList *fileSet)
294 if(fileSet->size() == 1)
297 FileList::const_iterator it = fileSet->begin();
299 int nX = (*it)->GetXSize();
300 int nY = (*it)->GetYSize();
301 int pixelSize = (*it)->GetPixelSize();
305 it != fileSet->end();
308 if ( (*it)->GetXSize() != nX )
310 if ( (*it)->GetYSize() != nY )
312 if ( (*it)->GetPixelSize() != pixelSize )
314 // probabely more is to be checked (?)
319 #ifndef GDCM_LEGACY_REMOVE
321 FileList *SerieHelper::GetFirstCoherentFileList()
323 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
324 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
325 return ItFileSetHt->second;
330 FileList *SerieHelper::GetNextCoherentFileList()
332 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
335 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
336 return ItFileSetHt->second;
341 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
343 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
345 return SingleSerieUIDFileSetHT[SerieUID];
351 * \brief Get the first Fileset while visiting the SingleSerieUIDFileSetmap
352 * @return The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
354 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
356 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
357 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
358 return ItFileSetHt->second;
363 * \brief Get the next Fileset while visiting the SingleSerieUIDFileSetmap
364 * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called
365 * @return The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
367 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
369 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
372 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
373 return ItFileSetHt->second;
378 * \brief Get the SingleSerieUIDFileSet according to its Serie UID
379 * @param SerieUID SerieUID to retrieve
380 * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
382 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
384 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
386 return SingleSerieUIDFileSetHT[SerieUID];
390 * \brief Splits a Single SerieUID Fileset according to the Orientations
391 * @param fileSet File Set to be splitted
392 * \return std::map of 'Xcoherent' File sets
395 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
397 XCoherentFileSetmap CoherentFileSet;
399 int nb = fileSet->size();
401 return CoherentFileSet;
404 std::string strOrient;
405 std::ostringstream ossOrient;
406 FileList::const_iterator it = fileSet->begin();
409 it != fileSet->end();
412 // Information is in :
413 // 0020 0037 : Image Orientation (Patient) or
414 // 0020 0035 : Image Orientation (RET)
416 // Let's build again the 'cosines' string, to be sure of it's format
417 (*it)->GetImageOrientationPatient(iop);
420 for (int i = 1; i < 6; i++)
425 strOrient = ossOrient.str();
427 // FIXME : is it a 'cleaner' way to initialize an ostringstream?
429 if ( CoherentFileSet.count(strOrient) == 0 )
431 gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
432 // create a File set in 'orientation' position
433 CoherentFileSet[strOrient] = new FileList;
435 // Current Orientation and DICOM header match; add the file:
436 CoherentFileSet[strOrient]->push_back( (*it) );
438 return CoherentFileSet;
442 * \brief Splits a 'Single SerieUID' Fileset according to the Positions
443 * @param fileSet File Set to be splitted
444 * \return std::map of 'Xcoherent' File sets
447 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
449 XCoherentFileSetmap CoherentFileSet;
451 int nb = fileSet->size();
453 return CoherentFileSet;
455 std::string strImPos; // read on disc
456 std::ostringstream ossPosition;
457 std::string strPosition; // re computed
458 FileList::const_iterator it = fileSet->begin();
461 it != fileSet->end();
464 // Information is in :
465 // 0020,0032 : Image Position Patient
466 // 0020,0030 : Image Position (RET)
468 strImPos = (*it)->GetEntryString(0x0020,0x0032);
469 if ( strImPos == GDCM_UNFOUND)
471 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
472 strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
473 if ( strImPos == GDCM_UNFOUND )
475 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
476 // User wants to split on the 'Position'
477 // No 'Position' info found.
478 // We return an empty Htable !
479 return CoherentFileSet;
483 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ",
484 &pos[0], &pos[1], &pos[2]) != 3 )
486 gdcmWarningMacro( "Wrong number for Position : ["
487 << strImPos << "]" );
488 return CoherentFileSet;
491 // Let's build again the 'position' string, to be sure of it's format
493 ossPosition << pos[0];
494 for (int i = 1; i < 3; i++)
497 ossPosition << pos[i];
499 strPosition = ossPosition.str();
501 if ( CoherentFileSet.count(strPosition) == 0 )
503 gdcmDebugMacro(" New Position :[" << strPosition << "]");
504 // create a File set in 'position' position
505 CoherentFileSet[strPosition] = new FileList;
507 // Current Position and DICOM header match; add the file:
508 CoherentFileSet[strPosition]->push_back( (*it) );
510 return CoherentFileSet;
514 * \brief Splits a 'Single SerieUID' File set Coherent according to the
515 * value of a given Tag
516 * @param fileSet File Set to be splitted
517 * @param group group number of the target Element
518 * @param elem element number of the target Element
519 * \return std::map of 'Xcoherent' File sets
522 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet,
523 uint16_t group, uint16_t elem)
525 XCoherentFileSetmap CoherentFileSet;
527 int nb = fileSet->size();
529 return CoherentFileSet;
531 std::string strTagValue; // read on disc
533 FileList::const_iterator it = fileSet->begin();
536 it != fileSet->end();
539 // Information is in :
540 // 0020,0032 : Image Position Patient
541 // 0020,0030 : Image Position (RET)
543 strTagValue = (*it)->GetEntryString(group,elem);
545 if ( CoherentFileSet.count(strTagValue) == 0 )
547 gdcmDebugMacro(" New Tag Value :[" << strTagValue << "]");
548 // create a File set in 'position' position
549 CoherentFileSet[strTagValue] = new FileList;
551 // Current Tag value and DICOM header match; add the file:
552 CoherentFileSet[strTagValue]->push_back( (*it) );
554 return CoherentFileSet;
557 //-----------------------------------------------------------------------------
560 //-----------------------------------------------------------------------------
563 * \brief sorts the images, according to their Patient Position
564 * We may order, considering :
565 * -# Image Position Patient
568 * -# More to come :-)
569 * \note : FileList = std::vector<File* >
570 * @param fileList Coherent File list (same Serie UID) to sort
571 * @return false only if the header is bugged !
573 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
574 //based on Jolinda Smith's algorithm
576 //iop is calculated based on the file file
581 float min = 0, max = 0;
584 std::vector<float> distlist;
586 //!\todo rewrite this for loop.
587 for ( FileList::const_iterator
588 it = fileList->begin();
589 it != fileList->end(); ++it )
593 (*it)->GetImageOrientationPatient( cosines );
595 // You only have to do this once for all slices in the volume. Next,
596 // for each slice, calculate the distance along the slice normal
597 // using the IPP ("Image Position Patient") tag.
598 // ("dist" is initialized to zero before reading the first slice) :
599 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
600 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
601 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
603 ipp[0] = (*it)->GetXOrigin();
604 ipp[1] = (*it)->GetYOrigin();
605 ipp[2] = (*it)->GetZOrigin();
608 for ( int i = 0; i < 3; ++i )
610 dist += normal[i]*ipp[i];
613 distlist.push_back( dist );
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 );
632 min = (min < dist) ? min : dist;
633 max = (max > dist) ? max : dist;
638 // Then I order the slices according to the value "dist". Finally, once
639 // I've read in all the slices, I calculate the z-spacing as the difference
640 // between the "dist" values for the first two slices.
641 FileVector CoherentFileVector(n);
642 // CoherentFileVector.reserve( n );
643 CoherentFileVector.resize( n );
644 // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
646 // Find out if min/max are coherent
649 gdcmWarningMacro("Looks like all images have the exact same image position"
650 << ". No PositionPatientOrdering sort performed" );
654 float step = (max - min)/(n - 1);
658 //VC++ don't understand what scope is !! it -> it2
659 for (FileList::const_iterator it2 = fileList->begin();
660 it2 != fileList->end(); ++it2, ++n)
663 //Assumption: all files are present (no one missing)
664 pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
666 // a Dicom 'Serie' may contain scout views
667 // and images may have differents directions
668 // -> More than one may have the same 'pos'
669 // Sorting has then NO meaning !
670 if (CoherentFileVector[pos]==NULL)
671 CoherentFileVector[pos] = *it2;
674 gdcmWarningMacro( "At least 2 files with same position."
675 << " No PositionPatientOrdering sort performed");
680 fileList->clear(); // doesn't delete list elements, only nodes
684 //VC++ don't understand what scope is !! it -> it3
685 for (FileVector::const_iterator it3 = CoherentFileVector.begin();
686 it3 != CoherentFileVector.end(); ++it3)
688 fileList->push_back( *it3 );
691 else // user asked for reverse order
693 FileVector::const_iterator it4;
694 it4 = CoherentFileVector.end();
698 fileList->push_back( *it4 );
699 } while (it4 != CoherentFileVector.begin() );
703 CoherentFileVector.clear();
708 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
710 return file1->GetImageNumber() < file2->GetImageNumber();
713 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
715 return file1->GetImageNumber() > file2->GetImageNumber();
719 * \brief sorts the images, according to their Image Number
720 * \note Works only on bona fide files (i.e image number is a character string
721 * corresponding to an integer)
722 * within a bona fide serie (i.e image numbers are consecutive)
723 * @param fileList File set (same Serie UID) to sort
724 * @return false if non bona fide stuff encountered
726 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
729 int n = fileList->size();
731 FileList::const_iterator it = fileList->begin();
732 min = max = (*it)->GetImageNumber();
734 for (; it != fileList->end(); ++it, ++n)
736 pos = (*it)->GetImageNumber();
737 min = (min < pos) ? min : pos;
738 max = (max > pos) ? max : pos;
741 // Find out if image numbers are coherent (consecutive)
742 if ( min == max || max == 0 || max >= (n+min) )
744 gdcmWarningMacro( " 'Image numbers' not coherent. "
745 << " No ImageNumberOrdering sort performed.");
749 std::sort(fileList->begin(), fileList->end(),
750 SerieHelper::ImageNumberLessThan );
752 std::sort(fileList->begin(), fileList->end(),
753 SerieHelper::ImageNumberGreaterThan );
758 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
760 return file1->GetFileName() < file2->GetFileName();
763 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
765 return file1->GetFileName() > file2->GetFileName();
768 * \brief sorts the images, according to their File Name
769 * @param fileList Coherent File list (same Serie UID) to sort
770 * @return false only if the header is bugged !
772 bool SerieHelper::FileNameOrdering(FileList *fileList)
775 std::sort(fileList->begin(), fileList->end(),
776 SerieHelper::FileNameLessThan);
778 std::sort(fileList->begin(), fileList->end(),
779 SerieHelper::FileNameGreaterThan);
785 * \brief sorts the images, according to user supplied function
786 * @param fileList Coherent File list (same Serie UID) to sort
787 * @return false only if the header is bugged !
789 bool SerieHelper::UserOrdering(FileList *fileList)
791 std::sort(fileList->begin(), fileList->end(),
792 SerieHelper::UserLessThanFunction);
795 std::reverse(fileList->begin(), fileList->end());
800 //-----------------------------------------------------------------------------
803 * \brief Canonical printer.
805 void SerieHelper::Print(std::ostream &os, std::string const &indent)
807 // For all the Coherent File lists of the gdcm::Serie
808 SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
809 if ( itl == SingleSerieUIDFileSetHT.end() )
811 gdcmWarningMacro( "No SingleSerieUID File set found" );
814 while (itl != SingleSerieUIDFileSetHT.end())
816 os << "Serie UID :[" << itl->first << "]" << std::endl;
818 // For all the files of a SingleSerieUID File set
819 for (FileList::iterator it = (itl->second)->begin();
820 it != (itl->second)->end();
823 os << indent << " --- " << (*it)->GetFileName() << std::endl;
829 //-----------------------------------------------------------------------------
830 } // end namespace gdcm