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