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