]> Creatis software - gdcm.git/blob - vtk/vtkgdcmSerieViewer2.cxx
COMP: Fix comp on 64bits machine and VTK5
[gdcm.git] / vtk / vtkgdcmSerieViewer2.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkgdcmSerieViewer2.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/03/30 17:11:11 $
7   Version:   $Revision: 1.4 $
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 <vtkImageViewer2.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 "gdcmDataEntry.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 userSuppliedUpsideDownFunction(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    vtkImageViewer2 *ImageViewer;
97 };
98
99 int main(int argc, char *argv[])
100 {
101    START_USAGE(usage)
102    " \n vtkgdcmSerieViewer2 : \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 is 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    "      upsidedown : user wants to 'upsidedown' the images| examples of user",
118    "                                                        | definedfunctions",
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 upsidedown = am->ArgMgrDefined("upsidedown");
156
157    if ( mirror && upsidedown )
158    {
159       std::cout << "*EITHER* mirror *OR* upsidedown !"
160                 << std::endl;
161       delete am;
162       return 0;
163    }
164
165    int check   = am->ArgMgrDefined("check");
166   
167    // This is so ugly, a cstring is NOT a char * (god damit!)
168    bool bname = ( strcmp(am->ArgMgrGetString("order", "not found"),"name")==0 );
169    if (bname)
170       elemsToOrderOn = am->ArgMgrGetXInt16Enum("order", &orderNb);
171
172    if (am->ArgMgrDefined("debug"))
173       gdcm::Debug::DebugOn();
174
175    /* if unused Param we give up */
176    if ( am->ArgMgrPrintUnusedLabels() )
177    {
178       am->ArgMgrUsage(usage);
179       delete am;
180       return 0;
181    } 
182
183    delete am;  // we don't need Argument Manager any longer
184
185    // ----------------------- End Arguments Manager ----------------------
186   
187    gdcm::SerieHelper *sh = gdcm::SerieHelper::New();
188    sh->SetLoadMode(loadMode);
189    if (reverse)
190       sh->SetSortOrderToReverse();
191    sh->SetDirectory( dirName, true);
192     
193    // Just to see
194
195    int nbFiles;
196    // For all the 'Single Serie UID' FileSets of the gdcm::Serie
197    gdcm::FileList *l = sh->GetFirstSingleSerieUIDFileSet();
198    if (l == 0 )
199    {
200       std::cout << "Oops! No 'Single Serie UID' FileSet found ?!?" << std::endl;
201       return 0;
202    }
203
204    if (bname)
205      sh->SetUserLessThanFunction(userSuppliedLessThanFunction2);
206    else if (orderNb != 0)
207       sh->SetUserLessThanFunction(userSuppliedLessThanFunction);
208
209    while (l)
210    { 
211       nbFiles = l->size() ;
212       if ( l->size() > 1 )
213       {
214          std::cout << "Sort list : " << nbFiles << " long" << std::endl;
215          sh->OrderFileList(l);  // sort the list
216          double zsp = sh->GetZSpacing();
217          std::cout << "List sorted, ZSpacing = " << zsp << std::endl;
218          break;  // The first one is OK. user will have to check
219       }
220       else
221       {
222          std::cout << "Oops! Empty 'Single Serie UID' FileSet found ?!?"
223                    << std::endl;
224       }
225       l = sh->GetNextSingleSerieUIDFileSet();
226    }
227
228    if (check)
229    {
230       if ( !sh->IsCoherent(l) ) // just be sure (?)
231       {
232          std::cout << "Files are not coherent. Stop everything " << std::endl;
233          sh->Delete();
234          return 0;
235       }
236    }
237
238    vtkGdcmReader *reader = vtkGdcmReader::New();
239    reader->AllowLookupTableOff();
240
241    if (mirror)
242       reader->SetUserFunction (userSuppliedMirrorFunction);
243    else if (upsidedown)
244       reader->SetUserFunction (userSuppliedUpsideDownFunction);
245
246    // Only the first FileList is dealt with (just an example)
247    // (The files will not be parsed twice by the reader)
248
249    //---------------------------------------------------------
250    reader->SetCoherentFileList(l);
251    //---------------------------------------------------------
252
253    // because we passed a Coherent File List from a SerieHelper,
254    // setting LoadMode is useless in this case
255    //  reader->SetLoadMode(NO_SHADOWSEQ);  
256    reader->Update();
257
258    //print debug info:
259    reader->GetOutput()->Print( cout );
260
261    vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
262
263    vtkImageViewer2 *viewer = vtkImageViewer2::New();
264
265    if( reader->GetLookupTable() )
266    {
267       //convert to color:
268       vtkImageMapToColors *map = vtkImageMapToColors::New ();
269       map->SetInput (reader->GetOutput());
270       map->SetLookupTable (reader->GetLookupTable());
271       map->SetOutputFormatToRGB();
272       viewer->SetInput ( map->GetOutput() );
273       map->Delete();
274    }
275    else
276    {
277       vtkFloatingPointType *range = reader->GetOutput()->GetScalarRange();
278       viewer->SetColorLevel (0.5 * (range[1] + range[0]));
279       viewer->SetColorWindow (range[1] - range[0]);
280
281       viewer->SetInput ( reader->GetOutput() );
282    }
283    viewer->SetupInteractor (iren);
284   
285    //vtkFloatingPointType *range = reader->GetOutput()->GetScalarRange();
286    //viewer->SetColorWindow (range[1] - range[0]);
287    //viewer->SetColorLevel (0.5 * (range[1] + range[0]));
288
289    // Here is where we setup the observer, 
290    vtkgdcmObserver *obs = vtkgdcmObserver::New();
291    obs->ImageViewer = viewer;
292    iren->AddObserver(vtkCommand::CharEvent,obs);
293    obs->Delete();
294
295    //viewer->Render();
296    iren->Initialize();
297    iren->Start();
298
299    //if you wish you can export dicom to a vtk file  
300    vtkStructuredPointsWriter *writer = vtkStructuredPointsWriter::New();
301    writer->SetInput( reader->GetOutput());
302    writer->SetFileName( "foo.vtk" );
303    writer->SetFileTypeToBinary();
304    //writer->Write();
305
306    reader->Delete();
307    iren->Delete();
308    viewer->Delete();
309    writer->Delete();
310
311    return 0;
312 }
313
314
315 // --------------------------------------------------------
316 // This is just a *very* simple example of user supplied function
317 //      to mirror (why not ?) the image
318 // It's *not* part of gdcm.
319 // --------------------------------------------------------
320
321 #define UF(ty)                          \
322    int i, j;                            \
323    ty *imj;                             \
324    ty tamp;                             \
325    for (j=0;j<ny;j++)                   \
326    {                                    \
327       imj = (ty *)im +j*nx;             \
328       for (i=0;i<nx/2;i++)              \
329       {                                 \
330         tamp       =imj[i];             \
331         imj[i]     =imj[nx-1-i];        \
332         imj[nx-1-i]=tamp;               \
333       }                                 \
334    }                                    \
335    if (nx%2 != 0)                       \
336    {                                    \
337       i = nx / 2;                       \
338       for (j=0;j<ny;j++)                \
339       {                                 \
340         imj = (ty *)im  +j*nx;          \
341         tamp       =imj[i];             \
342         imj[i]     =imj[nx/2+1];        \
343         imj[nx/2+1]=tamp;               \
344       }                                 \
345    }
346
347 void userSuppliedMirrorFunction(uint8_t *im, gdcm::File *f)
348 {
349    if (f->GetZSize() != 1)
350    {
351       std::cout << "mirror : Multiframe images not yet dealt with" << std::endl;
352       return;
353    }
354
355    if (f->GetSamplesPerPixel() != 1 || f->GetBitsAllocated() == 24)
356    {
357       std::cout << "mirror : RGB / YBR not yet dealt with" << std::endl;
358       return;
359    }
360    int nx = f->GetXSize();
361    int ny = f->GetYSize();
362
363    std::string pixelType = f->GetPixelType();
364    if ( pixelType ==  "8U" || pixelType == "8S" )
365    {
366       UF(uint8_t)
367       return;
368    }
369    if ( pixelType == "16U" || pixelType == "16S")
370    {
371       UF(uint16_t)
372       return;
373    }
374    std::cout << "mirror : Pixel Size (!=8, !=16) not yet dealt with" 
375              << std::endl;
376    return;
377 }
378
379
380 // --------------------------------------------------------
381 // This is just a *very* simple example of user supplied function
382 //      to upsidedown (why not ?) the image
383 // It's *not* part of gdcm.
384 // --------------------------------------------------------
385
386 #define UF2(ty)                         \
387    int i, j;                            \
388    ty *imj, *imJ;                       \
389    ty tamp;                             \
390    for (j=0;j<ny/2;j++)                 \
391    {                                    \
392       imj = (ty *)im +j*nx;             \
393       imJ = (ty *)im +(ny-1-j)*nx;      \
394       for (i=0;i<nx;i++)                \
395       {                                 \
396         tamp       =imj[i];             \
397         imj[i]     =imJ[i];             \
398         imJ[i]     =tamp;               \
399       }                                 \
400    }
401
402 void userSuppliedUpsideDownFunction(uint8_t *im, gdcm::File *f)
403 {
404    if (f->GetZSize() != 1)
405    {
406       std::cout << "mirror : Multiframe images not yet dealt with" << std::endl;
407       return;
408    }
409
410    if (f->GetSamplesPerPixel() != 1 || f->GetBitsAllocated() == 24)
411    {
412       std::cout << "mirror : RGB / YBR not yet dealt with" << std::endl;
413       return;
414    }
415    int nx = f->GetXSize();
416    int ny = f->GetYSize();
417
418    std::string pixelType = f->GetPixelType();
419    if ( pixelType ==  "8U" || pixelType == "8S" )
420    {
421       UF2(uint8_t)
422       return;
423    }
424    if ( pixelType == "16U" || pixelType == "16S")
425    {
426       UF2(uint16_t)
427       return;
428    }
429    std::cout << "topdown : Pixel Size (!=8, !=16) not yet dealt with" 
430              << std::endl;
431    return;
432 }
433
434 // --------------------------------------------------------
435 // This is just a *very* simple example of user supplied 'LessThan' function
436 // It's *not* part of gdcm.
437 //
438 // Note : orderNb and elemsToOrderOn are here global variables.
439 // Within a 'normal' function they would't be any orderNb and elemsToOrderOn var
440 // User *knows* on what field(s) he wants to compare; 
441 // He just writes a decent function.
442 // Here, we want to get info from the command line Argument Manager.
443 //
444 // Warning : it's up to 'vtkgdcmSerieViewer' user to find a suitable data set !
445 // --------------------------------------------------------
446
447
448 bool userSuppliedLessThanFunction(gdcm::File *f1, gdcm::File *f2)
449 {
450    // for *this* user supplied function, I supposed only ValEntries are checked.
451 // 
452    std::string s1, s2;
453    gdcm::DataEntry *e1,*e2;
454    for (int ri=0; ri<orderNb; ri++)
455    {
456       std::cout << std::hex << elemsToOrderOn[2*ri] << "|" 
457                             << elemsToOrderOn[2*ri+1]
458                             << std::endl;
459  
460       e1= f1->GetDataEntry( elemsToOrderOn[2*ri],
461                  elemsToOrderOn[2*ri+1]);
462
463       e2= f2->GetDataEntry( elemsToOrderOn[2*ri],
464                                  elemsToOrderOn[2*ri+1]);
465       if(!e2 || !e2)
466       {
467          std::cout << std::hex << elemsToOrderOn[2*ri] << "|"
468                               << elemsToOrderOn[2*ri+1]
469                               << " not found" << std::endl;
470          continue;
471       }
472       s1 = e1->GetString();      
473       s2 = e2->GetString();
474       std::cout << "[" << s1 << "] vs [" << s2 << "]" << std::endl;
475       if ( s1 < s2 ) 
476          return true;
477       else if (s1 == s2 )
478          continue;
479       else 
480          return false;
481    }
482    return false; // all fields equal
483 }
484
485 // --------------------------------------------------------
486 // This is just an other *very* simple example of user supplied 'LessThan'
487 // function
488 // It's *not* part of gdcm.
489 //
490 // Warning : it's up to 'vtkgdcmSerieViewer' user to find a suitable data set !
491 // --------------------------------------------------------
492
493 bool userSuppliedLessThanFunction2(gdcm::File *f1, gdcm::File *f2)
494 {
495    std::cout << "[" << f1->GetFileName() << "] vs [" 
496                     << f2->GetFileName() << "]" << std::endl;
497    return f1->GetFileName() < f2->GetFileName();
498 }