]> Creatis software - gdcm.git/blob - Example/exExtractCSA.cxx
gdcm::
[gdcm.git] / Example / exExtractCSA.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: exExtractCSA.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/06/21 15:06:13 $
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
19 /*
20  * http://www.enac.northwestern.edu/~tew/archives/2003/02/25/incomplete-dicom-headers/
21  * http://www.nmr.mgh.harvard.edu/~rudolph/software/vox2ras/download/vox2ras_rsolve.m
22  * http://www.mail-archive.com/freesurfer@nmr.mgh.harvard.edu/msg03409.html
23  * http://www.mmrrcc.upenn.edu/CAMRIS/cfn/dicomhdr.html
24  */
25
26 // See this one :
27 // http://www.mmrrcc.upenn.edu/CAMRIS/cfn/dicomhdr.html
28
29 #include <iostream>
30 #include <fstream>
31 #include <stdint.h>
32 #include <assert.h>
33 #include <vector>
34 #include <map>
35
36 #include "gdcmFile.h"
37 #include "gdcmFileHelper.h"
38 #include "gdcmCommon.h"
39 #include "gdcmDebug.h"
40 #include "gdcmDocEntry.h"
41 #include "gdcmDataEntry.h"
42 #include "gdcmSeqEntry.h"
43 #include "gdcmSQItem.h"
44 #include "gdcmArgMgr.h"
45
46 // Looks like there is mapping in between syngodt and vr...
47 //  O <=> UN
48 //  3 <=> DS
49 //  4 <=> FD
50 //  5 <=> FL
51 //  6 <=> IS
52 //  9 <=> UL
53 // 10 <=> US
54 // 16 <=> CS
55 // 19 <=> LO
56 // 20 <=> LT
57 // 22 <=> SH
58 // 25 <=> UI
59
60 // --------------------------------------------------------
61
62 typedef struct {
63    uint32_t  Item_xx[4];
64    int Len;
65    std::string Value;
66 } CSA_item;
67
68 typedef std::vector<CSA_item *> ItemVector;
69
70 typedef struct {
71    std::string Name;
72    int VM;
73    std::string VR;
74    int Syngodt;
75    int Nitems;
76    ItemVector Items_set;   
77 } CSA_entry;
78
79 typedef std::map<std::string, CSA_entry *> CSA_content;
80
81 // --------------------------------------------------------
82
83
84 struct equ
85
86   uint32_t syngodt;
87   char vr[2+1];
88 };
89
90 static equ mapping[] = {
91   {  0 , "UN" },
92   {  3 , "DS" },
93   {  4 , "FD" },
94   {  5 , "FL" },
95   {  6 , "IS" },
96   {  9 , "UL" },
97   { 10 , "US" },
98   { 16 , "CS" },
99   { 19 , "LO" },
100   { 20 , "LT" },
101   { 22 , "SH" },
102   { 23 , "ST" },
103   { 25 , "UI" },
104 };
105
106 bool check_mapping(uint32_t syngodt, const char *vr)
107 {
108   static const unsigned int max = sizeof(mapping) / sizeof(equ);
109   unsigned int s = 0;
110   const equ *p = mapping;
111   assert( syngodt <= mapping[max-1].syngodt );
112   while(p->syngodt < syngodt )
113   {
114     //std::cout << "mapping:" << p->vr << std::endl;
115     ++p;
116   }
117   assert( p->syngodt == syngodt ); // or else need to update mapping
118   const char* lvr = p->vr;
119   int check = strcmp(vr, lvr) == 0;
120   assert( check );
121   return true;
122 }
123
124
125      ///\to  fix the Desctructor!
126 void  DeleteCSA_content (CSA_content &myMap) {
127    for ( CSA_content::const_iterator it = myMap.begin();
128                                     it != myMap.end();
129                                   ++it)
130    { 
131      ItemVector item_v = (*it).second->Items_set;
132      for ( ItemVector::const_iterator it2  = item_v.begin();
133                                       it2 != item_v.end();
134                                     ++it2)
135      {
136        // delete (*it2); 
137      }
138      //delete (*it).second;   
139    } 
140 }
141
142 void PrintCSA_content(CSA_content &myMap) {
143    int item_no;
144    for ( CSA_content::const_iterator it = myMap.begin();
145                                     it != myMap.end();
146                                   ++it)
147    { 
148      std::cout << "[" << (*it).second->Name << "] : VR=[" << (*it).second->VR 
149                << "] vm = " << (*it).second->VM << std::endl;
150      item_no = 0;
151      ItemVector item_v = (*it).second->Items_set;
152      for ( ItemVector::const_iterator it2 = item_v.begin();
153                                       it2 != item_v.end();
154                                     ++it2)
155      {
156        std::cout << "      --- item no : " << item_no << std::endl;
157        std::cout << "      Item_xxx : " << (*it2)->Item_xx[0] << " " 
158                  << (*it2)->Item_xx[1] 
159                  << " " << (*it2)->Item_xx[2] << " " << (*it2)->Item_xx[3] 
160                  << std::endl;
161     
162        std::cout << "      Len = " << (*it2)->Len ;
163        std::cout << "      Value = [" << (*it2)->Value << "]" << std::endl;
164    
165        item_no++;
166      } 
167    }
168 }
169
170 int main(int argc, char *argv[])
171 {
172    START_USAGE(usage)
173    "\n exExtractCSA :\n                                                       ",
174    "Extracts and displays the CSA tag(s) of gdcm-parsable Dicom file          ",
175    "                                                                          ",
176    "usage: exExtractCSA {filein=inputFileName|dirin=inputDirectoryName}       ",
177    "                   tmp=temporaryWorkFileName                              ",
178    "                       [extract=listOfElementsToExtract]                  ",
179    "                       [ { [noshadowseq] | [noshadow][noseq] } ] [debug]  ",
180    "       inputFileName : Name of the (single) file user wants to anonymize  ",
181    "       listOfElementsExtract : group-elem,g2-e2,... (in hexa, no space)   ",
182    "                                of Elements to extract                    ",
183    "                              default : 0029-1010,0029-1020               ",
184    "       noshadowseq: user doesn't want to load Private Sequences           ",
185    "       noshadow   : user doesn't want to load Private groups (odd number) ",
186    "       noseq      : user doesn't want to load Sequences                   ",
187    "       verbose    : developper wants to run the program in 'verbose mode' ",
188    "       debug      : developper wants to run the program in 'debug mode'   ",
189    FINISH_USAGE
190
191    // ----- Initialize Arguments Manager ------
192   
193    GDCM_NAME_SPACE::ArgMgr *am = new GDCM_NAME_SPACE::ArgMgr(argc, argv);
194   
195    if (am->ArgMgrDefined("usage") || argc == 1) 
196    {
197       am->ArgMgrUsage(usage); // Display 'usage'
198       delete am;
199       return 0;
200    }
201
202    if (am->ArgMgrDefined("debug"))
203       GDCM_NAME_SPACE::Debug::DebugOn();
204
205    bool verbose = am->ArgMgrDefined("verbose");
206    
207    const char *fileName = am->ArgMgrGetString("filein");
208
209    int loadMode = GDCM_NAME_SPACE::LD_ALL;
210    if ( am->ArgMgrDefined("noshadowseq") )
211       loadMode |= GDCM_NAME_SPACE::LD_NOSHADOWSEQ;
212    else 
213    {
214       if ( am->ArgMgrDefined("noshadow") )
215          loadMode |= GDCM_NAME_SPACE::LD_NOSHADOW;
216       if ( am->ArgMgrDefined("noseq") )
217          loadMode |= GDCM_NAME_SPACE::LD_NOSEQ;
218    }
219    
220    const char *tempWorkFile = am->ArgMgrGetString("tmp");
221
222    int extractNb;
223    uint16_t *elemsToExtract;
224    if (am->ArgMgrDefined("extract")) 
225    {
226       am->ArgMgrGetXInt16Enum("extract", &extractNb);
227       std::cout << "extractNb=" << extractNb << std::endl;
228       if (extractNb =! 0)
229          for (int k=0;k<extractNb; k++)
230             std::cout << std::hex << elemsToExtract[2*k] << "|" << elemsToExtract[2*k+1] <<std::endl;
231    }
232    else 
233    {
234      elemsToExtract = new  uint16_t[4];
235      elemsToExtract[0] = 0x0029;
236      elemsToExtract[1] = 0x1010;
237      elemsToExtract[2] = 0x0029;  
238      elemsToExtract[3] = 0x1020;
239      extractNb=2;
240    }     
241
242    /* if unused Param we give up */
243    if ( am->ArgMgrPrintUnusedLabels() )
244    {
245       am->ArgMgrUsage(usage);
246       delete am;
247       return 0;
248    }  
249    delete am;  // ------ we don't need Arguments Manager any longer ------
250
251 // ============================================================
252 //   Read the input image.
253 // ============================================================ 
254   
255    GDCM_NAME_SPACE::File *f = GDCM_NAME_SPACE::File::New( );
256
257    //f->SetLoadMode(GDCM_NAME_SPACE::LD_NOSEQ | GDCM_NAME_SPACE::LD_NOSHADOW);
258    f->SetFileName( fileName );
259    f->SetMaxSizeLoadEntry(0xffff);
260    bool res = f->Load();  
261
262    if( GDCM_NAME_SPACE::Debug::GetDebugFlag())
263    {
264       std::cout << "---------------------------------------------" << std::endl;
265       f->Print();
266       std::cout << "---------------------------------------------" << std::endl;
267    }
268    if (!res) {
269        std::cerr << "Sorry, " << fileName << " not a gdcm-readable "
270            << "DICOM / ACR File"
271            << std::endl;
272       f->Delete();
273       return 1;
274    }
275    std::cout << " ... is readable " << std::endl;
276    
277    
278 // --------------------------------------------------------
279 CSA_content myMap;
280 CSA_entry  *myEntry; 
281 CSA_item   *myItem;
282 // --------------------------------------------------------
283
284 // For each tag user wants to extract :
285
286 for (int tag_no=0; tag_no<extractNb; tag_no++) {
287
288    uint16_t group = elemsToExtract[2*tag_no];
289    uint16_t elem = elemsToExtract[2*tag_no+1];
290    
291    if (verbose)
292       std::cout << "Let's try tag : " << std::hex << group << "|" << elem << std::endl;
293       
294    std::string dicom_tag_value = f->GetEntryString(group, elem);
295    if (dicom_tag_value == GDCM_NAME_SPACE::GDCM_UNFOUND)
296    {
297      GDCM_NAME_SPACE::DictEntry *dictEntry = f->GetPubDict()->GetEntry( group, elem);
298      if (dictEntry != NULL)
299         std::cerr << "Image doesn't contain any tag: " << dictEntry->GetName() 
300                   << std::endl;
301      else
302         std::cerr << "Dicom Dictionary doesn't contain any tag: " 
303           << std::hex << group << "|" << elem << std::endl; 
304      f->Delete();
305      return 1;
306    }
307
308    GDCM_NAME_SPACE::DocEntry *dicom_tag_doc = f->GetDocEntry(group, elem);
309    GDCM_NAME_SPACE::DataEntry *dicom_tag = dynamic_cast<GDCM_NAME_SPACE::DataEntry *>(dicom_tag_doc);
310    if( !dicom_tag )
311    {
312       std::cerr << "Sorry DataEntry only please" << std::endl;
313       f->Delete();
314       return 1;
315    }
316
317    // Write out the data as a file:
318    std::ofstream o(tempWorkFile);
319    if( !o )
320    {
321       std::cerr << "Problem opening file: [" << tempWorkFile << "]" 
322                 << std::endl;
323       f->Delete();
324       return 1;
325    }
326    o.write((char*)dicom_tag->GetBinArea(), dicom_tag->GetLength());
327    o.close();
328    
329    
330 std::ifstream is( tempWorkFile );
331 char dummy[4+1];
332 dummy[4] = 0;
333 is.read(dummy, 4);
334 if (verbose)
335  std::cout << dummy << std::endl;
336 if( strcmp( dummy, "SV10" )  ) 
337 {
338    std::cerr << "Either not a SV10 header or filled with 0..." << std::endl;
339    return 1;
340 }
341 // wotsit ?
342 is.read(dummy, 4);
343 if( strcmp( dummy, "\4\3\2\1" )  ) 
344 {
345   std::cerr << "Either not a SV10 header or filled with 0..." << std::endl;
346   return 1;
347 }
348 if (verbose)
349    std::cout << (int)dummy[0] << (int)dummy[1] << (int)dummy[2] 
350              << (int)dummy[3]<< std::endl;
351 uint32_t n;
352 is.read((char*)&n, sizeof(n));
353 if (verbose)
354    std::cout << "number of entries " <<n << std::endl;
355 uint32_t unused;
356 is.read((char*)&unused, sizeof(unused));
357 if (verbose)
358    std::cout << "unused " << unused<< std::endl;
359 assert( unused == 77 ); // 'M' character...
360
361 for(uint32_t i = 0; i < n; ++i)
362 {
363 if (verbose)
364      std::cout << "============================================== " << i <<
365      std::endl;
366   char name[64+1];
367   name[64] = 0; // security
368   //std::cout << "Pos 0x" << std::hex << is.tellg() << std::dec << std::endl;
369   is.read(name, 64);
370 if (verbose)
371      std::cout << "Name=[" << name << "]" << std::endl;
372   uint32_t vm;
373   is.read((char*)&vm, sizeof(vm));
374 if (verbose)
375      std::cout << "vm=" << vm <<  std::endl;
376   char vr[4];
377   is.read(vr, 4);
378      assert( vr[2] == vr[3] && vr[2] == 0 );
379 if (verbose)
380      std::cout << "vr=[" << vr << "]" <<std::endl;
381   uint32_t syngodt;
382   is.read((char*)&syngodt, sizeof(syngodt));
383   check_mapping(syngodt, vr);
384
385 if (verbose)
386      std::cout << "syngodt=" << syngodt << std::endl;
387   uint32_t nitems;
388   is.read((char*)&nitems, sizeof(nitems));
389 if (verbose)
390      std::cout << "nitems=" << nitems<< std::endl;
391   uint32_t xx;
392   is.read((char*)&xx, sizeof(xx));
393   //std::cout << "xx=" << xx<< std::endl;
394   assert( xx == 77 || xx == 205 );
395
396   myEntry = new CSA_entry;
397   myEntry->Name    = name;
398   myEntry->VM      = vm;
399   myEntry->VR      = vr;
400   myEntry->Syngodt = syngodt;
401   myEntry->Nitems  = nitems;
402
403   for( uint32_t j = 0; j < nitems; ++j)
404   {
405 if (verbose)
406        std::cout << "-------------------------------------------- " << j
407                  << std::endl;
408     uint32_t item_xx[4];
409     is.read((char*)&item_xx, 4*sizeof(uint32_t));
410 if (verbose)
411        std::cout << std::dec 
412                  << "item_xx=" << item_xx[0] << " " << item_xx[1] << " " 
413                  << item_xx[2] << " " << item_xx[3] << std::endl;
414     //std::cout << "0x" << std::hex << is.tellg() << std::dec << std::endl;
415     assert( item_xx[2] == 77 || item_xx[2] == 205 );
416     uint32_t len = item_xx[1]; // 2nd element
417 if (verbose)
418        std::cout << "len=" << len << std::endl;
419     assert( item_xx[0] == item_xx[1] && item_xx[1] == item_xx[3] );
420     char *val = new char[len+1];
421     val[len] = 0; // security
422     is.read(val,len);
423     // WARNING vr does not means anything AFAIK, 
424     // simply print the value as if it was IS/DS or LO (ASCII)
425 if (verbose)
426      std::cout << "val=[" << val << "]" << std::endl;
427
428     char dummy[4];
429     uint32_t dummy_len = (4 - len % 4) % 4;
430     is.read(dummy, dummy_len );
431
432
433     for(uint32_t d= 0; d < dummy_len; ++d)
434     {
435      // I think dummy should always be 0
436       if( dummy[d] )
437       {
438 if (verbose)
439            std::cout << "dummy=" << (int)dummy[d] << std::endl;
440       }
441     }
442
443      myItem = new CSA_item;
444      for (int i2=0; i2<4; i2++)
445         myItem->Item_xx[i2] = item_xx[i2];
446      myItem->Len = len;
447      myItem->Value = val;
448      
449      myEntry->Items_set.push_back(myItem);
450      delete[] val;     
451
452    }
453    myMap[name] = myEntry;
454   }
455
456 std::cout << "================================================================"
457           << std::endl
458           << "=== Extract :" << std::hex << group << " " << elem  << "========"
459           << std::endl
460           << "================================================================"
461           << std::endl;
462
463   PrintCSA_content (myMap);
464   DeleteCSA_content (myMap);
465 }
466
467 f->Delete();   
468 return 0;
469 }