]> Creatis software - gdcm.git/blob - vtk/vtkgdcmSerieViewer.cxx
COMP: Ugly fix to remove warning
[gdcm.git] / vtk / vtkgdcmSerieViewer.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkgdcmSerieViewer.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/09/04 15:40:25 $
7   Version:   $Revision: 1.10 $
8                                                                                 
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.
12                                                                                 
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.
16                                                                                 
17 =========================================================================*/
18 // This example illustrates how the vtkGdcmReader vtk class can 
19 // use the result of gdcm::SerieHelper constructor and check
20 // the various Setters :
21 //     SerieHelper::SetOrderToReverse, 
22 //     SerieHelper::SetUserLessThanFunction
23 //     SerieHelper::SetLoadMode
24 //     vtkGdcmReader::SetUserFunction
25 //     vtkGdcmReader::SetCoherentFileList
26 // Usage:
27 //  * the Directory name that contains the Dicom images constituting the stack 
28 //    should be given as command line argument (keyword : dirname=),
29 //  * you can navigate through the stack by hitting any character key,
30 //  * the produced vtk file is named "foo.vtk" (in the invocation directory).
31 // 
32 //----------------------------------------------------------------------------
33 #include <vtkRenderWindowInteractor.h>
34 #include <vtkImageViewer.h>
35 #include <vtkStructuredPoints.h>
36 #include <vtkStructuredPointsWriter.h>
37 #include <vtkCommand.h>
38 #include <vtkRenderer.h>
39 #include <vtkImageMapToColors.h>
40 #include <vtkLookupTable.h>
41
42 #include "vtkGdcmReader.h"
43 #include "gdcmDocument.h"  // for NO_SHADOWSEQ
44 #include "gdcmSerieHelper.h"
45 #include "gdcmDebug.h"
46 #include "gdcmValEntry.h"
47
48 #include "gdcmArgMgr.h" // for Argument Manager functions
49 #include <string.h>     // for strcmp
50 #ifndef vtkFloatingPointType
51 #define vtkFloatingPointType float
52 #endif
53
54 void userSuppliedMirrorFunction (uint8_t *im, gdcm::File *f);
55 void userSuppliedTopDownFunction(uint8_t *im, gdcm::File *f);
56 bool userSuppliedLessThanFunction(gdcm::File *f1, gdcm::File *f2);
57 bool userSuppliedLessThanFunction2(gdcm::File *f1, gdcm::File *f2);
58
59 int orderNb;
60 uint16_t *elemsToOrderOn;
61
62 //----------------------------------------------------------------------------
63 // Callback for the interaction
64 class vtkgdcmObserver : public vtkCommand
65 {
66 public:
67    virtual char const *GetClassName() const 
68    { 
69       return "vtkgdcmObserver";
70    }
71
72    static vtkgdcmObserver *New() 
73    { 
74       return new vtkgdcmObserver; 
75    }
76
77    vtkgdcmObserver()
78    {
79       this->ImageViewer = NULL;
80    }
81
82    virtual void Execute(vtkObject *, unsigned long event, void* )
83    {
84       if ( this->ImageViewer )
85       {
86          if ( event == vtkCommand::CharEvent )
87          {
88             int max = ImageViewer->GetWholeZMax();
89             int slice = (ImageViewer->GetZSlice() + 1 ) % ++max;
90             ImageViewer->SetZSlice( slice );
91             ImageViewer->GetRenderer()->ResetCameraClippingRange();
92             ImageViewer->Render();
93          }
94       }
95    }
96    vtkImageViewer *ImageViewer;
97 };
98
99 int main(int argc, char *argv[])
100 {
101    START_USAGE(usage)
102    " \n vtkgdcmSerieViewer : \n",
103    " Display a 'Serie' (same Serie UID) within a Directory                    ",
104    " You can navigate through the stack by hitting any character key.         ",
105    " usage: vtkgdcmSerieViewer dirname=sourcedirectory                        ",
106    "                           [noshadowseq][noshadow][noseq]                 ",
107    "                           [reverse] [{[mirror]|[topdown]|[rotate]}]      ",
108    "                           [order=] [check][debug]                        ",
109    "      sourcedirectory : name of the directory holding the images          ",
110    "                        if it holds more than one serie,                  ",
111    "                        only the first one id displayed.                  ",
112    "      noshadowseq: user doesn't want to load Private Sequences            ",
113    "      noshadow   : user doesn't want to load Private groups (odd number)  ",
114    "      noseq      : user doesn't want to load Sequences                    ",
115    "      reverse    : user wants to sort the images reverse order            ",
116    "      mirror     : user wants to 'mirror' the images | just some simple   ",
117    "      topdown    : user wants to 'topdown' the images| examples of user   ",
118    "      rotate     : NOT YET MADE (useless?)           | supplied functions ",
119    "      check      : user wants to force more coherence checking            ",
120    "      order=     : group1-elem1,group2-elem2,... (in hexa, no space)      ",
121    "                   if we want to use them as a sort criterium             ",
122    "                   Right now : ValEntries only -just an example-          ",
123    "        or                                                                ",
124    "      order=     : order=name if we want to sort on file name (why not ?) ",
125    "      debug      : user wants to run the program in 'debug mode'          ",
126    FINISH_USAGE
127
128
129    // Initialize Arguments Manager   
130    gdcm::ArgMgr *am= new gdcm::ArgMgr(argc, argv);
131   
132    if (argc == 1 || am->ArgMgrDefined("usage") )
133    {
134       am->ArgMgrUsage(usage); // Display 'usage'
135       delete am;
136       return 0;
137    }
138
139    char *dirName = am->ArgMgrWantString("dirname",usage);
140
141    int loadMode = gdcm::LD_ALL;
142    if ( am->ArgMgrDefined("noshadowseq") )
143       loadMode |= gdcm::LD_NOSHADOWSEQ;
144    else 
145    {
146       if ( am->ArgMgrDefined("noshadow") )
147          loadMode |= gdcm::LD_NOSHADOW;
148       if ( am->ArgMgrDefined("noseq") )
149          loadMode |= gdcm::LD_NOSEQ;
150    }
151
152    int reverse = am->ArgMgrDefined("reverse");
153
154    int mirror  = am->ArgMgrDefined("mirror");
155    int topdown = am->ArgMgrDefined("topdown");
156    int rotate  = am->ArgMgrDefined("rotate");
157
158    if ( mirror && topdown )
159    {
160       std::cout << "mirror *OR* topDown !"
161                 << std::endl;
162       delete am;
163       return 0;
164    }
165    if ( rotate )
166    {
167       std::cout << "'rotate' undealt with -> ignored !"
168                 << std::endl;
169    }
170
171    int check   = am->ArgMgrDefined("check");
172   
173    // This is so ugly, a cstring is NOT a char * (god damit!)
174    bool bname = ( strcmp(am->ArgMgrGetString("order", (char*)"not found"),"name")==0 );
175    if (bname)
176       elemsToOrderOn = am->ArgMgrGetXInt16Enum("order", &orderNb);
177
178    if (am->ArgMgrDefined("debug"))
179       gdcm::Debug::DebugOn();
180
181    /* if unused Param we give up */
182    if ( am->ArgMgrPrintUnusedLabels() )
183    {
184       am->ArgMgrUsage(usage);
185       delete am;
186       return 0;
187    } 
188
189    delete am;  // we don't need Argument Manager any longer
190
191    // ----------------------- End Arguments Manager ----------------------
192   
193    gdcm::SerieHelper *sh = new gdcm::SerieHelper();
194    sh->SetLoadMode(loadMode);
195    if (reverse)
196       sh->SetSortOrderToReverse();
197    sh->SetDirectory( dirName, true);
198     
199    // Just to see
200
201    int nbFiles;
202    // For all the Coherent Files lists of the gdcm::Serie
203    gdcm::FileList *l = sh->GetFirstCoherentFileList();
204    if (l == 0 )
205    {
206       std::cout << "Oops! No CoherentFileList found ?!?" << std::endl;
207       return 0;
208    }
209
210    if (bname)
211      sh->SetUserLessThanFunction(userSuppliedLessThanFunction2);
212    else if (orderNb != 0)
213       sh->SetUserLessThanFunction(userSuppliedLessThanFunction);
214
215    while (l)
216    { 
217       nbFiles = l->size() ;
218       if ( l->size() > 1 )
219       {
220          std::cout << "Sort list : " << nbFiles << " long" << std::endl;
221          sh->OrderFileList(l);  // sort the list
222          break;  // The first one is OK. user will have to check
223       }
224       else
225       {
226          std::cout << "Oops! Empty CoherentFileList found ?!?" << std::endl;
227       }
228       l = sh->GetNextCoherentFileList();
229    }
230
231    if (check)
232    {
233       if ( !sh->IsCoherent(l) ) // just be sure (?)
234       {
235          std::cout << "Files are not coherent. Stop everything " << std::endl;
236          delete sh;
237          return 0;
238       }
239    }
240
241    vtkGdcmReader *reader = vtkGdcmReader::New();
242    reader->AllowLookupTableOff();
243
244    if (mirror)
245       reader->SetUserFunction (userSuppliedMirrorFunction);
246    else if (topdown)
247       reader->SetUserFunction (userSuppliedTopDownFunction);
248
249    // Only the first FileList is dealt with (just an example)
250    // (The files will not be parsed twice by the reader)
251
252    //---------------------------------------------------------
253    reader->SetCoherentFileList(l);
254    //---------------------------------------------------------
255
256    // because we passed a Coherent File List from a SerieHelper,
257    // setting LoadMode is useless in this case
258    //  reader->SetLoadMode(NO_SHADOWSEQ);  
259    reader->Update();
260
261    //print debug info:
262    reader->GetOutput()->Print( cout );
263
264    vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
265
266    vtkImageViewer *viewer = vtkImageViewer::New();
267
268    if( reader->GetLookupTable() )
269    {
270       //convert to color:
271       vtkImageMapToColors *map = vtkImageMapToColors::New ();
272       map->SetInput (reader->GetOutput());
273       map->SetLookupTable (reader->GetLookupTable());
274       map->SetOutputFormatToRGB();
275       viewer->SetInput ( map->GetOutput() );
276       map->Delete();
277    }
278    else
279    {
280       vtkFloatingPointType *range = reader->GetOutput()->GetScalarRange();
281       viewer->SetColorLevel (0.5 * (range[1] + range[0]));
282       viewer->SetColorWindow (range[1] - range[0]);
283
284       viewer->SetInput ( reader->GetOutput() );
285    }
286    viewer->SetupInteractor (iren);
287   
288    //vtkFloatingPointType *range = reader->GetOutput()->GetScalarRange();
289    //viewer->SetColorWindow (range[1] - range[0]);
290    //viewer->SetColorLevel (0.5 * (range[1] + range[0]));
291
292    // Here is where we setup the observer, 
293    vtkgdcmObserver *obs = vtkgdcmObserver::New();
294    obs->ImageViewer = viewer;
295    iren->AddObserver(vtkCommand::CharEvent,obs);
296    obs->Delete();
297
298    //viewer->Render();
299    iren->Initialize();
300    iren->Start();
301
302    //if you wish you can export dicom to a vtk file  
303    vtkStructuredPointsWriter *writer = vtkStructuredPointsWriter::New();
304    writer->SetInput( reader->GetOutput());
305    writer->SetFileName( "foo.vtk" );
306    writer->SetFileTypeToBinary();
307    //writer->Write();
308
309    reader->Delete();
310    iren->Delete();
311    viewer->Delete();
312    writer->Delete();
313
314    return 0;
315 }
316
317
318 // --------------------------------------------------------
319 // This is just a *very* simple example of user supplied function
320 //      to mirror (why not ?) the image
321 // It's *not* part of gdcm.
322 // --------------------------------------------------------
323
324 #define UF(ty)                          \
325    int i, j;                            \
326    ty *imj;                             \
327    ty tamp;                             \
328    for (j=0;j<ny;j++)                   \
329    {                                    \
330       imj = (ty *)im +j*nx;             \
331       for (i=0;i<nx/2;i++)              \
332       {                                 \
333         tamp       =imj[i];             \
334         imj[i]     =imj[nx-1-i];        \
335         imj[nx-1-i]=tamp;               \
336       }                                 \
337    }                                    \
338    if (nx%2 != 0)                       \
339    {                                    \
340       for (j=0;j<ny;j++)                \
341       {                                 \
342         imj = (ty *)im  +j*nx;          \
343         tamp       =imj[i];             \
344         imj[i]     =imj[nx/2+1];        \
345         imj[nx/2+1]=tamp;               \
346       }                                 \
347    }
348
349 void userSuppliedMirrorFunction(uint8_t *im, gdcm::File *f)
350 {
351    if (f->GetZSize() != 1)
352    {
353       std::cout << "mirror : Multiframe images not yet dealt with" << std::endl;
354       return;
355    }
356
357    if (f->GetSamplesPerPixel() != 1 || f->GetBitsAllocated() == 24)
358    {
359       std::cout << "mirror : RGB / YBR not yet dealt with" << std::endl;
360       return;
361    }
362    int nx = f->GetXSize();
363    int ny = f->GetYSize();
364
365    std::string pixelType = f->GetPixelType();
366    if ( pixelType ==  "8U" || pixelType == "8S" )
367    {
368       UF(uint8_t)
369       return;
370    }
371    if ( pixelType == "16U" || pixelType == "16S")
372    {
373       UF(uint16_t)
374       return;
375    }
376    std::cout << "mirror : Pixel Size (!=8, !=16) not yet dealt with" 
377              << std::endl;
378    return;
379 }
380
381
382 // --------------------------------------------------------
383 // This is just a *very* simple example of user supplied function
384 //      to topdown (why not ?) the image
385 // It's *not* part of gdcm.
386 // --------------------------------------------------------
387
388 #define UF2(ty)                         \
389    int i, j;                            \
390    ty *imj, *imJ;                       \
391    ty tamp;                             \
392    for (j=0;j<ny/2;j++)                 \
393    {                                    \
394       imj = (ty *)im +j*nx;             \
395       imJ = (ty *)im +(ny-1-j)*nx;      \
396       for (i=0;i<nx;i++)                \
397       {                                 \
398         tamp       =imj[i];             \
399         imj[i]     =imJ[i];             \
400         imJ[i]     =tamp;               \
401       }                                 \
402    }
403
404 void userSuppliedTopDownFunction(uint8_t *im, gdcm::File *f)
405 {
406    if (f->GetZSize() != 1)
407    {
408       std::cout << "mirror : Multiframe images not yet dealt with" << std::endl;
409       return;
410    }
411
412    if (f->GetSamplesPerPixel() != 1 || f->GetBitsAllocated() == 24)
413    {
414       std::cout << "mirror : RGB / YBR not yet dealt with" << std::endl;
415       return;
416    }
417    int nx = f->GetXSize();
418    int ny = f->GetYSize();
419
420    std::string pixelType = f->GetPixelType();
421    if ( pixelType ==  "8U" || pixelType == "8S" )
422    {
423       UF2(uint8_t)
424       return;
425    }
426    if ( pixelType == "16U" || pixelType == "16S")
427    {
428       UF2(uint16_t)
429       return;
430    }
431    std::cout << "topdown : Pixel Size (!=8, !=16) not yet dealt with" 
432              << std::endl;
433    return;
434 }
435
436 // --------------------------------------------------------
437 // This is just a *very* simple example of user supplied 'LessThan' function
438 // It's *not* part of gdcm.
439 //
440 // Note : orderNb and elemsToOrderOn are here global variables.
441 // Within a 'normal' function they would't be any orderNb and elemsToOrderOn var
442 // User *knows* on what field(s) he wants to compare; 
443 // He just writes a decent function.
444 // Here, we want to get info from the command line Argument Manager.
445 //
446 // Warning : it's up to 'vtkgdcmSerieViewer' user to find a suitable data set !
447 // --------------------------------------------------------
448
449
450 bool userSuppliedLessThanFunction(gdcm::File *f1, gdcm::File *f2)
451 {
452    // for *this* user supplied function, I supposed only ValEntries are checked.
453 // 
454    std::string s1, s2;
455    gdcm::ValEntry *e1,*e2;
456    for (int ri=0; ri<orderNb; ri++)
457    {
458       std::cout << std::hex << elemsToOrderOn[2*ri] << "|" 
459                             << elemsToOrderOn[2*ri+1]
460                             << std::endl;
461  
462       e1= f1->gdcm::Document::GetValEntry( elemsToOrderOn[2*ri],
463                                  elemsToOrderOn[2*ri+1]);
464
465       e2= f2->gdcm::Document::GetValEntry( elemsToOrderOn[2*ri],
466                                  elemsToOrderOn[2*ri+1]);
467       if(!e2 || !e2)
468       {
469          std::cout << std::hex << elemsToOrderOn[2*ri] << "|"
470                               << elemsToOrderOn[2*ri+1]
471                               << " not found" << std::endl;
472          continue;
473       }
474       s1 = e1->gdcm::ValEntry::GetValue();      
475       s2 = e2->gdcm::ValEntry::GetValue();
476       std::cout << "[" << s1 << "] vs [" << s2 << "]" << std::endl;
477       if ( s1 < s2 ) 
478          return true;
479       else if (s1 == s2 )
480          continue;
481       else 
482          return false;
483    }
484    return false; // all fields equal
485 }
486
487 // --------------------------------------------------------
488 // This is just an other *very* simple example of user supplied 'LessThan'
489 // function
490 // It's *not* part of gdcm.
491 //
492 // Warning : it's up to 'vtkgdcmSerieViewer' user to find a suitable data set !
493 // --------------------------------------------------------
494
495 bool userSuppliedLessThanFunction2(gdcm::File *f1, gdcm::File *f2)
496 {
497    std::cout << "[" << f1->GetFileName() << "] vs [" 
498                     << f2->GetFileName() << "]" << std::endl;
499    return f1->GetFileName() < f2->GetFileName();
500 }