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