1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2005/08/31 16:24:19 $
7 Version: $Revision: 1.20 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmSerieHelper.h"
20 #include "gdcmDirList.h"
22 #include "gdcmDictEntry.h" // for TranslateToKey
23 #include "gdcmDebug.h"
32 //-----------------------------------------------------------------------------
34 //-----------------------------------------------------------------------------
35 // Constructor / Destructor
37 * \brief Constructor from a given SerieHelper
39 SerieHelper::SerieHelper()
41 UserLessThanFunction = 0;
43 // For all the File lists that may already exist within the gdcm::Serie
44 FileList *l = GetFirstCoherentFileList();
47 // For all the files of a File list
48 for (gdcm::FileList::iterator it = l->begin();
52 delete *it; // remove entry
55 delete l; // remove the list
56 l = GetNextCoherentFileList();
62 * \brief Canonical destructor.
64 SerieHelper::~SerieHelper()
66 // For all the Coherent File lists of the gdcm::Serie
67 FileList *l = GetFirstCoherentFileList();
70 // For all the files of a Coherent File list
71 for (FileList::iterator it = l->begin();
75 delete *it; // remove entry
78 delete l; // remove the list
79 l = GetNextCoherentFileList();
83 //-----------------------------------------------------------------------------
85 //-----------------------------------------------------------------------------
89 * \brief add a gdcm::File to the list corresponding to its Serie UID
90 * @param filename Name of the file to deal with
92 void SerieHelper::AddFileName(std::string const &filename)
94 // Create a DICOM file
95 File *header = new File ();
96 header->SetLoadMode(LoadMode);
97 header->SetFileName( filename );
100 if ( header->IsReadable() )
103 // First step the user has defined a set of rules for the DICOM file
104 // he is looking for.
105 // make sure the file correspond to his set of rules:
108 for(SerieRestrictions::iterator it = Restrictions.begin();
109 it != Restrictions.end();
113 // doesn't compile (no matching function...).
114 const std::string s;// = header->GetEntryValue( r.first );
115 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
117 // Argh ! This rule is unmatch let's just quit
123 // Just keep 'new style' for Rules
125 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
126 it2 != ExRestrictions.end();
129 const ExRule &r = *it2;
130 s = header->GetEntryValue( r.group, r.elem );
131 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
133 // Argh ! This rule is unmatch let's just quit
139 if ( allrules ) // all rules are respected:
141 // Allright ! we have a found a DICOM that match the user expectation.
144 // 0020 000e UI REL Series Instance UID
145 const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
146 // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
147 // no need here to do anything special
149 if ( CoherentFileListHT.count(uid) == 0 )
151 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
152 // create a std::list in 'uid' position
153 CoherentFileListHT[uid] = new FileList;
155 // Current Serie UID and DICOM header seems to match; add the file:
156 CoherentFileListHT[uid]->push_back( header );
160 // at least one rule was unmatch we need to deallocate the file:
166 gdcmWarningMacro("Could not read file: " << filename );
172 * \brief add a gdcm::File to the first (and supposed to be unique) list
173 * of the gdcm::SerieHelper.
174 * \warning : this method should be used by aware users only!
175 * User is supposed to know the files he want to deal with
176 * and consider them they belong to the same Serie
177 * (even if their Serie UID is different)
178 * user will probabely OrderFileList() this list (actually, ordering
179 * user choosen gdm::File is the sole interest of this method)
180 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
181 * vtkGdcmReader parsing twice the same files.
182 * *no* coherence check is performed, but those specified
183 * by SerieHelper::AddRestriction()
184 * @param header gdcm::File* of the file to deal with
186 void SerieHelper::AddGdcmFile(File *header)
189 // First step the user has defined a set of rules for the DICOM
190 // he is looking for.
191 // make sure the file correspond to his set of rules:
192 for(SerieRestrictions::iterator it = Restrictions.begin();
193 it != Restrictions.end();
197 const std::string s;// = header->GetEntryValue( r.first );
198 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
200 // Argh ! This rule is unmatch let's just quit
205 if ( allrules ) // all rules are respected:
207 // Allright ! we have a found a DICOM that match the user expectation.
210 const std::string &uid = "0";
211 // Serie UID of the gdcm::File* may be different.
212 // User is supposed to know what he wants
214 if ( CoherentFileListHT.count(uid) == 0 )
216 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
217 // create a std::list in 'uid' position
218 CoherentFileListHT[uid] = new FileList;
220 // Current Serie UID and DICOM header seems to match; add the file:
221 CoherentFileListHT[uid]->push_back( header );
223 // Even if a rule was unmatch we don't deallocate the gdcm::File:
227 * \brief add a rules for restricting a DICOM file to be in the serie we are
228 * trying to find. For example you can select only the DICOM file from a
229 * directory which would have a particular EchoTime==4.0.
230 * This method is a user level, value is not required to be formatted as a DICOM
232 * @param group Group number of the target tag.
233 * @param elem Element number of the target tag.
234 * @param value value to be checked to exclude File
235 * @param op operator we want to use to check
237 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
238 std::string const &value, int op)
245 ExRestrictions.push_back( r );
248 #ifndef GDCM_LEGACY_REMOVE
250 * \brief add a rules for restricting a DICOM file to be in the serie we are
251 * trying to find. For example you can select only the DICOM file from a
252 * directory which would have a particular EchoTime==4.0.
253 * This method is a user level, value is not required to be formatted as a DICOM
255 * @param group Group number of the target tag.
256 * @param elem Element number of the target tag.
257 * @param value value to be checked to exclude File
258 * @deprecated use : AddRestriction(uint16_t group, uint16_t elem,
259 * std::string const &value, int op);
261 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
266 Restrictions.push_back( r );
271 * \brief Sets the root Directory
272 * @param dir Name of the directory to deal with
273 * @param recursive whether we want explore recursively the Directory
275 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
277 DirList dirList(dir, recursive); // OS specific
279 DirListType filenames_list = dirList.GetFilenames();
280 for( DirListType::const_iterator it = filenames_list.begin();
281 it != filenames_list.end(); ++it)
288 * \brief Sorts the given File List
289 * \warning This could be implemented in a 'Strategy Pattern' approach
290 * But as I don't know how to do it, I leave it this way
291 * BTW, this is also a Strategy, I don't know this is the best approach :)
293 void SerieHelper::OrderFileList(FileList *coherentFileList)
296 if ( SerieHelper::UserLessThanFunction )
298 UserOrdering( coherentFileList );
301 else if ( ImagePositionPatientOrdering( coherentFileList ) )
305 else if ( ImageNumberOrdering(coherentFileList ) )
311 FileNameOrdering(coherentFileList );
316 * \brief Elementary coherence checking of the files with the same Serie UID
317 * Only sizes and pixel type are checked right now ...
319 bool SerieHelper::IsCoherent(FileList *coherentFileList)
321 if(coherentFileList->size() == 1)
324 FileList::const_iterator it = coherentFileList->begin();
326 int nX = (*it)->GetXSize();
327 int nY = (*it)->GetYSize();
328 int pixelSize = (*it)->GetPixelSize();
332 it != coherentFileList->end();
335 if ( (*it)->GetXSize() != nX )
337 if ( (*it)->GetYSize() != nY )
339 if ( (*it)->GetPixelSize() != pixelSize )
341 // probabely more is to be checked (?)
346 * \brief Get the first List while visiting the CoherentFileListHT
347 * @return The first FileList if found, otherwhise NULL
349 FileList *SerieHelper::GetFirstCoherentFileList()
351 ItListHt = CoherentFileListHT.begin();
352 if ( ItListHt != CoherentFileListHT.end() )
353 return ItListHt->second;
358 * \brief Get the next List while visiting the CoherentFileListHT
359 * \note : meaningfull only if GetFirstCoherentFileList() already called
360 * @return The next FileList if found, otherwhise NULL
362 FileList *SerieHelper::GetNextCoherentFileList()
364 gdcmAssertMacro (ItListHt != CoherentFileListHT.end());
367 if ( ItListHt != CoherentFileListHT.end() )
368 return ItListHt->second;
373 * \brief Get the Coherent Files list according to its Serie UID
374 * @param SerieUID SerieUID
375 * \return pointer to the Coherent Files list if found, otherwhise NULL
377 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
379 if ( CoherentFileListHT.count(SerieUID) == 0 )
381 return CoherentFileListHT[SerieUID];
384 //-----------------------------------------------------------------------------
387 //-----------------------------------------------------------------------------
390 * \brief sorts the images, according to their Patient Position
391 * We may order, considering :
392 * -# Image Position Patient
394 * -# More to come :-)
395 * WARNING : FileList = std::vector<File* >
396 * @param fileList Coherent File list (same Serie UID) to sort
397 * @return false only if the header is bugged !
399 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
400 //based on Jolinda Smith's algorithm
402 //iop is calculated based on the file file
407 float min = 0, max = 0;
410 std::vector<float> distlist;
412 //!\todo rewrite this for loop.
413 for ( FileList::const_iterator
414 it = fileList->begin();
415 it != fileList->end(); ++it )
419 (*it)->GetImageOrientationPatient( cosines );
421 // You only have to do this once for all slices in the volume. Next,
422 // for each slice, calculate the distance along the slice normal
423 // using the IPP tag ("dist" is initialized to zero before reading
424 // the first slice) :
425 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
426 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
427 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
429 ipp[0] = (*it)->GetXOrigin();
430 ipp[1] = (*it)->GetYOrigin();
431 ipp[2] = (*it)->GetZOrigin();
434 for ( int i = 0; i < 3; ++i )
436 dist += normal[i]*ipp[i];
439 distlist.push_back( dist );
446 ipp[0] = (*it)->GetXOrigin();
447 ipp[1] = (*it)->GetYOrigin();
448 ipp[2] = (*it)->GetZOrigin();
451 for ( int i = 0; i < 3; ++i )
453 dist += normal[i]*ipp[i];
456 distlist.push_back( dist );
458 min = (min < dist) ? min : dist;
459 max = (max > dist) ? max : dist;
464 // Then I order the slices according to the value "dist". Finally, once
465 // I've read in all the slices, I calculate the z-spacing as the difference
466 // between the "dist" values for the first two slices.
467 FileVector CoherentFileVector(n);
468 // CoherentFileVector.reserve( n );
469 CoherentFileVector.resize( n );
470 // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
472 // Find out if min/max are coherent
475 gdcmWarningMacro( "Looks like all images have the exact same image position."
476 << "No PositionPatientOrdering sort performed" );
480 float step = (max - min)/(n - 1);
484 //VC++ don't understand what scope is !! it -> it2
485 for (FileList::const_iterator it2 = fileList->begin();
486 it2 != fileList->end(); ++it2, ++n)
489 //Assumption: all files are present (no one missing)
490 pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
492 // a Dicom 'Serie' may contain scout views
493 // and images may have differents directions
494 // -> More than one may have the same 'pos'
495 // Sorting has then NO meaning !
496 if (CoherentFileVector[pos]==NULL)
497 CoherentFileVector[pos] = *it2;
500 gdcmWarningMacro( "At least 2 files with same position. No PositionPatientOrdering sort performed");
505 fileList->clear(); // doesn't delete list elements, only nodes
509 //VC++ don't understand what scope is !! it -> it3
510 for (FileVector::const_iterator it3 = CoherentFileVector.begin();
511 it3 != CoherentFileVector.end(); ++it3)
513 fileList->push_back( *it3 );
516 else // user asked for reverse order
518 FileVector::const_iterator it4;
519 it4 = CoherentFileVector.end();
523 fileList->push_back( *it4 );
524 } while (it4 != CoherentFileVector.begin() );
528 CoherentFileVector.clear();
533 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
535 return file1->GetImageNumber() < file2->GetImageNumber();
538 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
540 return file1->GetImageNumber() > file2->GetImageNumber();
543 * \brief sorts the images, according to their Image Number
544 * \note Works only on bona fide files (i.e image number is a character string
545 * corresponding to an integer)
546 * within a bona fide serie (i.e image numbers are consecutive)
547 * @param fileList Coherent File list (same Serie UID) to sort
548 * @return false if non bona fide stuff encountered
550 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
553 int n = fileList->size();
555 FileList::const_iterator it = fileList->begin();
556 min = max = (*it)->GetImageNumber();
558 for (; it != fileList->end(); ++it, ++n)
560 pos = (*it)->GetImageNumber();
561 min = (min < pos) ? min : pos;
562 max = (max > pos) ? max : pos;
565 // Find out if image numbers are coherent (consecutive)
566 if ( min == max || max == 0 || max >= (n+min) )
568 gdcmWarningMacro( " 'Image numbers' not coherent. No ImageNumberOrdering sort performed.");
572 std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
574 std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberGreaterThan );
579 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
581 return file1->GetFileName() < file2->GetFileName();
584 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
586 return file1->GetFileName() > file2->GetFileName();
589 * \brief sorts the images, according to their File Name
590 * @param fileList Coherent File list (same Serie UID) to sort
591 * @return false only if the header is bugged !
593 bool SerieHelper::FileNameOrdering(FileList *fileList)
596 std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
598 std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameGreaterThan);
604 * \brief sorts the images, according to user supplied function
605 * @param fileList Coherent File list (same Serie UID) to sort
606 * @return false only if the header is bugged !
608 bool SerieHelper::UserOrdering(FileList *fileList)
610 std::sort(fileList->begin(), fileList->end(), SerieHelper::UserLessThanFunction);
613 std::reverse(fileList->begin(), fileList->end());
618 //-----------------------------------------------------------------------------
621 * \brief Canonical printer.
623 void SerieHelper::Print(std::ostream &os, std::string const &indent)
625 // For all the Coherent File lists of the gdcm::Serie
626 CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
627 if ( itl == CoherentFileListHT.end() )
629 gdcmWarningMacro( "No Coherent File list found" );
632 while (itl != CoherentFileListHT.end())
634 os << "Serie UID :[" << itl->first << "]" << std::endl;
636 // For all the files of a Coherent File list
637 for (FileList::iterator it = (itl->second)->begin();
638 it != (itl->second)->end();
641 os << indent << " --- " << (*it)->GetFileName() << std::endl;
647 //-----------------------------------------------------------------------------
648 } // end namespace gdcm