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