]> Creatis software - gdcm.git/blob - Example/ReWrite.cxx
Load *all* the fields
[gdcm.git] / Example / ReWrite.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: ReWrite.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/08/29 15:58:19 $
7   Version:   $Revision: 1.31 $
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 #include "gdcmFile.h"
19 #include "gdcmFileHelper.h"
20 #include "gdcmDebug.h"
21
22 #include "gdcmArgMgr.h"
23
24 #include <string.h> // for memcpy
25 #include <iostream>
26
27 int main(int argc, char *argv[])
28 {
29    START_USAGE(usage)
30    " \n ReWrite :\n",
31    " Re write a full gdcm-readable Dicom image                              ",
32    "     (usefull when the file header is not very straight).               ",
33    "                                                                        ",
34    " usage: ReWrite filein=inputFileName fileout=outputFileName             ", 
35    "       [mode=write mode] [monochrome1] [noshadow] [noseq][debug]        ",
36    "  --> The following line to 'rubout' a burnt-in Patient name            ",
37    "       [rubout=xBegin,xEnd,yBegin,yEnd [ruboutvalue=n (<255)] ]         ",
38    "  --> The 2 following lines, to extract a sub image within some frames  ",
39    "       [ROI=xBegin,xEnd,yBegin,yEnd]                                    ",
40    "       [firstframe=beg] [lastframe=end]                                 ", 
41    "                                                                        ",
42    "        mode = a (ACR), x (Explicit VR Dicom), r (RAW : only pixels)    ",
43    "               j (jpeg lossless), 2 (jpeg2000)                          ",
44    "        monochrome1 = user wants MONOCHROME1 photom. interp. (0=white)  ",
45    "        noshadowseq: user doesn't want to load Private Sequences        ",
46    "        noshadow : user doesn't want to load Private groups (odd number)",
47    "        noseq    : user doesn't want to load Sequences                  ",
48    "        rgb      : user wants to transform LUT (if any) to RGB pixels   ",
49    "        warning  : developper wants to run the program in 'warning mode'",
50    "        debug    : developper wants to run the program in 'debug mode'  ",
51    FINISH_USAGE
52
53    // ----- Initialize Arguments Manager ------  
54     
55    GDCM_NAME_SPACE::ArgMgr *am = new GDCM_NAME_SPACE::ArgMgr(argc, argv);
56   
57    if (argc == 1 || am->ArgMgrDefined("usage")) 
58    {
59       am->ArgMgrUsage(usage); // Display 'usage'
60       delete am;
61       return 1;
62    }
63    char *fileName = am->ArgMgrWantString("filein",usage);
64    if ( fileName == NULL )
65    {
66       std::cout << "'filein= ...' is mandatory" << std::endl;
67       delete am;
68       return 1;
69    }
70
71    char *outputFileName = am->ArgMgrWantString("fileout",usage);
72    if ( outputFileName == NULL )
73    {
74       std::cout << "'fileout= ...' is mandatory" << std::endl;
75       delete am;
76       return 1;
77    }
78
79    const char *mode = am->ArgMgrGetString("mode","X");
80
81    int loadMode = GDCM_NAME_SPACE::LD_ALL;
82    if ( am->ArgMgrDefined("noshadowseq") )
83       loadMode |= GDCM_NAME_SPACE::LD_NOSHADOWSEQ;
84    else 
85    {
86    if ( am->ArgMgrDefined("noshadow") )
87          loadMode |= GDCM_NAME_SPACE::LD_NOSHADOW;
88       if ( am->ArgMgrDefined("noseq") )
89          loadMode |= GDCM_NAME_SPACE::LD_NOSEQ;
90    }
91
92    bool rgb = ( 0 != am->ArgMgrDefined("RGB") );
93
94    bool monochrome1 = ( 0 != am->ArgMgrDefined("monochrome1") );
95    
96    if (am->ArgMgrDefined("debug"))
97       GDCM_NAME_SPACE::Debug::DebugOn();
98
99    if (am->ArgMgrDefined("warning"))
100       GDCM_NAME_SPACE::Debug::WarningOn();
101             
102    bool fail = false;
103    int *boundVal;
104    int ruboutVal;
105    bool rubout = false; 
106    if (am->ArgMgrDefined("rubout"))
107    {
108       int nbBound;
109       boundVal = am->ArgMgrGetListOfInt("rubout", &nbBound);
110
111       if (nbBound !=4)
112       {
113          std::cout << "Illegal number of 'rubout' boundary values (expected : 4, found:" 
114                    << nbBound << "); 'rubout' ignored" << std::endl;
115          fail = true;
116       }
117             
118       ruboutVal = am->ArgMgrGetInt("ruboutvalue", 0);
119       rubout = true;   
120    }
121
122    int *roiBoundVal;
123    bool roi = false; 
124    if (am->ArgMgrDefined("roi"))
125    {
126       int nbRoiBound;
127       roiBoundVal = am->ArgMgrGetListOfInt("roi", &nbRoiBound);
128
129       if (nbRoiBound !=4)
130       {
131         std::cout << "Illegal number of 'ROI' boundary values (expected : 4, found:" 
132                   << nbRoiBound << "); 'ROI' ignored" << std::endl;
133         fail = true;
134       }
135       else
136         roi = true;   
137    }
138   
139    int beg = am->ArgMgrGetInt("firstFrame",-1);
140    int end = am->ArgMgrGetInt("lastFrame",-1);
141  
142    // if unused Params we give up
143    if ( am->ArgMgrPrintUnusedLabels() )
144    { 
145       am->ArgMgrUsage(usage);
146       delete am;
147       return 0;
148    }
149
150    delete am;  // we don't need Argument Manager any longer
151
152    // ----------- End Arguments Manager ---------
153    GDCM_NAME_SPACE::File *f = GDCM_NAME_SPACE::File::New();
154    
155    f->SetMaxSizeLoadEntry(0x7fff);
156    
157    f->SetLoadMode( loadMode );
158
159    f->SetFileName( fileName );
160    bool res = f->Load();  
161       if ( !res )
162    {
163       f->Delete();
164       return 1;
165    }
166
167    if (!f->IsReadable())
168    {
169        std::cerr << "Sorry, not a Readable DICOM / ACR File"  <<std::endl;
170        f->Delete();
171        return 1;
172    }
173    
174    GDCM_NAME_SPACE::FileHelper *fh = GDCM_NAME_SPACE::FileHelper::New(f);
175    uint8_t *imageData; 
176    int dataSize;
177  
178    int nX,nY,nZ,sPP,planarConfig;
179    std::string pixelType, transferSyntaxName;
180    nX=f->GetXSize();
181    nY=f->GetYSize();
182    nZ=f->GetZSize();
183    
184    std::cout << " DIMX=" << nX << " DIMY=" << nY << " DIMZ=" << nZ << std::endl;
185
186    pixelType    = f->GetPixelType();
187    sPP          = f->GetSamplesPerPixel();
188    planarConfig = f->GetPlanarConfiguration();
189    
190    std::cout << " pixelType="           << pixelType 
191              << " SampleserPixel="      << sPP
192              << " PlanarConfiguration=" << planarConfig 
193              << " PhotometricInterpretation=" 
194              << f->GetEntryString(0x0028,0x0004) 
195              << std::endl;
196
197    int numberOfScalarComponents=f->GetNumberOfScalarComponents();
198    std::cout << "NumberOfScalarComponents " << numberOfScalarComponents 
199              <<std::endl;
200    transferSyntaxName = f->GetTransferSyntaxName();
201    std::cout << " TransferSyntaxName= [" << transferSyntaxName << "]" 
202              << std::endl;
203   
204    if(monochrome1)
205       fh->SetPhotometricInterpretationToMonochrome1();
206    
207    if (rgb)
208    {
209       dataSize  = fh->GetImageDataSize();
210       imageData = fh->GetImageData(); // somewhat important : Loads the Pixels in memory !
211       fh->SetWriteModeToRGB();
212    }
213    else
214    {
215       dataSize  = fh->GetImageDataRawSize();
216       imageData = fh->GetImageDataRaw();// somewhat important : Loads the Pixels in memory !
217       fh->SetWriteModeToRaw();
218    }
219
220    if ( imageData == 0 ) // to avoid warning
221    {
222       std::cout << "Was unable to read pixels " << std::endl;
223    }
224    printf(" dataSize %d imageData %p\n",dataSize, imageData);
225
226    // Since we just ReWrite the image, we know no modification 
227    // was performed on the pixels.
228    // We don't want this image appears as a 'Secondary Captured image'
229    fh->SetContentType(GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE);
230    
231
232    /// \todo : think about rubbing out a part of a *multiframe* image!
233    if (rubout)
234    {     
235       if (boundVal[0]<0 || boundVal[0]>nX)
236       { 
237          std::cout << "xBegin out of bounds; 'rubout' ignored" << std::endl;
238          fail = true;      
239       }
240       if (boundVal[1]<0 || boundVal[1]>nX)
241       { 
242          std::cout << "xEnd out of bounds; 'rubout' ignored" << std::endl;
243          fail = true;      
244       }
245       if (boundVal[0] > boundVal[1])
246       { 
247          std::cout << "xBegin greater than xEnd; 'rubout' ignored" << std::endl;
248          fail = true;      
249       }       
250       if (boundVal[2]<0 || boundVal[2]>nY)
251       { 
252          std::cout << "yBegin out of bounds; 'rubout' ignored" << std::endl;
253          fail = true;      
254       }
255       if (boundVal[3]<0 || boundVal[3]>nY)
256       { 
257          std::cout << "yEnd out of bounds; 'rubout' ignored" << std::endl;
258          fail = true;      
259       }
260       if (boundVal[2] > boundVal[3])
261       { 
262          std::cout << "yBegin greater than yEnd; 'rubout' ignored" << std::endl;
263          fail = true;      
264       }  
265       if (!fail)
266       {
267          int pixelLength = f->GetBitsAllocated()/8;
268          int lineLength = nX * sPP * pixelLength;
269          size_t lengthToRubout = (boundVal[1]-boundVal[0])*sPP*pixelLength;
270          int offsetToBeginOfRubout = boundVal[0]*sPP*pixelLength+lineLength*boundVal[2];
271       
272          for(int rbl=boundVal[2]; rbl<boundVal[3];rbl++)
273          {
274             memset((char *)imageData+offsetToBeginOfRubout, ruboutVal, lengthToRubout);
275             offsetToBeginOfRubout += lineLength; 
276          }
277       }   
278    } 
279
280
281 //------------------------------ Set the Writing mode ---------------------------------
282
283    switch (mode[0])
284    {
285       case 'A' :
286       case 'a' :
287       // Writting an ACR file
288       // from a full gdcm readable File
289          std::cout << "WriteACR" << std::endl;
290          fh->SetWriteTypeToAcr();
291          break;
292
293       case 'D' : // Not documented in the 'usage', because the method 
294       case 'd' : //                             is known to be bugged. 
295       // Writting a DICOM Implicit VR file
296       // from a full gdcm readable File
297          std::cout << "WriteDCM Implicit VR" << std::endl;
298          fh->SetWriteTypeToDcmImplVR(); 
299          break;
300
301       case 'X' :
302       case 'x' :
303       // writting a DICOM Explicit VR 
304       // from a full gdcm readable File
305          std::cout << "WriteDCM Explicit VR" << std::endl;
306          // fh->WriteDcmExplVR(outputFileName);
307          // Try this one :
308          fh->SetWriteTypeToDcmExplVR();
309
310          break;
311
312       case 'R' :
313       case 'r' :
314       //  Writting a Raw File, 
315          std::cout << "WriteRaw" << std::endl;
316          fh->WriteRawData(outputFileName);
317          break;
318  
319       case 'J' :
320       case 'j' :
321       // writting a DICOM Jpeg Lossless 
322       // from a full gdcm readable File
323          std::cout << "WriteDCM Jpeg Lossless" << std::endl;
324          fh->SetWriteTypeToJPEG();
325          break;
326
327       case '2' :
328       // writting a DICOM Jpeg 2000 
329       // from a full gdcm readable File
330          std::cout << "WriteDCM Jpeg 2000" << std::endl;
331          fh->SetWriteTypeToJPEG2000();
332          break; 
333  
334  // Just for fun :
335  // Write a 'Video inverse' version of the file.
336  // *Not* described, on purpose,  in the USAGE  
337       case 'V' :
338       case 'v' :
339          if ( fh->GetFile()->GetBitsAllocated() == 8)
340          {
341             std::cout << "videoinv for 8 bits" << std::endl;
342             for (int i=0; i<dataSize; i++) 
343             {
344                ((uint8_t*)imageData)[i] = 255 - ((uint8_t*)imageData)[i];
345             }
346          }
347          else
348          {
349             std::cout << "videoinv for 16 bits" << std::endl;    
350             for (int i=0; i<dataSize/2; i++) 
351             {
352                ((uint16_t*)imageData)[i] =  65535 - ((uint16_t*)imageData)[i];
353             }
354          }
355          std::cout << "WriteDCM Explicit VR + VideoInv" << std::endl;
356          fh->SetWriteTypeToDcmExplVR();
357          break;
358    }
359
360
361 //
362 // user wants to keep only a part of the image (ROI, and/or some frames)
363 // ---------------------------------------------------------------------
364 // (==> this is no longer really 'ReWrite' !)
365
366     int subImDimX = nX;
367     int subImDimY = nY;    
368
369     if (roi)
370     {  
371       if (roiBoundVal[0]<0 || roiBoundVal[0]>=nX)
372       { 
373          std::cout << "xBegin out of bounds; 'roi' ignored" << std::endl;
374          fail = true;      
375       }
376       if (roiBoundVal[1]<0 || roiBoundVal[1]>=nX)
377       { 
378          std::cout << "xEnd out of bounds; 'roi' ignored" << std::endl;
379          fail = true;      
380       }
381       if (roiBoundVal[0] > roiBoundVal[1])
382       { 
383          std::cout << "xBegin greater than xEnd; 'roi' ignored" << std::endl;
384          fail = true;      
385       }
386
387       if (roiBoundVal[2]<0 || roiBoundVal[2]>=nY)
388       { 
389          std::cout << "yBegin out of bounds; 'roi' ignored" << std::endl;
390          fail = true;      
391       }
392       if (roiBoundVal[3]<0 || roiBoundVal[3]>=nY)
393       { 
394          std::cout << "yEnd out of bounds; 'roi' ignored" << std::endl;
395          fail = true;      
396       }
397       if (roiBoundVal[2] > roiBoundVal[3])
398       { 
399          std::cout << "yBegin greater than yEnd; 'roi' ignored" << std::endl;
400          fail = true;      
401       }  
402    } 
403    else
404    {  
405      roiBoundVal = new int[4];
406      roiBoundVal[0] = 0;
407      roiBoundVal[1] = nX-1;
408      roiBoundVal[2] = 0;
409      roiBoundVal[3] = nY-1;  
410   }
411
412    subImDimX = roiBoundVal[1]-roiBoundVal[0]+1;     
413    subImDimY = roiBoundVal[3]-roiBoundVal[2]+1;  
414  
415   if (roi || beg != -1 || end != -1)
416   {  
417      if (beg == -1)
418         beg = 0;  
419      if (end == -1)
420         end = nZ-1;
421      
422      std::ostringstream str;
423      
424     // Set the data that will be *actually* written.
425
426      int pixelSize = fh->GetFile()->GetPixelSize();
427      size_t lgrSubLine  = subImDimX* pixelSize * numberOfScalarComponents;
428      size_t lgrSubFrame = subImDimY*lgrSubLine;
429                       ;
430      int lgrSubImage = (end-beg+1) * lgrSubFrame;
431        
432      uint8_t * subImage = new uint8_t[lgrSubImage];
433        
434      uint8_t * srcCopy = (uint8_t *) imageData;
435      uint8_t * destCopy = subImage;
436      int lineSize = nX*pixelSize*numberOfScalarComponents;
437      int frameSize = nY*lineSize; 
438  
439      int lineOffset = roiBoundVal[0]*pixelSize * numberOfScalarComponents;
440      
441      for (int frameNb=beg, frameCount=0; frameNb<=end; frameNb++, frameCount++)
442      { 
443         for (int lineNb=roiBoundVal[2], lineCount=0; lineNb<=roiBoundVal[3]; lineNb++, lineCount++)
444         {  
445             /// \todo : increment data pointer, don't multiply so much!
446             memcpy( (void *)(destCopy + frameCount*lgrSubFrame + lineCount*lgrSubLine), 
447                     (void *)(srcCopy  + frameNb*frameSize + lineNb*lineSize + lineOffset ), 
448                     lgrSubLine);
449         }        
450      }
451  
452     // Set the image size
453      str.str("");
454      str << subImDimX ;
455      fh->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
456
457      str.str("");
458      str << subImDimY;
459      fh->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
460      str.str("");
461      str << end-beg+1; 
462      fh->InsertEntryString(str.str(),0x0028,0x0008, "IS"); // Number of Frames 
463       
464      //fh->SetImageData(subImage,lgrSubImage);
465       fh->SetUserData(subImage,lgrSubImage);   // ensures the compression (if any)    
466   }
467   else
468   {         
469       fh->SetUserData(imageData,dataSize); // ensures the compression (if any) 
470   }
471
472
473
474 //----------------------------------- Write, now! ---------------------------------
475
476    if (mode[0] != 'R' && mode[0] != 'r')
477       fh->Write(outputFileName);
478
479    f->Delete();
480    fh->Delete();
481    return 0;
482 }
483
484